PackageManagerService.java revision b5a564a05645cd95ba9833b0fa804cd98f192c6b
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.MANAGE_DEVICE_ADMINS; 21import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS; 22import static android.Manifest.permission.INSTALL_PACKAGES; 23import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS; 24import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 25import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 26import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 27import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509; 28import static android.content.pm.PackageManager.CERT_INPUT_SHA256; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 34import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 39import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 42import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 43import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 44import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 52import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 53import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 54import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 55import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 59import static android.content.pm.PackageManager.INSTALL_INTERNAL; 60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 66import static android.content.pm.PackageManager.MATCH_ALL; 67import static android.content.pm.PackageManager.MATCH_ANY_USER; 68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER; 81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 83import static android.content.pm.PackageManager.PERMISSION_DENIED; 84import static android.content.pm.PackageManager.PERMISSION_GRANTED; 85import static android.content.pm.PackageParser.isApkFile; 86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 87import static android.os.storage.StorageManager.FLAG_STORAGE_CE; 88import static android.os.storage.StorageManager.FLAG_STORAGE_DE; 89import static android.system.OsConstants.O_CREAT; 90import static android.system.OsConstants.O_RDWR; 91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 95import static com.android.internal.util.ArrayUtils.appendInt; 96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 102import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures; 103import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists; 104import static com.android.server.pm.PackageManagerServiceUtils.decompressFile; 105import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride; 106import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo; 107import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles; 108import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime; 109import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo; 110import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures; 111import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE; 112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS; 113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 114 115import android.Manifest; 116import android.annotation.IntDef; 117import android.annotation.NonNull; 118import android.annotation.Nullable; 119import android.annotation.UserIdInt; 120import android.app.ActivityManager; 121import android.app.ActivityManagerInternal; 122import android.app.AppOpsManager; 123import android.app.IActivityManager; 124import android.app.ResourcesManager; 125import android.app.admin.IDevicePolicyManager; 126import android.app.admin.SecurityLog; 127import android.app.backup.IBackupManager; 128import android.content.BroadcastReceiver; 129import android.content.ComponentName; 130import android.content.ContentResolver; 131import android.content.Context; 132import android.content.IIntentReceiver; 133import android.content.Intent; 134import android.content.IntentFilter; 135import android.content.IntentSender; 136import android.content.IntentSender.SendIntentException; 137import android.content.ServiceConnection; 138import android.content.pm.ActivityInfo; 139import android.content.pm.ApplicationInfo; 140import android.content.pm.AppsQueryHelper; 141import android.content.pm.AuxiliaryResolveInfo; 142import android.content.pm.ChangedPackages; 143import android.content.pm.ComponentInfo; 144import android.content.pm.FallbackCategoryProvider; 145import android.content.pm.FeatureInfo; 146import android.content.pm.IDexModuleRegisterCallback; 147import android.content.pm.IOnPermissionsChangeListener; 148import android.content.pm.IPackageDataObserver; 149import android.content.pm.IPackageDeleteObserver; 150import android.content.pm.IPackageDeleteObserver2; 151import android.content.pm.IPackageInstallObserver2; 152import android.content.pm.IPackageInstaller; 153import android.content.pm.IPackageManager; 154import android.content.pm.IPackageManagerNative; 155import android.content.pm.IPackageMoveObserver; 156import android.content.pm.IPackageStatsObserver; 157import android.content.pm.InstantAppInfo; 158import android.content.pm.InstantAppRequest; 159import android.content.pm.InstantAppResolveInfo; 160import android.content.pm.InstrumentationInfo; 161import android.content.pm.IntentFilterVerificationInfo; 162import android.content.pm.KeySet; 163import android.content.pm.PackageCleanItem; 164import android.content.pm.PackageInfo; 165import android.content.pm.PackageInfoLite; 166import android.content.pm.PackageInstaller; 167import android.content.pm.PackageList; 168import android.content.pm.PackageManager; 169import android.content.pm.PackageManagerInternal; 170import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 171import android.content.pm.PackageManagerInternal.PackageListObserver; 172import android.content.pm.PackageParser; 173import android.content.pm.PackageParser.ActivityIntentInfo; 174import android.content.pm.PackageParser.Package; 175import android.content.pm.PackageParser.PackageLite; 176import android.content.pm.PackageParser.PackageParserException; 177import android.content.pm.PackageParser.ParseFlags; 178import android.content.pm.PackageParser.ServiceIntentInfo; 179import android.content.pm.PackageParser.SigningDetails; 180import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion; 181import android.content.pm.PackageStats; 182import android.content.pm.PackageUserState; 183import android.content.pm.ParceledListSlice; 184import android.content.pm.PermissionGroupInfo; 185import android.content.pm.PermissionInfo; 186import android.content.pm.ProviderInfo; 187import android.content.pm.ResolveInfo; 188import android.content.pm.ServiceInfo; 189import android.content.pm.SharedLibraryInfo; 190import android.content.pm.Signature; 191import android.content.pm.UserInfo; 192import android.content.pm.VerifierDeviceIdentity; 193import android.content.pm.VerifierInfo; 194import android.content.pm.VersionedPackage; 195import android.content.pm.dex.ArtManager; 196import android.content.pm.dex.DexMetadataHelper; 197import android.content.pm.dex.IArtManager; 198import android.content.res.Resources; 199import android.database.ContentObserver; 200import android.graphics.Bitmap; 201import android.hardware.display.DisplayManager; 202import android.net.Uri; 203import android.os.Binder; 204import android.os.Build; 205import android.os.Bundle; 206import android.os.Debug; 207import android.os.Environment; 208import android.os.Environment.UserEnvironment; 209import android.os.FileUtils; 210import android.os.Handler; 211import android.os.IBinder; 212import android.os.Looper; 213import android.os.Message; 214import android.os.Parcel; 215import android.os.ParcelFileDescriptor; 216import android.os.PatternMatcher; 217import android.os.PersistableBundle; 218import android.os.Process; 219import android.os.RemoteCallbackList; 220import android.os.RemoteException; 221import android.os.ResultReceiver; 222import android.os.SELinux; 223import android.os.ServiceManager; 224import android.os.ShellCallback; 225import android.os.SystemClock; 226import android.os.SystemProperties; 227import android.os.Trace; 228import android.os.UserHandle; 229import android.os.UserManager; 230import android.os.UserManagerInternal; 231import android.os.storage.IStorageManager; 232import android.os.storage.StorageEventListener; 233import android.os.storage.StorageManager; 234import android.os.storage.StorageManagerInternal; 235import android.os.storage.VolumeInfo; 236import android.os.storage.VolumeRecord; 237import android.provider.Settings.Global; 238import android.provider.Settings.Secure; 239import android.security.KeyStore; 240import android.security.SystemKeyStore; 241import android.service.pm.PackageServiceDumpProto; 242import android.system.ErrnoException; 243import android.system.Os; 244import android.text.TextUtils; 245import android.text.format.DateUtils; 246import android.util.ArrayMap; 247import android.util.ArraySet; 248import android.util.Base64; 249import android.util.ByteStringUtils; 250import android.util.DisplayMetrics; 251import android.util.EventLog; 252import android.util.ExceptionUtils; 253import android.util.Log; 254import android.util.LogPrinter; 255import android.util.LongSparseArray; 256import android.util.LongSparseLongArray; 257import android.util.MathUtils; 258import android.util.PackageUtils; 259import android.util.Pair; 260import android.util.PrintStreamPrinter; 261import android.util.Slog; 262import android.util.SparseArray; 263import android.util.SparseBooleanArray; 264import android.util.SparseIntArray; 265import android.util.TimingsTraceLog; 266import android.util.Xml; 267import android.util.jar.StrictJarFile; 268import android.util.proto.ProtoOutputStream; 269import android.view.Display; 270 271import com.android.internal.R; 272import com.android.internal.annotations.GuardedBy; 273import com.android.internal.app.IMediaContainerService; 274import com.android.internal.app.ResolverActivity; 275import com.android.internal.content.NativeLibraryHelper; 276import com.android.internal.content.PackageHelper; 277import com.android.internal.logging.MetricsLogger; 278import com.android.internal.os.IParcelFileDescriptorFactory; 279import com.android.internal.os.SomeArgs; 280import com.android.internal.os.Zygote; 281import com.android.internal.telephony.CarrierAppUtils; 282import com.android.internal.util.ArrayUtils; 283import com.android.internal.util.ConcurrentUtils; 284import com.android.internal.util.DumpUtils; 285import com.android.internal.util.FastXmlSerializer; 286import com.android.internal.util.IndentingPrintWriter; 287import com.android.internal.util.Preconditions; 288import com.android.internal.util.XmlUtils; 289import com.android.server.AttributeCache; 290import com.android.server.DeviceIdleController; 291import com.android.server.EventLogTags; 292import com.android.server.FgThread; 293import com.android.server.IntentResolver; 294import com.android.server.LocalServices; 295import com.android.server.LockGuard; 296import com.android.server.ServiceThread; 297import com.android.server.SystemConfig; 298import com.android.server.SystemServerInitThreadPool; 299import com.android.server.Watchdog; 300import com.android.server.net.NetworkPolicyManagerInternal; 301import com.android.server.pm.Installer.InstallerException; 302import com.android.server.pm.Settings.DatabaseVersion; 303import com.android.server.pm.Settings.VersionInfo; 304import com.android.server.pm.dex.ArtManagerService; 305import com.android.server.pm.dex.DexLogger; 306import com.android.server.pm.dex.DexManager; 307import com.android.server.pm.dex.DexoptOptions; 308import com.android.server.pm.dex.PackageDexUsage; 309import com.android.server.pm.permission.BasePermission; 310import com.android.server.pm.permission.DefaultPermissionGrantPolicy; 311import com.android.server.pm.permission.PermissionManagerService; 312import com.android.server.pm.permission.PermissionManagerInternal; 313import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback; 314import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback; 315import com.android.server.pm.permission.PermissionsState; 316import com.android.server.pm.permission.PermissionsState.PermissionState; 317import com.android.server.security.VerityUtils; 318import com.android.server.storage.DeviceStorageMonitorInternal; 319 320import dalvik.system.CloseGuard; 321import dalvik.system.VMRuntime; 322 323import libcore.io.IoUtils; 324 325import org.xmlpull.v1.XmlPullParser; 326import org.xmlpull.v1.XmlPullParserException; 327import org.xmlpull.v1.XmlSerializer; 328 329import java.io.BufferedOutputStream; 330import java.io.ByteArrayInputStream; 331import java.io.ByteArrayOutputStream; 332import java.io.File; 333import java.io.FileDescriptor; 334import java.io.FileInputStream; 335import java.io.FileOutputStream; 336import java.io.FilenameFilter; 337import java.io.IOException; 338import java.io.PrintWriter; 339import java.lang.annotation.Retention; 340import java.lang.annotation.RetentionPolicy; 341import java.nio.charset.StandardCharsets; 342import java.security.DigestException; 343import java.security.DigestInputStream; 344import java.security.MessageDigest; 345import java.security.NoSuchAlgorithmException; 346import java.security.PublicKey; 347import java.security.SecureRandom; 348import java.security.cert.CertificateException; 349import java.util.ArrayList; 350import java.util.Arrays; 351import java.util.Collection; 352import java.util.Collections; 353import java.util.Comparator; 354import java.util.HashMap; 355import java.util.HashSet; 356import java.util.Iterator; 357import java.util.LinkedHashSet; 358import java.util.List; 359import java.util.Map; 360import java.util.Objects; 361import java.util.Set; 362import java.util.concurrent.CountDownLatch; 363import java.util.concurrent.Future; 364import java.util.concurrent.TimeUnit; 365import java.util.concurrent.atomic.AtomicBoolean; 366import java.util.concurrent.atomic.AtomicInteger; 367 368/** 369 * Keep track of all those APKs everywhere. 370 * <p> 371 * Internally there are two important locks: 372 * <ul> 373 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 374 * and other related state. It is a fine-grained lock that should only be held 375 * momentarily, as it's one of the most contended locks in the system. 376 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 377 * operations typically involve heavy lifting of application data on disk. Since 378 * {@code installd} is single-threaded, and it's operations can often be slow, 379 * this lock should never be acquired while already holding {@link #mPackages}. 380 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 381 * holding {@link #mInstallLock}. 382 * </ul> 383 * Many internal methods rely on the caller to hold the appropriate locks, and 384 * this contract is expressed through method name suffixes: 385 * <ul> 386 * <li>fooLI(): the caller must hold {@link #mInstallLock} 387 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 388 * being modified must be frozen 389 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 390 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 391 * </ul> 392 * <p> 393 * Because this class is very central to the platform's security; please run all 394 * CTS and unit tests whenever making modifications: 395 * 396 * <pre> 397 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 398 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 399 * </pre> 400 */ 401public class PackageManagerService extends IPackageManager.Stub 402 implements PackageSender { 403 static final String TAG = "PackageManager"; 404 public static final boolean DEBUG_SETTINGS = false; 405 static final boolean DEBUG_PREFERRED = false; 406 static final boolean DEBUG_UPGRADE = false; 407 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 408 private static final boolean DEBUG_BACKUP = false; 409 public static final boolean DEBUG_INSTALL = false; 410 public static final boolean DEBUG_REMOVE = true; 411 private static final boolean DEBUG_BROADCASTS = false; 412 private static final boolean DEBUG_SHOW_INFO = false; 413 private static final boolean DEBUG_PACKAGE_INFO = false; 414 private static final boolean DEBUG_INTENT_MATCHING = false; 415 public static final boolean DEBUG_PACKAGE_SCANNING = false; 416 private static final boolean DEBUG_VERIFY = false; 417 private static final boolean DEBUG_FILTERS = false; 418 public static final boolean DEBUG_PERMISSIONS = false; 419 private static final boolean DEBUG_SHARED_LIBRARIES = false; 420 public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE; 421 422 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 423 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 424 // user, but by default initialize to this. 425 public static final boolean DEBUG_DEXOPT = false; 426 427 private static final boolean DEBUG_ABI_SELECTION = false; 428 private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE; 429 private static final boolean DEBUG_TRIAGED_MISSING = false; 430 private static final boolean DEBUG_APP_DATA = false; 431 432 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 433 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 434 435 private static final boolean HIDE_EPHEMERAL_APIS = false; 436 437 private static final boolean ENABLE_FREE_CACHE_V2 = 438 SystemProperties.getBoolean("fw.free_cache_v2", true); 439 440 private static final int RADIO_UID = Process.PHONE_UID; 441 private static final int LOG_UID = Process.LOG_UID; 442 private static final int NFC_UID = Process.NFC_UID; 443 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 444 private static final int SHELL_UID = Process.SHELL_UID; 445 private static final int SE_UID = Process.SE_UID; 446 447 // Suffix used during package installation when copying/moving 448 // package apks to install directory. 449 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 450 451 static final int SCAN_NO_DEX = 1<<0; 452 static final int SCAN_UPDATE_SIGNATURE = 1<<1; 453 static final int SCAN_NEW_INSTALL = 1<<2; 454 static final int SCAN_UPDATE_TIME = 1<<3; 455 static final int SCAN_BOOTING = 1<<4; 456 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6; 457 static final int SCAN_REQUIRE_KNOWN = 1<<7; 458 static final int SCAN_MOVE = 1<<8; 459 static final int SCAN_INITIAL = 1<<9; 460 static final int SCAN_CHECK_ONLY = 1<<10; 461 static final int SCAN_DONT_KILL_APP = 1<<11; 462 static final int SCAN_IGNORE_FROZEN = 1<<12; 463 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13; 464 static final int SCAN_AS_INSTANT_APP = 1<<14; 465 static final int SCAN_AS_FULL_APP = 1<<15; 466 static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16; 467 static final int SCAN_AS_SYSTEM = 1<<17; 468 static final int SCAN_AS_PRIVILEGED = 1<<18; 469 static final int SCAN_AS_OEM = 1<<19; 470 static final int SCAN_AS_VENDOR = 1<<20; 471 static final int SCAN_AS_PRODUCT = 1<<21; 472 473 @IntDef(flag = true, prefix = { "SCAN_" }, value = { 474 SCAN_NO_DEX, 475 SCAN_UPDATE_SIGNATURE, 476 SCAN_NEW_INSTALL, 477 SCAN_UPDATE_TIME, 478 SCAN_BOOTING, 479 SCAN_DELETE_DATA_ON_FAILURES, 480 SCAN_REQUIRE_KNOWN, 481 SCAN_MOVE, 482 SCAN_INITIAL, 483 SCAN_CHECK_ONLY, 484 SCAN_DONT_KILL_APP, 485 SCAN_IGNORE_FROZEN, 486 SCAN_FIRST_BOOT_OR_UPGRADE, 487 SCAN_AS_INSTANT_APP, 488 SCAN_AS_FULL_APP, 489 SCAN_AS_VIRTUAL_PRELOAD, 490 }) 491 @Retention(RetentionPolicy.SOURCE) 492 public @interface ScanFlags {} 493 494 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 495 /** Extension of the compressed packages */ 496 public final static String COMPRESSED_EXTENSION = ".gz"; 497 /** Suffix of stub packages on the system partition */ 498 public final static String STUB_SUFFIX = "-Stub"; 499 500 private static final int[] EMPTY_INT_ARRAY = new int[0]; 501 502 private static final int TYPE_UNKNOWN = 0; 503 private static final int TYPE_ACTIVITY = 1; 504 private static final int TYPE_RECEIVER = 2; 505 private static final int TYPE_SERVICE = 3; 506 private static final int TYPE_PROVIDER = 4; 507 @IntDef(prefix = { "TYPE_" }, value = { 508 TYPE_UNKNOWN, 509 TYPE_ACTIVITY, 510 TYPE_RECEIVER, 511 TYPE_SERVICE, 512 TYPE_PROVIDER, 513 }) 514 @Retention(RetentionPolicy.SOURCE) 515 public @interface ComponentType {} 516 517 /** 518 * Timeout (in milliseconds) after which the watchdog should declare that 519 * our handler thread is wedged. The usual default for such things is one 520 * minute but we sometimes do very lengthy I/O operations on this thread, 521 * such as installing multi-gigabyte applications, so ours needs to be longer. 522 */ 523 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 524 525 /** 526 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 527 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 528 * settings entry if available, otherwise we use the hardcoded default. If it's been 529 * more than this long since the last fstrim, we force one during the boot sequence. 530 * 531 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 532 * one gets run at the next available charging+idle time. This final mandatory 533 * no-fstrim check kicks in only of the other scheduling criteria is never met. 534 */ 535 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 536 537 /** 538 * Whether verification is enabled by default. 539 */ 540 private static final boolean DEFAULT_VERIFY_ENABLE = true; 541 542 /** 543 * The default maximum time to wait for the verification agent to return in 544 * milliseconds. 545 */ 546 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 547 548 /** 549 * The default response for package verification timeout. 550 * 551 * This can be either PackageManager.VERIFICATION_ALLOW or 552 * PackageManager.VERIFICATION_REJECT. 553 */ 554 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 555 556 public static final String PLATFORM_PACKAGE_NAME = "android"; 557 558 public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 559 560 public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 561 DEFAULT_CONTAINER_PACKAGE, 562 "com.android.defcontainer.DefaultContainerService"); 563 564 private static final String KILL_APP_REASON_GIDS_CHANGED = 565 "permission grant or revoke changed gids"; 566 567 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 568 "permissions revoked"; 569 570 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 571 572 private static final String PACKAGE_SCHEME = "package"; 573 574 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 575 576 private static final String PRODUCT_OVERLAY_DIR = "/product/overlay"; 577 578 private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob"; 579 580 /** Canonical intent used to identify what counts as a "web browser" app */ 581 private static final Intent sBrowserIntent; 582 static { 583 sBrowserIntent = new Intent(); 584 sBrowserIntent.setAction(Intent.ACTION_VIEW); 585 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 586 sBrowserIntent.setData(Uri.parse("http:")); 587 sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL); 588 } 589 590 /** 591 * The set of all protected actions [i.e. those actions for which a high priority 592 * intent filter is disallowed]. 593 */ 594 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 595 static { 596 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 597 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 598 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 599 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 600 } 601 602 // Compilation reasons. 603 public static final int REASON_UNKNOWN = -1; 604 public static final int REASON_FIRST_BOOT = 0; 605 public static final int REASON_BOOT = 1; 606 public static final int REASON_INSTALL = 2; 607 public static final int REASON_BACKGROUND_DEXOPT = 3; 608 public static final int REASON_AB_OTA = 4; 609 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5; 610 public static final int REASON_SHARED = 6; 611 612 public static final int REASON_LAST = REASON_SHARED; 613 614 /** 615 * Version number for the package parser cache. Increment this whenever the format or 616 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 617 */ 618 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 619 620 /** 621 * Whether the package parser cache is enabled. 622 */ 623 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 624 625 /** 626 * Permissions required in order to receive instant application lifecycle broadcasts. 627 */ 628 private static final String[] INSTANT_APP_BROADCAST_PERMISSION = 629 new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS }; 630 631 final ServiceThread mHandlerThread; 632 633 final PackageHandler mHandler; 634 635 private final ProcessLoggingHandler mProcessLoggingHandler; 636 637 /** 638 * Messages for {@link #mHandler} that need to wait for system ready before 639 * being dispatched. 640 */ 641 private ArrayList<Message> mPostSystemReadyMessages; 642 643 final int mSdkVersion = Build.VERSION.SDK_INT; 644 645 final Context mContext; 646 final boolean mFactoryTest; 647 final boolean mOnlyCore; 648 final DisplayMetrics mMetrics; 649 final int mDefParseFlags; 650 final String[] mSeparateProcesses; 651 final boolean mIsUpgrade; 652 final boolean mIsPreNUpgrade; 653 final boolean mIsPreNMR1Upgrade; 654 655 // Have we told the Activity Manager to whitelist the default container service by uid yet? 656 @GuardedBy("mPackages") 657 boolean mDefaultContainerWhitelisted = false; 658 659 @GuardedBy("mPackages") 660 private boolean mDexOptDialogShown; 661 662 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 663 // LOCK HELD. Can be called with mInstallLock held. 664 @GuardedBy("mInstallLock") 665 final Installer mInstaller; 666 667 /** Directory where installed applications are stored */ 668 private static final File sAppInstallDir = 669 new File(Environment.getDataDirectory(), "app"); 670 /** Directory where installed application's 32-bit native libraries are copied. */ 671 private static final File sAppLib32InstallDir = 672 new File(Environment.getDataDirectory(), "app-lib"); 673 /** Directory where code and non-resource assets of forward-locked applications are stored */ 674 private static final File sDrmAppPrivateInstallDir = 675 new File(Environment.getDataDirectory(), "app-private"); 676 677 // ---------------------------------------------------------------- 678 679 // Lock for state used when installing and doing other long running 680 // operations. Methods that must be called with this lock held have 681 // the suffix "LI". 682 final Object mInstallLock = new Object(); 683 684 // ---------------------------------------------------------------- 685 686 // Keys are String (package name), values are Package. This also serves 687 // as the lock for the global state. Methods that must be called with 688 // this lock held have the prefix "LP". 689 @GuardedBy("mPackages") 690 final ArrayMap<String, PackageParser.Package> mPackages = 691 new ArrayMap<String, PackageParser.Package>(); 692 693 final ArrayMap<String, Set<String>> mKnownCodebase = 694 new ArrayMap<String, Set<String>>(); 695 696 // Keys are isolated uids and values are the uid of the application 697 // that created the isolated proccess. 698 @GuardedBy("mPackages") 699 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 700 701 /** 702 * Tracks new system packages [received in an OTA] that we expect to 703 * find updated user-installed versions. Keys are package name, values 704 * are package location. 705 */ 706 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 707 /** 708 * Tracks high priority intent filters for protected actions. During boot, certain 709 * filter actions are protected and should never be allowed to have a high priority 710 * intent filter for them. However, there is one, and only one exception -- the 711 * setup wizard. It must be able to define a high priority intent filter for these 712 * actions to ensure there are no escapes from the wizard. We need to delay processing 713 * of these during boot as we need to look at all of the system packages in order 714 * to know which component is the setup wizard. 715 */ 716 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 717 /** 718 * Whether or not processing protected filters should be deferred. 719 */ 720 private boolean mDeferProtectedFilters = true; 721 722 /** 723 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 724 */ 725 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 726 /** 727 * Whether or not system app permissions should be promoted from install to runtime. 728 */ 729 boolean mPromoteSystemApps; 730 731 @GuardedBy("mPackages") 732 final Settings mSettings; 733 734 /** 735 * Set of package names that are currently "frozen", which means active 736 * surgery is being done on the code/data for that package. The platform 737 * will refuse to launch frozen packages to avoid race conditions. 738 * 739 * @see PackageFreezer 740 */ 741 @GuardedBy("mPackages") 742 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 743 744 final ProtectedPackages mProtectedPackages; 745 746 @GuardedBy("mLoadedVolumes") 747 final ArraySet<String> mLoadedVolumes = new ArraySet<>(); 748 749 boolean mFirstBoot; 750 751 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 752 753 @GuardedBy("mAvailableFeatures") 754 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 755 756 private final InstantAppRegistry mInstantAppRegistry; 757 758 @GuardedBy("mPackages") 759 int mChangedPackagesSequenceNumber; 760 /** 761 * List of changed [installed, removed or updated] packages. 762 * mapping from user id -> sequence number -> package name 763 */ 764 @GuardedBy("mPackages") 765 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 766 /** 767 * The sequence number of the last change to a package. 768 * mapping from user id -> package name -> sequence number 769 */ 770 @GuardedBy("mPackages") 771 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 772 773 @GuardedBy("mPackages") 774 final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>(); 775 776 class PackageParserCallback implements PackageParser.Callback { 777 @Override public final boolean hasFeature(String feature) { 778 return PackageManagerService.this.hasSystemFeature(feature, 0); 779 } 780 781 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 782 Collection<PackageParser.Package> allPackages, String targetPackageName) { 783 List<PackageParser.Package> overlayPackages = null; 784 for (PackageParser.Package p : allPackages) { 785 if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) { 786 if (overlayPackages == null) { 787 overlayPackages = new ArrayList<PackageParser.Package>(); 788 } 789 overlayPackages.add(p); 790 } 791 } 792 if (overlayPackages != null) { 793 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 794 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 795 return p1.mOverlayPriority - p2.mOverlayPriority; 796 } 797 }; 798 Collections.sort(overlayPackages, cmp); 799 } 800 return overlayPackages; 801 } 802 803 @GuardedBy("mInstallLock") 804 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 805 String targetPackageName, String targetPath) { 806 if ("android".equals(targetPackageName)) { 807 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 808 // native AssetManager. 809 return null; 810 } 811 List<PackageParser.Package> overlayPackages = 812 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 813 if (overlayPackages == null || overlayPackages.isEmpty()) { 814 return null; 815 } 816 List<String> overlayPathList = null; 817 for (PackageParser.Package overlayPackage : overlayPackages) { 818 if (targetPath == null) { 819 if (overlayPathList == null) { 820 overlayPathList = new ArrayList<String>(); 821 } 822 overlayPathList.add(overlayPackage.baseCodePath); 823 continue; 824 } 825 826 try { 827 // Creates idmaps for system to parse correctly the Android manifest of the 828 // target package. 829 // 830 // OverlayManagerService will update each of them with a correct gid from its 831 // target package app id. 832 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 833 UserHandle.getSharedAppGid( 834 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 835 if (overlayPathList == null) { 836 overlayPathList = new ArrayList<String>(); 837 } 838 overlayPathList.add(overlayPackage.baseCodePath); 839 } catch (InstallerException e) { 840 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 841 overlayPackage.baseCodePath); 842 } 843 } 844 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 845 } 846 847 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 848 synchronized (mPackages) { 849 return getStaticOverlayPathsLocked( 850 mPackages.values(), targetPackageName, targetPath); 851 } 852 } 853 854 @Override public final String[] getOverlayApks(String targetPackageName) { 855 return getStaticOverlayPaths(targetPackageName, null); 856 } 857 858 @Override public final String[] getOverlayPaths(String targetPackageName, 859 String targetPath) { 860 return getStaticOverlayPaths(targetPackageName, targetPath); 861 } 862 } 863 864 class ParallelPackageParserCallback extends PackageParserCallback { 865 List<PackageParser.Package> mOverlayPackages = null; 866 867 void findStaticOverlayPackages() { 868 synchronized (mPackages) { 869 for (PackageParser.Package p : mPackages.values()) { 870 if (p.mOverlayIsStatic) { 871 if (mOverlayPackages == null) { 872 mOverlayPackages = new ArrayList<PackageParser.Package>(); 873 } 874 mOverlayPackages.add(p); 875 } 876 } 877 } 878 } 879 880 @Override 881 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 882 // We can trust mOverlayPackages without holding mPackages because package uninstall 883 // can't happen while running parallel parsing. 884 // Moreover holding mPackages on each parsing thread causes dead-lock. 885 return mOverlayPackages == null ? null : 886 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 887 } 888 } 889 890 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 891 final ParallelPackageParserCallback mParallelPackageParserCallback = 892 new ParallelPackageParserCallback(); 893 894 public static final class SharedLibraryEntry { 895 public final @Nullable String path; 896 public final @Nullable String apk; 897 public final @NonNull SharedLibraryInfo info; 898 899 SharedLibraryEntry(String _path, String _apk, String name, long version, int type, 900 String declaringPackageName, long declaringPackageVersionCode) { 901 path = _path; 902 apk = _apk; 903 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 904 declaringPackageName, declaringPackageVersionCode), null); 905 } 906 } 907 908 // Currently known shared libraries. 909 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 910 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 911 new ArrayMap<>(); 912 913 // All available activities, for your resolving pleasure. 914 final ActivityIntentResolver mActivities = 915 new ActivityIntentResolver(); 916 917 // All available receivers, for your resolving pleasure. 918 final ActivityIntentResolver mReceivers = 919 new ActivityIntentResolver(); 920 921 // All available services, for your resolving pleasure. 922 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 923 924 // All available providers, for your resolving pleasure. 925 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 926 927 // Mapping from provider base names (first directory in content URI codePath) 928 // to the provider information. 929 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 930 new ArrayMap<String, PackageParser.Provider>(); 931 932 // Mapping from instrumentation class names to info about them. 933 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 934 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 935 936 // Packages whose data we have transfered into another package, thus 937 // should no longer exist. 938 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 939 940 // Broadcast actions that are only available to the system. 941 @GuardedBy("mProtectedBroadcasts") 942 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>(); 943 944 /** List of packages waiting for verification. */ 945 final SparseArray<PackageVerificationState> mPendingVerification 946 = new SparseArray<PackageVerificationState>(); 947 948 final PackageInstallerService mInstallerService; 949 950 final ArtManagerService mArtManagerService; 951 952 private final PackageDexOptimizer mPackageDexOptimizer; 953 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 954 // is used by other apps). 955 private final DexManager mDexManager; 956 957 private AtomicInteger mNextMoveId = new AtomicInteger(); 958 private final MoveCallbacks mMoveCallbacks; 959 960 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 961 962 // Cache of users who need badging. 963 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 964 965 /** Token for keys in mPendingVerification. */ 966 private int mPendingVerificationToken = 0; 967 968 volatile boolean mSystemReady; 969 volatile boolean mSafeMode; 970 volatile boolean mHasSystemUidErrors; 971 private volatile boolean mWebInstantAppsDisabled; 972 973 ApplicationInfo mAndroidApplication; 974 final ActivityInfo mResolveActivity = new ActivityInfo(); 975 final ResolveInfo mResolveInfo = new ResolveInfo(); 976 ComponentName mResolveComponentName; 977 PackageParser.Package mPlatformPackage; 978 ComponentName mCustomResolverComponentName; 979 980 boolean mResolverReplaced = false; 981 982 private final @Nullable ComponentName mIntentFilterVerifierComponent; 983 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 984 985 private int mIntentFilterVerificationToken = 0; 986 987 /** The service connection to the ephemeral resolver */ 988 final InstantAppResolverConnection mInstantAppResolverConnection; 989 /** Component used to show resolver settings for Instant Apps */ 990 final ComponentName mInstantAppResolverSettingsComponent; 991 992 /** Activity used to install instant applications */ 993 ActivityInfo mInstantAppInstallerActivity; 994 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 995 996 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 997 = new SparseArray<IntentFilterVerificationState>(); 998 999 // TODO remove this and go through mPermissonManager directly 1000 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 1001 private final PermissionManagerInternal mPermissionManager; 1002 1003 // List of packages names to keep cached, even if they are uninstalled for all users 1004 private List<String> mKeepUninstalledPackages; 1005 1006 private UserManagerInternal mUserManagerInternal; 1007 private ActivityManagerInternal mActivityManagerInternal; 1008 1009 private DeviceIdleController.LocalService mDeviceIdleController; 1010 1011 private File mCacheDir; 1012 1013 private Future<?> mPrepareAppDataFuture; 1014 1015 private static class IFVerificationParams { 1016 PackageParser.Package pkg; 1017 boolean replacing; 1018 int userId; 1019 int verifierUid; 1020 1021 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1022 int _userId, int _verifierUid) { 1023 pkg = _pkg; 1024 replacing = _replacing; 1025 userId = _userId; 1026 replacing = _replacing; 1027 verifierUid = _verifierUid; 1028 } 1029 } 1030 1031 private interface IntentFilterVerifier<T extends IntentFilter> { 1032 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1033 T filter, String packageName); 1034 void startVerifications(int userId); 1035 void receiveVerificationResponse(int verificationId); 1036 } 1037 1038 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1039 private Context mContext; 1040 private ComponentName mIntentFilterVerifierComponent; 1041 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1042 1043 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1044 mContext = context; 1045 mIntentFilterVerifierComponent = verifierComponent; 1046 } 1047 1048 private String getDefaultScheme() { 1049 return IntentFilter.SCHEME_HTTPS; 1050 } 1051 1052 @Override 1053 public void startVerifications(int userId) { 1054 // Launch verifications requests 1055 int count = mCurrentIntentFilterVerifications.size(); 1056 for (int n=0; n<count; n++) { 1057 int verificationId = mCurrentIntentFilterVerifications.get(n); 1058 final IntentFilterVerificationState ivs = 1059 mIntentFilterVerificationStates.get(verificationId); 1060 1061 String packageName = ivs.getPackageName(); 1062 1063 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1064 final int filterCount = filters.size(); 1065 ArraySet<String> domainsSet = new ArraySet<>(); 1066 for (int m=0; m<filterCount; m++) { 1067 PackageParser.ActivityIntentInfo filter = filters.get(m); 1068 domainsSet.addAll(filter.getHostsList()); 1069 } 1070 synchronized (mPackages) { 1071 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1072 packageName, domainsSet) != null) { 1073 scheduleWriteSettingsLocked(); 1074 } 1075 } 1076 sendVerificationRequest(verificationId, ivs); 1077 } 1078 mCurrentIntentFilterVerifications.clear(); 1079 } 1080 1081 private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) { 1082 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1083 verificationIntent.putExtra( 1084 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1085 verificationId); 1086 verificationIntent.putExtra( 1087 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1088 getDefaultScheme()); 1089 verificationIntent.putExtra( 1090 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1091 ivs.getHostsString()); 1092 verificationIntent.putExtra( 1093 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1094 ivs.getPackageName()); 1095 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1096 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1097 1098 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1099 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1100 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1101 UserHandle.USER_SYSTEM, true, "intent filter verifier"); 1102 1103 mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM); 1104 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1105 "Sending IntentFilter verification broadcast"); 1106 } 1107 1108 public void receiveVerificationResponse(int verificationId) { 1109 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1110 1111 final boolean verified = ivs.isVerified(); 1112 1113 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1114 final int count = filters.size(); 1115 if (DEBUG_DOMAIN_VERIFICATION) { 1116 Slog.i(TAG, "Received verification response " + verificationId 1117 + " for " + count + " filters, verified=" + verified); 1118 } 1119 for (int n=0; n<count; n++) { 1120 PackageParser.ActivityIntentInfo filter = filters.get(n); 1121 filter.setVerified(verified); 1122 1123 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1124 + " verified with result:" + verified + " and hosts:" 1125 + ivs.getHostsString()); 1126 } 1127 1128 mIntentFilterVerificationStates.remove(verificationId); 1129 1130 final String packageName = ivs.getPackageName(); 1131 IntentFilterVerificationInfo ivi = null; 1132 1133 synchronized (mPackages) { 1134 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1135 } 1136 if (ivi == null) { 1137 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1138 + verificationId + " packageName:" + packageName); 1139 return; 1140 } 1141 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1142 "Updating IntentFilterVerificationInfo for package " + packageName 1143 +" verificationId:" + verificationId); 1144 1145 synchronized (mPackages) { 1146 if (verified) { 1147 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1148 } else { 1149 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1150 } 1151 scheduleWriteSettingsLocked(); 1152 1153 final int userId = ivs.getUserId(); 1154 if (userId != UserHandle.USER_ALL) { 1155 final int userStatus = 1156 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1157 1158 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1159 boolean needUpdate = false; 1160 1161 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1162 // already been set by the User thru the Disambiguation dialog 1163 switch (userStatus) { 1164 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1165 if (verified) { 1166 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1167 } else { 1168 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1169 } 1170 needUpdate = true; 1171 break; 1172 1173 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1174 if (verified) { 1175 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1176 needUpdate = true; 1177 } 1178 break; 1179 1180 default: 1181 // Nothing to do 1182 } 1183 1184 if (needUpdate) { 1185 mSettings.updateIntentFilterVerificationStatusLPw( 1186 packageName, updatedStatus, userId); 1187 scheduleWritePackageRestrictionsLocked(userId); 1188 } 1189 } 1190 } 1191 } 1192 1193 @Override 1194 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1195 ActivityIntentInfo filter, String packageName) { 1196 if (!hasValidDomains(filter)) { 1197 return false; 1198 } 1199 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1200 if (ivs == null) { 1201 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1202 packageName); 1203 } 1204 if (DEBUG_DOMAIN_VERIFICATION) { 1205 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1206 } 1207 ivs.addFilter(filter); 1208 return true; 1209 } 1210 1211 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1212 int userId, int verificationId, String packageName) { 1213 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1214 verifierUid, userId, packageName); 1215 ivs.setPendingState(); 1216 synchronized (mPackages) { 1217 mIntentFilterVerificationStates.append(verificationId, ivs); 1218 mCurrentIntentFilterVerifications.add(verificationId); 1219 } 1220 return ivs; 1221 } 1222 } 1223 1224 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1225 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1226 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1227 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1228 } 1229 1230 // Set of pending broadcasts for aggregating enable/disable of components. 1231 static class PendingPackageBroadcasts { 1232 // for each user id, a map of <package name -> components within that package> 1233 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1234 1235 public PendingPackageBroadcasts() { 1236 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1237 } 1238 1239 public ArrayList<String> get(int userId, String packageName) { 1240 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1241 return packages.get(packageName); 1242 } 1243 1244 public void put(int userId, String packageName, ArrayList<String> components) { 1245 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1246 packages.put(packageName, components); 1247 } 1248 1249 public void remove(int userId, String packageName) { 1250 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1251 if (packages != null) { 1252 packages.remove(packageName); 1253 } 1254 } 1255 1256 public void remove(int userId) { 1257 mUidMap.remove(userId); 1258 } 1259 1260 public int userIdCount() { 1261 return mUidMap.size(); 1262 } 1263 1264 public int userIdAt(int n) { 1265 return mUidMap.keyAt(n); 1266 } 1267 1268 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1269 return mUidMap.get(userId); 1270 } 1271 1272 public int size() { 1273 // total number of pending broadcast entries across all userIds 1274 int num = 0; 1275 for (int i = 0; i< mUidMap.size(); i++) { 1276 num += mUidMap.valueAt(i).size(); 1277 } 1278 return num; 1279 } 1280 1281 public void clear() { 1282 mUidMap.clear(); 1283 } 1284 1285 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1286 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1287 if (map == null) { 1288 map = new ArrayMap<String, ArrayList<String>>(); 1289 mUidMap.put(userId, map); 1290 } 1291 return map; 1292 } 1293 } 1294 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1295 1296 // Service Connection to remote media container service to copy 1297 // package uri's from external media onto secure containers 1298 // or internal storage. 1299 private IMediaContainerService mContainerService = null; 1300 1301 static final int SEND_PENDING_BROADCAST = 1; 1302 static final int MCS_BOUND = 3; 1303 static final int END_COPY = 4; 1304 static final int INIT_COPY = 5; 1305 static final int MCS_UNBIND = 6; 1306 static final int START_CLEANING_PACKAGE = 7; 1307 static final int FIND_INSTALL_LOC = 8; 1308 static final int POST_INSTALL = 9; 1309 static final int MCS_RECONNECT = 10; 1310 static final int MCS_GIVE_UP = 11; 1311 static final int WRITE_SETTINGS = 13; 1312 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1313 static final int PACKAGE_VERIFIED = 15; 1314 static final int CHECK_PENDING_VERIFICATION = 16; 1315 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1316 static final int INTENT_FILTER_VERIFIED = 18; 1317 static final int WRITE_PACKAGE_LIST = 19; 1318 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1319 1320 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1321 1322 // Delay time in millisecs 1323 static final int BROADCAST_DELAY = 10 * 1000; 1324 1325 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1326 2 * 60 * 60 * 1000L; /* two hours */ 1327 1328 static UserManagerService sUserManager; 1329 1330 // Stores a list of users whose package restrictions file needs to be updated 1331 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1332 1333 final private DefaultContainerConnection mDefContainerConn = 1334 new DefaultContainerConnection(); 1335 class DefaultContainerConnection implements ServiceConnection { 1336 public void onServiceConnected(ComponentName name, IBinder service) { 1337 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1338 final IMediaContainerService imcs = IMediaContainerService.Stub 1339 .asInterface(Binder.allowBlocking(service)); 1340 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1341 } 1342 1343 public void onServiceDisconnected(ComponentName name) { 1344 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1345 } 1346 } 1347 1348 // Recordkeeping of restore-after-install operations that are currently in flight 1349 // between the Package Manager and the Backup Manager 1350 static class PostInstallData { 1351 public InstallArgs args; 1352 public PackageInstalledInfo res; 1353 1354 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1355 args = _a; 1356 res = _r; 1357 } 1358 } 1359 1360 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1361 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1362 1363 // XML tags for backup/restore of various bits of state 1364 private static final String TAG_PREFERRED_BACKUP = "pa"; 1365 private static final String TAG_DEFAULT_APPS = "da"; 1366 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1367 1368 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1369 private static final String TAG_ALL_GRANTS = "rt-grants"; 1370 private static final String TAG_GRANT = "grant"; 1371 private static final String ATTR_PACKAGE_NAME = "pkg"; 1372 1373 private static final String TAG_PERMISSION = "perm"; 1374 private static final String ATTR_PERMISSION_NAME = "name"; 1375 private static final String ATTR_IS_GRANTED = "g"; 1376 private static final String ATTR_USER_SET = "set"; 1377 private static final String ATTR_USER_FIXED = "fixed"; 1378 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1379 1380 // System/policy permission grants are not backed up 1381 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1382 FLAG_PERMISSION_POLICY_FIXED 1383 | FLAG_PERMISSION_SYSTEM_FIXED 1384 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1385 1386 // And we back up these user-adjusted states 1387 private static final int USER_RUNTIME_GRANT_MASK = 1388 FLAG_PERMISSION_USER_SET 1389 | FLAG_PERMISSION_USER_FIXED 1390 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1391 1392 final @Nullable String mRequiredVerifierPackage; 1393 final @NonNull String mRequiredInstallerPackage; 1394 final @NonNull String mRequiredUninstallerPackage; 1395 final @Nullable String mSetupWizardPackage; 1396 final @Nullable String mStorageManagerPackage; 1397 final @Nullable String mSystemTextClassifierPackage; 1398 final @NonNull String mServicesSystemSharedLibraryPackageName; 1399 final @NonNull String mSharedSystemSharedLibraryPackageName; 1400 1401 private final PackageUsage mPackageUsage = new PackageUsage(); 1402 private final CompilerStats mCompilerStats = new CompilerStats(); 1403 1404 class PackageHandler extends Handler { 1405 private boolean mBound = false; 1406 final ArrayList<HandlerParams> mPendingInstalls = 1407 new ArrayList<HandlerParams>(); 1408 1409 private boolean connectToService() { 1410 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1411 " DefaultContainerService"); 1412 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1414 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1415 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1416 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1417 mBound = true; 1418 return true; 1419 } 1420 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1421 return false; 1422 } 1423 1424 private void disconnectService() { 1425 mContainerService = null; 1426 mBound = false; 1427 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1428 mContext.unbindService(mDefContainerConn); 1429 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1430 } 1431 1432 PackageHandler(Looper looper) { 1433 super(looper); 1434 } 1435 1436 public void handleMessage(Message msg) { 1437 try { 1438 doHandleMessage(msg); 1439 } finally { 1440 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1441 } 1442 } 1443 1444 void doHandleMessage(Message msg) { 1445 switch (msg.what) { 1446 case INIT_COPY: { 1447 HandlerParams params = (HandlerParams) msg.obj; 1448 int idx = mPendingInstalls.size(); 1449 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1450 // If a bind was already initiated we dont really 1451 // need to do anything. The pending install 1452 // will be processed later on. 1453 if (!mBound) { 1454 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1455 System.identityHashCode(mHandler)); 1456 // If this is the only one pending we might 1457 // have to bind to the service again. 1458 if (!connectToService()) { 1459 Slog.e(TAG, "Failed to bind to media container service"); 1460 params.serviceError(); 1461 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1462 System.identityHashCode(mHandler)); 1463 if (params.traceMethod != null) { 1464 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1465 params.traceCookie); 1466 } 1467 return; 1468 } else { 1469 // Once we bind to the service, the first 1470 // pending request will be processed. 1471 mPendingInstalls.add(idx, params); 1472 } 1473 } else { 1474 mPendingInstalls.add(idx, params); 1475 // Already bound to the service. Just make 1476 // sure we trigger off processing the first request. 1477 if (idx == 0) { 1478 mHandler.sendEmptyMessage(MCS_BOUND); 1479 } 1480 } 1481 break; 1482 } 1483 case MCS_BOUND: { 1484 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1485 if (msg.obj != null) { 1486 mContainerService = (IMediaContainerService) msg.obj; 1487 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1488 System.identityHashCode(mHandler)); 1489 } 1490 if (mContainerService == null) { 1491 if (!mBound) { 1492 // Something seriously wrong since we are not bound and we are not 1493 // waiting for connection. Bail out. 1494 Slog.e(TAG, "Cannot bind to media container service"); 1495 for (HandlerParams params : mPendingInstalls) { 1496 // Indicate service bind error 1497 params.serviceError(); 1498 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1499 System.identityHashCode(params)); 1500 if (params.traceMethod != null) { 1501 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1502 params.traceMethod, params.traceCookie); 1503 } 1504 return; 1505 } 1506 mPendingInstalls.clear(); 1507 } else { 1508 Slog.w(TAG, "Waiting to connect to media container service"); 1509 } 1510 } else if (mPendingInstalls.size() > 0) { 1511 HandlerParams params = mPendingInstalls.get(0); 1512 if (params != null) { 1513 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1514 System.identityHashCode(params)); 1515 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1516 if (params.startCopy()) { 1517 // We are done... look for more work or to 1518 // go idle. 1519 if (DEBUG_SD_INSTALL) Log.i(TAG, 1520 "Checking for more work or unbind..."); 1521 // Delete pending install 1522 if (mPendingInstalls.size() > 0) { 1523 mPendingInstalls.remove(0); 1524 } 1525 if (mPendingInstalls.size() == 0) { 1526 if (mBound) { 1527 if (DEBUG_SD_INSTALL) Log.i(TAG, 1528 "Posting delayed MCS_UNBIND"); 1529 removeMessages(MCS_UNBIND); 1530 Message ubmsg = obtainMessage(MCS_UNBIND); 1531 // Unbind after a little delay, to avoid 1532 // continual thrashing. 1533 sendMessageDelayed(ubmsg, 10000); 1534 } 1535 } else { 1536 // There are more pending requests in queue. 1537 // Just post MCS_BOUND message to trigger processing 1538 // of next pending install. 1539 if (DEBUG_SD_INSTALL) Log.i(TAG, 1540 "Posting MCS_BOUND for next work"); 1541 mHandler.sendEmptyMessage(MCS_BOUND); 1542 } 1543 } 1544 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1545 } 1546 } else { 1547 // Should never happen ideally. 1548 Slog.w(TAG, "Empty queue"); 1549 } 1550 break; 1551 } 1552 case MCS_RECONNECT: { 1553 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1554 if (mPendingInstalls.size() > 0) { 1555 if (mBound) { 1556 disconnectService(); 1557 } 1558 if (!connectToService()) { 1559 Slog.e(TAG, "Failed to bind to media container service"); 1560 for (HandlerParams params : mPendingInstalls) { 1561 // Indicate service bind error 1562 params.serviceError(); 1563 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1564 System.identityHashCode(params)); 1565 } 1566 mPendingInstalls.clear(); 1567 } 1568 } 1569 break; 1570 } 1571 case MCS_UNBIND: { 1572 // If there is no actual work left, then time to unbind. 1573 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1574 1575 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1576 if (mBound) { 1577 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1578 1579 disconnectService(); 1580 } 1581 } else if (mPendingInstalls.size() > 0) { 1582 // There are more pending requests in queue. 1583 // Just post MCS_BOUND message to trigger processing 1584 // of next pending install. 1585 mHandler.sendEmptyMessage(MCS_BOUND); 1586 } 1587 1588 break; 1589 } 1590 case MCS_GIVE_UP: { 1591 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1592 HandlerParams params = mPendingInstalls.remove(0); 1593 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1594 System.identityHashCode(params)); 1595 break; 1596 } 1597 case SEND_PENDING_BROADCAST: { 1598 String packages[]; 1599 ArrayList<String> components[]; 1600 int size = 0; 1601 int uids[]; 1602 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1603 synchronized (mPackages) { 1604 if (mPendingBroadcasts == null) { 1605 return; 1606 } 1607 size = mPendingBroadcasts.size(); 1608 if (size <= 0) { 1609 // Nothing to be done. Just return 1610 return; 1611 } 1612 packages = new String[size]; 1613 components = new ArrayList[size]; 1614 uids = new int[size]; 1615 int i = 0; // filling out the above arrays 1616 1617 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1618 int packageUserId = mPendingBroadcasts.userIdAt(n); 1619 Iterator<Map.Entry<String, ArrayList<String>>> it 1620 = mPendingBroadcasts.packagesForUserId(packageUserId) 1621 .entrySet().iterator(); 1622 while (it.hasNext() && i < size) { 1623 Map.Entry<String, ArrayList<String>> ent = it.next(); 1624 packages[i] = ent.getKey(); 1625 components[i] = ent.getValue(); 1626 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1627 uids[i] = (ps != null) 1628 ? UserHandle.getUid(packageUserId, ps.appId) 1629 : -1; 1630 i++; 1631 } 1632 } 1633 size = i; 1634 mPendingBroadcasts.clear(); 1635 } 1636 // Send broadcasts 1637 for (int i = 0; i < size; i++) { 1638 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1639 } 1640 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1641 break; 1642 } 1643 case START_CLEANING_PACKAGE: { 1644 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1645 final String packageName = (String)msg.obj; 1646 final int userId = msg.arg1; 1647 final boolean andCode = msg.arg2 != 0; 1648 synchronized (mPackages) { 1649 if (userId == UserHandle.USER_ALL) { 1650 int[] users = sUserManager.getUserIds(); 1651 for (int user : users) { 1652 mSettings.addPackageToCleanLPw( 1653 new PackageCleanItem(user, packageName, andCode)); 1654 } 1655 } else { 1656 mSettings.addPackageToCleanLPw( 1657 new PackageCleanItem(userId, packageName, andCode)); 1658 } 1659 } 1660 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1661 startCleaningPackages(); 1662 } break; 1663 case POST_INSTALL: { 1664 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1665 1666 PostInstallData data = mRunningInstalls.get(msg.arg1); 1667 final boolean didRestore = (msg.arg2 != 0); 1668 mRunningInstalls.delete(msg.arg1); 1669 1670 if (data != null) { 1671 InstallArgs args = data.args; 1672 PackageInstalledInfo parentRes = data.res; 1673 1674 final boolean grantPermissions = (args.installFlags 1675 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1676 final boolean killApp = (args.installFlags 1677 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1678 final boolean virtualPreload = ((args.installFlags 1679 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 1680 final String[] grantedPermissions = args.installGrantPermissions; 1681 1682 // Handle the parent package 1683 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1684 virtualPreload, grantedPermissions, didRestore, 1685 args.installerPackageName, args.observer); 1686 1687 // Handle the child packages 1688 final int childCount = (parentRes.addedChildPackages != null) 1689 ? parentRes.addedChildPackages.size() : 0; 1690 for (int i = 0; i < childCount; i++) { 1691 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1692 handlePackagePostInstall(childRes, grantPermissions, killApp, 1693 virtualPreload, grantedPermissions, false /*didRestore*/, 1694 args.installerPackageName, args.observer); 1695 } 1696 1697 // Log tracing if needed 1698 if (args.traceMethod != null) { 1699 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1700 args.traceCookie); 1701 } 1702 } else { 1703 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1704 } 1705 1706 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1707 } break; 1708 case WRITE_SETTINGS: { 1709 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1710 synchronized (mPackages) { 1711 removeMessages(WRITE_SETTINGS); 1712 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1713 mSettings.writeLPr(); 1714 mDirtyUsers.clear(); 1715 } 1716 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1717 } break; 1718 case WRITE_PACKAGE_RESTRICTIONS: { 1719 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1720 synchronized (mPackages) { 1721 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1722 for (int userId : mDirtyUsers) { 1723 mSettings.writePackageRestrictionsLPr(userId); 1724 } 1725 mDirtyUsers.clear(); 1726 } 1727 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1728 } break; 1729 case WRITE_PACKAGE_LIST: { 1730 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1731 synchronized (mPackages) { 1732 removeMessages(WRITE_PACKAGE_LIST); 1733 mSettings.writePackageListLPr(msg.arg1); 1734 } 1735 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1736 } break; 1737 case CHECK_PENDING_VERIFICATION: { 1738 final int verificationId = msg.arg1; 1739 final PackageVerificationState state = mPendingVerification.get(verificationId); 1740 1741 if ((state != null) && !state.timeoutExtended()) { 1742 final InstallArgs args = state.getInstallArgs(); 1743 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1744 1745 Slog.i(TAG, "Verification timed out for " + originUri); 1746 mPendingVerification.remove(verificationId); 1747 1748 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1749 1750 final UserHandle user = args.getUser(); 1751 if (getDefaultVerificationResponse(user) 1752 == PackageManager.VERIFICATION_ALLOW) { 1753 Slog.i(TAG, "Continuing with installation of " + originUri); 1754 state.setVerifierResponse(Binder.getCallingUid(), 1755 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1756 broadcastPackageVerified(verificationId, originUri, 1757 PackageManager.VERIFICATION_ALLOW, user); 1758 try { 1759 ret = args.copyApk(mContainerService, true); 1760 } catch (RemoteException e) { 1761 Slog.e(TAG, "Could not contact the ContainerService"); 1762 } 1763 } else { 1764 broadcastPackageVerified(verificationId, originUri, 1765 PackageManager.VERIFICATION_REJECT, user); 1766 } 1767 1768 Trace.asyncTraceEnd( 1769 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1770 1771 processPendingInstall(args, ret); 1772 mHandler.sendEmptyMessage(MCS_UNBIND); 1773 } 1774 break; 1775 } 1776 case PACKAGE_VERIFIED: { 1777 final int verificationId = msg.arg1; 1778 1779 final PackageVerificationState state = mPendingVerification.get(verificationId); 1780 if (state == null) { 1781 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1782 break; 1783 } 1784 1785 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1786 1787 state.setVerifierResponse(response.callerUid, response.code); 1788 1789 if (state.isVerificationComplete()) { 1790 mPendingVerification.remove(verificationId); 1791 1792 final InstallArgs args = state.getInstallArgs(); 1793 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1794 1795 int ret; 1796 if (state.isInstallAllowed()) { 1797 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1798 broadcastPackageVerified(verificationId, originUri, 1799 response.code, state.getInstallArgs().getUser()); 1800 try { 1801 ret = args.copyApk(mContainerService, true); 1802 } catch (RemoteException e) { 1803 Slog.e(TAG, "Could not contact the ContainerService"); 1804 } 1805 } else { 1806 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1807 } 1808 1809 Trace.asyncTraceEnd( 1810 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1811 1812 processPendingInstall(args, ret); 1813 mHandler.sendEmptyMessage(MCS_UNBIND); 1814 } 1815 1816 break; 1817 } 1818 case START_INTENT_FILTER_VERIFICATIONS: { 1819 IFVerificationParams params = (IFVerificationParams) msg.obj; 1820 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1821 params.replacing, params.pkg); 1822 break; 1823 } 1824 case INTENT_FILTER_VERIFIED: { 1825 final int verificationId = msg.arg1; 1826 1827 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1828 verificationId); 1829 if (state == null) { 1830 Slog.w(TAG, "Invalid IntentFilter verification token " 1831 + verificationId + " received"); 1832 break; 1833 } 1834 1835 final int userId = state.getUserId(); 1836 1837 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1838 "Processing IntentFilter verification with token:" 1839 + verificationId + " and userId:" + userId); 1840 1841 final IntentFilterVerificationResponse response = 1842 (IntentFilterVerificationResponse) msg.obj; 1843 1844 state.setVerifierResponse(response.callerUid, response.code); 1845 1846 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1847 "IntentFilter verification with token:" + verificationId 1848 + " and userId:" + userId 1849 + " is settings verifier response with response code:" 1850 + response.code); 1851 1852 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1853 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1854 + response.getFailedDomainsString()); 1855 } 1856 1857 if (state.isVerificationComplete()) { 1858 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1859 } else { 1860 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1861 "IntentFilter verification with token:" + verificationId 1862 + " was not said to be complete"); 1863 } 1864 1865 break; 1866 } 1867 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1868 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1869 mInstantAppResolverConnection, 1870 (InstantAppRequest) msg.obj, 1871 mInstantAppInstallerActivity, 1872 mHandler); 1873 } 1874 } 1875 } 1876 } 1877 1878 private PermissionCallback mPermissionCallback = new PermissionCallback() { 1879 @Override 1880 public void onGidsChanged(int appId, int userId) { 1881 mHandler.post(new Runnable() { 1882 @Override 1883 public void run() { 1884 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 1885 } 1886 }); 1887 } 1888 @Override 1889 public void onPermissionGranted(int uid, int userId) { 1890 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1891 1892 // Not critical; if this is lost, the application has to request again. 1893 synchronized (mPackages) { 1894 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 1895 } 1896 } 1897 @Override 1898 public void onInstallPermissionGranted() { 1899 synchronized (mPackages) { 1900 scheduleWriteSettingsLocked(); 1901 } 1902 } 1903 @Override 1904 public void onPermissionRevoked(int uid, int userId) { 1905 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1906 1907 synchronized (mPackages) { 1908 // Critical; after this call the application should never have the permission 1909 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 1910 } 1911 1912 final int appId = UserHandle.getAppId(uid); 1913 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 1914 } 1915 @Override 1916 public void onInstallPermissionRevoked() { 1917 synchronized (mPackages) { 1918 scheduleWriteSettingsLocked(); 1919 } 1920 } 1921 @Override 1922 public void onPermissionUpdated(int[] updatedUserIds, boolean sync) { 1923 synchronized (mPackages) { 1924 for (int userId : updatedUserIds) { 1925 mSettings.writeRuntimePermissionsForUserLPr(userId, sync); 1926 } 1927 } 1928 } 1929 @Override 1930 public void onInstallPermissionUpdated() { 1931 synchronized (mPackages) { 1932 scheduleWriteSettingsLocked(); 1933 } 1934 } 1935 @Override 1936 public void onPermissionRemoved() { 1937 synchronized (mPackages) { 1938 mSettings.writeLPr(); 1939 } 1940 } 1941 }; 1942 1943 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1944 boolean killApp, boolean virtualPreload, String[] grantedPermissions, 1945 boolean launchedForRestore, String installerPackage, 1946 IPackageInstallObserver2 installObserver) { 1947 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1948 // Send the removed broadcasts 1949 if (res.removedInfo != null) { 1950 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1951 } 1952 1953 // Now that we successfully installed the package, grant runtime 1954 // permissions if requested before broadcasting the install. Also 1955 // for legacy apps in permission review mode we clear the permission 1956 // review flag which is used to emulate runtime permissions for 1957 // legacy apps. 1958 if (grantPermissions) { 1959 final int callingUid = Binder.getCallingUid(); 1960 mPermissionManager.grantRequestedRuntimePermissions( 1961 res.pkg, res.newUsers, grantedPermissions, callingUid, 1962 mPermissionCallback); 1963 } 1964 1965 final boolean update = res.removedInfo != null 1966 && res.removedInfo.removedPackage != null; 1967 final String installerPackageName = 1968 res.installerPackageName != null 1969 ? res.installerPackageName 1970 : res.removedInfo != null 1971 ? res.removedInfo.installerPackageName 1972 : null; 1973 1974 // If this is the first time we have child packages for a disabled privileged 1975 // app that had no children, we grant requested runtime permissions to the new 1976 // children if the parent on the system image had them already granted. 1977 if (res.pkg.parentPackage != null) { 1978 final int callingUid = Binder.getCallingUid(); 1979 mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage( 1980 res.pkg, callingUid, mPermissionCallback); 1981 } 1982 1983 synchronized (mPackages) { 1984 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1985 } 1986 1987 final String packageName = res.pkg.applicationInfo.packageName; 1988 1989 // Determine the set of users who are adding this package for 1990 // the first time vs. those who are seeing an update. 1991 int[] firstUserIds = EMPTY_INT_ARRAY; 1992 int[] firstInstantUserIds = EMPTY_INT_ARRAY; 1993 int[] updateUserIds = EMPTY_INT_ARRAY; 1994 int[] instantUserIds = EMPTY_INT_ARRAY; 1995 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1996 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1997 for (int newUser : res.newUsers) { 1998 final boolean isInstantApp = ps.getInstantApp(newUser); 1999 if (allNewUsers) { 2000 if (isInstantApp) { 2001 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 2002 } else { 2003 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 2004 } 2005 continue; 2006 } 2007 boolean isNew = true; 2008 for (int origUser : res.origUsers) { 2009 if (origUser == newUser) { 2010 isNew = false; 2011 break; 2012 } 2013 } 2014 if (isNew) { 2015 if (isInstantApp) { 2016 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 2017 } else { 2018 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 2019 } 2020 } else { 2021 if (isInstantApp) { 2022 instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser); 2023 } else { 2024 updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser); 2025 } 2026 } 2027 } 2028 2029 // Send installed broadcasts if the package is not a static shared lib. 2030 if (res.pkg.staticSharedLibName == null) { 2031 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 2032 2033 // Send added for users that see the package for the first time 2034 // sendPackageAddedForNewUsers also deals with system apps 2035 int appId = UserHandle.getAppId(res.uid); 2036 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 2037 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload, 2038 virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds); 2039 2040 // Send added for users that don't see the package for the first time 2041 Bundle extras = new Bundle(1); 2042 extras.putInt(Intent.EXTRA_UID, res.uid); 2043 if (update) { 2044 extras.putBoolean(Intent.EXTRA_REPLACING, true); 2045 } 2046 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2047 extras, 0 /*flags*/, 2048 null /*targetPackage*/, null /*finishedReceiver*/, 2049 updateUserIds, instantUserIds); 2050 if (installerPackageName != null) { 2051 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2052 extras, 0 /*flags*/, 2053 installerPackageName, null /*finishedReceiver*/, 2054 updateUserIds, instantUserIds); 2055 } 2056 2057 // Send replaced for users that don't see the package for the first time 2058 if (update) { 2059 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 2060 packageName, extras, 0 /*flags*/, 2061 null /*targetPackage*/, null /*finishedReceiver*/, 2062 updateUserIds, instantUserIds); 2063 if (installerPackageName != null) { 2064 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 2065 extras, 0 /*flags*/, 2066 installerPackageName, null /*finishedReceiver*/, 2067 updateUserIds, instantUserIds); 2068 } 2069 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 2070 null /*package*/, null /*extras*/, 0 /*flags*/, 2071 packageName /*targetPackage*/, 2072 null /*finishedReceiver*/, updateUserIds, instantUserIds); 2073 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 2074 // First-install and we did a restore, so we're responsible for the 2075 // first-launch broadcast. 2076 if (DEBUG_BACKUP) { 2077 Slog.i(TAG, "Post-restore of " + packageName 2078 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds)); 2079 } 2080 sendFirstLaunchBroadcast(packageName, installerPackage, 2081 firstUserIds, firstInstantUserIds); 2082 } 2083 2084 // Send broadcast package appeared if forward locked/external for all users 2085 // treat asec-hosted packages like removable media on upgrade 2086 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 2087 if (DEBUG_INSTALL) { 2088 Slog.i(TAG, "upgrading pkg " + res.pkg 2089 + " is ASEC-hosted -> AVAILABLE"); 2090 } 2091 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2092 ArrayList<String> pkgList = new ArrayList<>(1); 2093 pkgList.add(packageName); 2094 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2095 } 2096 } 2097 2098 // Work that needs to happen on first install within each user 2099 if (firstUserIds != null && firstUserIds.length > 0) { 2100 synchronized (mPackages) { 2101 for (int userId : firstUserIds) { 2102 // If this app is a browser and it's newly-installed for some 2103 // users, clear any default-browser state in those users. The 2104 // app's nature doesn't depend on the user, so we can just check 2105 // its browser nature in any user and generalize. 2106 if (packageIsBrowser(packageName, userId)) { 2107 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2108 } 2109 2110 // We may also need to apply pending (restored) runtime 2111 // permission grants within these users. 2112 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2113 } 2114 } 2115 } 2116 2117 if (allNewUsers && !update) { 2118 notifyPackageAdded(packageName); 2119 } 2120 2121 // Log current value of "unknown sources" setting 2122 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2123 getUnknownSourcesSettings()); 2124 2125 // Remove the replaced package's older resources safely now 2126 // We delete after a gc for applications on sdcard. 2127 if (res.removedInfo != null && res.removedInfo.args != null) { 2128 Runtime.getRuntime().gc(); 2129 synchronized (mInstallLock) { 2130 res.removedInfo.args.doPostDeleteLI(true); 2131 } 2132 } else { 2133 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2134 // and not block here. 2135 VMRuntime.getRuntime().requestConcurrentGC(); 2136 } 2137 2138 // Notify DexManager that the package was installed for new users. 2139 // The updated users should already be indexed and the package code paths 2140 // should not change. 2141 // Don't notify the manager for ephemeral apps as they are not expected to 2142 // survive long enough to benefit of background optimizations. 2143 for (int userId : firstUserIds) { 2144 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2145 // There's a race currently where some install events may interleave with an uninstall. 2146 // This can lead to package info being null (b/36642664). 2147 if (info != null) { 2148 mDexManager.notifyPackageInstalled(info, userId); 2149 } 2150 } 2151 } 2152 2153 // If someone is watching installs - notify them 2154 if (installObserver != null) { 2155 try { 2156 Bundle extras = extrasForInstallResult(res); 2157 installObserver.onPackageInstalled(res.name, res.returnCode, 2158 res.returnMsg, extras); 2159 } catch (RemoteException e) { 2160 Slog.i(TAG, "Observer no longer exists."); 2161 } 2162 } 2163 } 2164 2165 private StorageEventListener mStorageListener = new StorageEventListener() { 2166 @Override 2167 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2168 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2169 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2170 final String volumeUuid = vol.getFsUuid(); 2171 2172 // Clean up any users or apps that were removed or recreated 2173 // while this volume was missing 2174 sUserManager.reconcileUsers(volumeUuid); 2175 reconcileApps(volumeUuid); 2176 2177 // Clean up any install sessions that expired or were 2178 // cancelled while this volume was missing 2179 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2180 2181 loadPrivatePackages(vol); 2182 2183 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2184 unloadPrivatePackages(vol); 2185 } 2186 } 2187 } 2188 2189 @Override 2190 public void onVolumeForgotten(String fsUuid) { 2191 if (TextUtils.isEmpty(fsUuid)) { 2192 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2193 return; 2194 } 2195 2196 // Remove any apps installed on the forgotten volume 2197 synchronized (mPackages) { 2198 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2199 for (PackageSetting ps : packages) { 2200 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2201 deletePackageVersioned(new VersionedPackage(ps.name, 2202 PackageManager.VERSION_CODE_HIGHEST), 2203 new LegacyPackageDeleteObserver(null).getBinder(), 2204 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2205 // Try very hard to release any references to this package 2206 // so we don't risk the system server being killed due to 2207 // open FDs 2208 AttributeCache.instance().removePackage(ps.name); 2209 } 2210 2211 mSettings.onVolumeForgotten(fsUuid); 2212 mSettings.writeLPr(); 2213 } 2214 } 2215 }; 2216 2217 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2218 Bundle extras = null; 2219 switch (res.returnCode) { 2220 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2221 extras = new Bundle(); 2222 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2223 res.origPermission); 2224 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2225 res.origPackage); 2226 break; 2227 } 2228 case PackageManager.INSTALL_SUCCEEDED: { 2229 extras = new Bundle(); 2230 extras.putBoolean(Intent.EXTRA_REPLACING, 2231 res.removedInfo != null && res.removedInfo.removedPackage != null); 2232 break; 2233 } 2234 } 2235 return extras; 2236 } 2237 2238 void scheduleWriteSettingsLocked() { 2239 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2240 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2241 } 2242 } 2243 2244 void scheduleWritePackageListLocked(int userId) { 2245 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2246 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2247 msg.arg1 = userId; 2248 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2249 } 2250 } 2251 2252 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2253 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2254 scheduleWritePackageRestrictionsLocked(userId); 2255 } 2256 2257 void scheduleWritePackageRestrictionsLocked(int userId) { 2258 final int[] userIds = (userId == UserHandle.USER_ALL) 2259 ? sUserManager.getUserIds() : new int[]{userId}; 2260 for (int nextUserId : userIds) { 2261 if (!sUserManager.exists(nextUserId)) return; 2262 mDirtyUsers.add(nextUserId); 2263 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2264 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2265 } 2266 } 2267 } 2268 2269 public static PackageManagerService main(Context context, Installer installer, 2270 boolean factoryTest, boolean onlyCore) { 2271 // Self-check for initial settings. 2272 PackageManagerServiceCompilerMapping.checkProperties(); 2273 2274 PackageManagerService m = new PackageManagerService(context, installer, 2275 factoryTest, onlyCore); 2276 m.enableSystemUserPackages(); 2277 ServiceManager.addService("package", m); 2278 final PackageManagerNative pmn = m.new PackageManagerNative(); 2279 ServiceManager.addService("package_native", pmn); 2280 return m; 2281 } 2282 2283 private void enableSystemUserPackages() { 2284 if (!UserManager.isSplitSystemUser()) { 2285 return; 2286 } 2287 // For system user, enable apps based on the following conditions: 2288 // - app is whitelisted or belong to one of these groups: 2289 // -- system app which has no launcher icons 2290 // -- system app which has INTERACT_ACROSS_USERS permission 2291 // -- system IME app 2292 // - app is not in the blacklist 2293 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2294 Set<String> enableApps = new ArraySet<>(); 2295 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2296 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2297 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2298 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2299 enableApps.addAll(wlApps); 2300 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2301 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2302 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2303 enableApps.removeAll(blApps); 2304 Log.i(TAG, "Applications installed for system user: " + enableApps); 2305 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2306 UserHandle.SYSTEM); 2307 final int allAppsSize = allAps.size(); 2308 synchronized (mPackages) { 2309 for (int i = 0; i < allAppsSize; i++) { 2310 String pName = allAps.get(i); 2311 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2312 // Should not happen, but we shouldn't be failing if it does 2313 if (pkgSetting == null) { 2314 continue; 2315 } 2316 boolean install = enableApps.contains(pName); 2317 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2318 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2319 + " for system user"); 2320 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2321 } 2322 } 2323 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2324 } 2325 } 2326 2327 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2328 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2329 Context.DISPLAY_SERVICE); 2330 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2331 } 2332 2333 /** 2334 * Requests that files preopted on a secondary system partition be copied to the data partition 2335 * if possible. Note that the actual copying of the files is accomplished by init for security 2336 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2337 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2338 */ 2339 private static void requestCopyPreoptedFiles() { 2340 final int WAIT_TIME_MS = 100; 2341 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2342 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2343 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2344 // We will wait for up to 100 seconds. 2345 final long timeStart = SystemClock.uptimeMillis(); 2346 final long timeEnd = timeStart + 100 * 1000; 2347 long timeNow = timeStart; 2348 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2349 try { 2350 Thread.sleep(WAIT_TIME_MS); 2351 } catch (InterruptedException e) { 2352 // Do nothing 2353 } 2354 timeNow = SystemClock.uptimeMillis(); 2355 if (timeNow > timeEnd) { 2356 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2357 Slog.wtf(TAG, "cppreopt did not finish!"); 2358 break; 2359 } 2360 } 2361 2362 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2363 } 2364 } 2365 2366 public PackageManagerService(Context context, Installer installer, 2367 boolean factoryTest, boolean onlyCore) { 2368 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2369 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2370 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2371 SystemClock.uptimeMillis()); 2372 2373 if (mSdkVersion <= 0) { 2374 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2375 } 2376 2377 mContext = context; 2378 2379 mFactoryTest = factoryTest; 2380 mOnlyCore = onlyCore; 2381 mMetrics = new DisplayMetrics(); 2382 mInstaller = installer; 2383 2384 // Create sub-components that provide services / data. Order here is important. 2385 synchronized (mInstallLock) { 2386 synchronized (mPackages) { 2387 // Expose private service for system components to use. 2388 LocalServices.addService( 2389 PackageManagerInternal.class, new PackageManagerInternalImpl()); 2390 sUserManager = new UserManagerService(context, this, 2391 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2392 mPermissionManager = PermissionManagerService.create(context, 2393 new DefaultPermissionGrantedCallback() { 2394 @Override 2395 public void onDefaultRuntimePermissionsGranted(int userId) { 2396 synchronized(mPackages) { 2397 mSettings.onDefaultRuntimePermissionsGrantedLPr(userId); 2398 } 2399 } 2400 }, mPackages /*externalLock*/); 2401 mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy(); 2402 mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages); 2403 } 2404 } 2405 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2406 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2407 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2408 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2409 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2410 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2411 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2412 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2413 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2414 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2415 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2416 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2417 mSettings.addSharedUserLPw("android.uid.se", SE_UID, 2418 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2419 2420 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2421 if (separateProcesses != null && separateProcesses.length() > 0) { 2422 if ("*".equals(separateProcesses)) { 2423 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2424 mSeparateProcesses = null; 2425 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2426 } else { 2427 mDefParseFlags = 0; 2428 mSeparateProcesses = separateProcesses.split(","); 2429 Slog.w(TAG, "Running with debug.separate_processes: " 2430 + separateProcesses); 2431 } 2432 } else { 2433 mDefParseFlags = 0; 2434 mSeparateProcesses = null; 2435 } 2436 2437 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2438 "*dexopt*"); 2439 DexManager.Listener dexManagerListener = DexLogger.getListener(this, 2440 installer, mInstallLock); 2441 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock, 2442 dexManagerListener); 2443 mArtManagerService = new ArtManagerService(this, installer, mInstallLock); 2444 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2445 2446 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2447 FgThread.get().getLooper()); 2448 2449 getDefaultDisplayMetrics(context, mMetrics); 2450 2451 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2452 SystemConfig systemConfig = SystemConfig.getInstance(); 2453 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2454 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2455 2456 mProtectedPackages = new ProtectedPackages(mContext); 2457 2458 synchronized (mInstallLock) { 2459 // writer 2460 synchronized (mPackages) { 2461 mHandlerThread = new ServiceThread(TAG, 2462 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2463 mHandlerThread.start(); 2464 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2465 mProcessLoggingHandler = new ProcessLoggingHandler(); 2466 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2467 mInstantAppRegistry = new InstantAppRegistry(this); 2468 2469 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2470 final int builtInLibCount = libConfig.size(); 2471 for (int i = 0; i < builtInLibCount; i++) { 2472 String name = libConfig.keyAt(i); 2473 String path = libConfig.valueAt(i); 2474 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2475 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2476 } 2477 2478 SELinuxMMAC.readInstallPolicy(); 2479 2480 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2481 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2482 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2483 2484 // Clean up orphaned packages for which the code path doesn't exist 2485 // and they are an update to a system app - caused by bug/32321269 2486 final int packageSettingCount = mSettings.mPackages.size(); 2487 for (int i = packageSettingCount - 1; i >= 0; i--) { 2488 PackageSetting ps = mSettings.mPackages.valueAt(i); 2489 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2490 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2491 mSettings.mPackages.removeAt(i); 2492 mSettings.enableSystemPackageLPw(ps.name); 2493 } 2494 } 2495 2496 if (mFirstBoot) { 2497 requestCopyPreoptedFiles(); 2498 } 2499 2500 String customResolverActivity = Resources.getSystem().getString( 2501 R.string.config_customResolverActivity); 2502 if (TextUtils.isEmpty(customResolverActivity)) { 2503 customResolverActivity = null; 2504 } else { 2505 mCustomResolverComponentName = ComponentName.unflattenFromString( 2506 customResolverActivity); 2507 } 2508 2509 long startTime = SystemClock.uptimeMillis(); 2510 2511 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2512 startTime); 2513 2514 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2515 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2516 2517 if (bootClassPath == null) { 2518 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2519 } 2520 2521 if (systemServerClassPath == null) { 2522 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2523 } 2524 2525 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2526 2527 final VersionInfo ver = mSettings.getInternalVersion(); 2528 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2529 if (mIsUpgrade) { 2530 logCriticalInfo(Log.INFO, 2531 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2532 } 2533 2534 // when upgrading from pre-M, promote system app permissions from install to runtime 2535 mPromoteSystemApps = 2536 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2537 2538 // When upgrading from pre-N, we need to handle package extraction like first boot, 2539 // as there is no profiling data available. 2540 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2541 2542 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2543 2544 // save off the names of pre-existing system packages prior to scanning; we don't 2545 // want to automatically grant runtime permissions for new system apps 2546 if (mPromoteSystemApps) { 2547 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2548 while (pkgSettingIter.hasNext()) { 2549 PackageSetting ps = pkgSettingIter.next(); 2550 if (isSystemApp(ps)) { 2551 mExistingSystemPackages.add(ps.name); 2552 } 2553 } 2554 } 2555 2556 mCacheDir = preparePackageParserCache(mIsUpgrade); 2557 2558 // Set flag to monitor and not change apk file paths when 2559 // scanning install directories. 2560 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2561 2562 if (mIsUpgrade || mFirstBoot) { 2563 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2564 } 2565 2566 // Collect vendor/product overlay packages. (Do this before scanning any apps.) 2567 // For security and version matching reason, only consider 2568 // overlay packages if they reside in the right directory. 2569 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), 2570 mDefParseFlags 2571 | PackageParser.PARSE_IS_SYSTEM_DIR, 2572 scanFlags 2573 | SCAN_AS_SYSTEM 2574 | SCAN_AS_VENDOR, 2575 0); 2576 scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR), 2577 mDefParseFlags 2578 | PackageParser.PARSE_IS_SYSTEM_DIR, 2579 scanFlags 2580 | SCAN_AS_SYSTEM 2581 | SCAN_AS_PRODUCT, 2582 0); 2583 2584 mParallelPackageParserCallback.findStaticOverlayPackages(); 2585 2586 // Find base frameworks (resource packages without code). 2587 scanDirTracedLI(frameworkDir, 2588 mDefParseFlags 2589 | PackageParser.PARSE_IS_SYSTEM_DIR, 2590 scanFlags 2591 | SCAN_NO_DEX 2592 | SCAN_AS_SYSTEM 2593 | SCAN_AS_PRIVILEGED, 2594 0); 2595 2596 // Collect privileged system packages. 2597 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2598 scanDirTracedLI(privilegedAppDir, 2599 mDefParseFlags 2600 | PackageParser.PARSE_IS_SYSTEM_DIR, 2601 scanFlags 2602 | SCAN_AS_SYSTEM 2603 | SCAN_AS_PRIVILEGED, 2604 0); 2605 2606 // Collect ordinary system packages. 2607 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2608 scanDirTracedLI(systemAppDir, 2609 mDefParseFlags 2610 | PackageParser.PARSE_IS_SYSTEM_DIR, 2611 scanFlags 2612 | SCAN_AS_SYSTEM, 2613 0); 2614 2615 // Collect privileged vendor packages. 2616 File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 2617 try { 2618 privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile(); 2619 } catch (IOException e) { 2620 // failed to look up canonical path, continue with original one 2621 } 2622 scanDirTracedLI(privilegedVendorAppDir, 2623 mDefParseFlags 2624 | PackageParser.PARSE_IS_SYSTEM_DIR, 2625 scanFlags 2626 | SCAN_AS_SYSTEM 2627 | SCAN_AS_VENDOR 2628 | SCAN_AS_PRIVILEGED, 2629 0); 2630 2631 // Collect ordinary vendor packages. 2632 File vendorAppDir = new File(Environment.getVendorDirectory(), "app"); 2633 try { 2634 vendorAppDir = vendorAppDir.getCanonicalFile(); 2635 } catch (IOException e) { 2636 // failed to look up canonical path, continue with original one 2637 } 2638 scanDirTracedLI(vendorAppDir, 2639 mDefParseFlags 2640 | PackageParser.PARSE_IS_SYSTEM_DIR, 2641 scanFlags 2642 | SCAN_AS_SYSTEM 2643 | SCAN_AS_VENDOR, 2644 0); 2645 2646 // Collect privileged odm packages. /odm is another vendor partition 2647 // other than /vendor. 2648 File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), 2649 "priv-app"); 2650 try { 2651 privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile(); 2652 } catch (IOException e) { 2653 // failed to look up canonical path, continue with original one 2654 } 2655 scanDirTracedLI(privilegedOdmAppDir, 2656 mDefParseFlags 2657 | PackageParser.PARSE_IS_SYSTEM_DIR, 2658 scanFlags 2659 | SCAN_AS_SYSTEM 2660 | SCAN_AS_VENDOR 2661 | SCAN_AS_PRIVILEGED, 2662 0); 2663 2664 // Collect ordinary odm packages. /odm is another vendor partition 2665 // other than /vendor. 2666 File odmAppDir = new File(Environment.getOdmDirectory(), "app"); 2667 try { 2668 odmAppDir = odmAppDir.getCanonicalFile(); 2669 } catch (IOException e) { 2670 // failed to look up canonical path, continue with original one 2671 } 2672 scanDirTracedLI(odmAppDir, 2673 mDefParseFlags 2674 | PackageParser.PARSE_IS_SYSTEM_DIR, 2675 scanFlags 2676 | SCAN_AS_SYSTEM 2677 | SCAN_AS_VENDOR, 2678 0); 2679 2680 // Collect all OEM packages. 2681 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2682 scanDirTracedLI(oemAppDir, 2683 mDefParseFlags 2684 | PackageParser.PARSE_IS_SYSTEM_DIR, 2685 scanFlags 2686 | SCAN_AS_SYSTEM 2687 | SCAN_AS_OEM, 2688 0); 2689 2690 // Collected privileged product packages. 2691 File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 2692 try { 2693 privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile(); 2694 } catch (IOException e) { 2695 // failed to look up canonical path, continue with original one 2696 } 2697 scanDirTracedLI(privilegedProductAppDir, 2698 mDefParseFlags 2699 | PackageParser.PARSE_IS_SYSTEM_DIR, 2700 scanFlags 2701 | SCAN_AS_SYSTEM 2702 | SCAN_AS_PRODUCT 2703 | SCAN_AS_PRIVILEGED, 2704 0); 2705 2706 // Collect ordinary product packages. 2707 File productAppDir = new File(Environment.getProductDirectory(), "app"); 2708 try { 2709 productAppDir = productAppDir.getCanonicalFile(); 2710 } catch (IOException e) { 2711 // failed to look up canonical path, continue with original one 2712 } 2713 scanDirTracedLI(productAppDir, 2714 mDefParseFlags 2715 | PackageParser.PARSE_IS_SYSTEM_DIR, 2716 scanFlags 2717 | SCAN_AS_SYSTEM 2718 | SCAN_AS_PRODUCT, 2719 0); 2720 2721 // Prune any system packages that no longer exist. 2722 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>(); 2723 // Stub packages must either be replaced with full versions in the /data 2724 // partition or be disabled. 2725 final List<String> stubSystemApps = new ArrayList<>(); 2726 if (!mOnlyCore) { 2727 // do this first before mucking with mPackages for the "expecting better" case 2728 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator(); 2729 while (pkgIterator.hasNext()) { 2730 final PackageParser.Package pkg = pkgIterator.next(); 2731 if (pkg.isStub) { 2732 stubSystemApps.add(pkg.packageName); 2733 } 2734 } 2735 2736 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2737 while (psit.hasNext()) { 2738 PackageSetting ps = psit.next(); 2739 2740 /* 2741 * If this is not a system app, it can't be a 2742 * disable system app. 2743 */ 2744 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2745 continue; 2746 } 2747 2748 /* 2749 * If the package is scanned, it's not erased. 2750 */ 2751 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2752 if (scannedPkg != null) { 2753 /* 2754 * If the system app is both scanned and in the 2755 * disabled packages list, then it must have been 2756 * added via OTA. Remove it from the currently 2757 * scanned package so the previously user-installed 2758 * application can be scanned. 2759 */ 2760 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2761 logCriticalInfo(Log.WARN, 2762 "Expecting better updated system app for " + ps.name 2763 + "; removing system app. Last known" 2764 + " codePath=" + ps.codePathString 2765 + ", versionCode=" + ps.versionCode 2766 + "; scanned versionCode=" + scannedPkg.getLongVersionCode()); 2767 removePackageLI(scannedPkg, true); 2768 mExpectingBetter.put(ps.name, ps.codePath); 2769 } 2770 2771 continue; 2772 } 2773 2774 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2775 psit.remove(); 2776 logCriticalInfo(Log.WARN, "System package " + ps.name 2777 + " no longer exists; it's data will be wiped"); 2778 // Actual deletion of code and data will be handled by later 2779 // reconciliation step 2780 } else { 2781 // we still have a disabled system package, but, it still might have 2782 // been removed. check the code path still exists and check there's 2783 // still a package. the latter can happen if an OTA keeps the same 2784 // code path, but, changes the package name. 2785 final PackageSetting disabledPs = 2786 mSettings.getDisabledSystemPkgLPr(ps.name); 2787 if (disabledPs.codePath == null || !disabledPs.codePath.exists() 2788 || disabledPs.pkg == null) { 2789 possiblyDeletedUpdatedSystemApps.add(ps.name); 2790 } 2791 } 2792 } 2793 } 2794 2795 //delete tmp files 2796 deleteTempPackageFiles(); 2797 2798 final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get(); 2799 2800 // Remove any shared userIDs that have no associated packages 2801 mSettings.pruneSharedUsersLPw(); 2802 final long systemScanTime = SystemClock.uptimeMillis() - startTime; 2803 final int systemPackagesCount = mPackages.size(); 2804 Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime 2805 + " ms, packageCount: " + systemPackagesCount 2806 + " , timePerPackage: " 2807 + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount) 2808 + " , cached: " + cachedSystemApps); 2809 if (mIsUpgrade && systemPackagesCount > 0) { 2810 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time", 2811 ((int) systemScanTime) / systemPackagesCount); 2812 } 2813 if (!mOnlyCore) { 2814 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2815 SystemClock.uptimeMillis()); 2816 scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2817 2818 scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags 2819 | PackageParser.PARSE_FORWARD_LOCK, 2820 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2821 2822 // Remove disable package settings for updated system apps that were 2823 // removed via an OTA. If the update is no longer present, remove the 2824 // app completely. Otherwise, revoke their system privileges. 2825 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2826 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2827 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2828 final String msg; 2829 if (deletedPkg == null) { 2830 // should have found an update, but, we didn't; remove everything 2831 msg = "Updated system package " + deletedAppName 2832 + " no longer exists; removing its data"; 2833 // Actual deletion of code and data will be handled by later 2834 // reconciliation step 2835 } else { 2836 // found an update; revoke system privileges 2837 msg = "Updated system package + " + deletedAppName 2838 + " no longer exists; revoking system privileges"; 2839 2840 // Don't do anything if a stub is removed from the system image. If 2841 // we were to remove the uncompressed version from the /data partition, 2842 // this is where it'd be done. 2843 2844 final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2845 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2846 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2847 } 2848 logCriticalInfo(Log.WARN, msg); 2849 } 2850 2851 /* 2852 * Make sure all system apps that we expected to appear on 2853 * the userdata partition actually showed up. If they never 2854 * appeared, crawl back and revive the system version. 2855 */ 2856 for (int i = 0; i < mExpectingBetter.size(); i++) { 2857 final String packageName = mExpectingBetter.keyAt(i); 2858 if (!mPackages.containsKey(packageName)) { 2859 final File scanFile = mExpectingBetter.valueAt(i); 2860 2861 logCriticalInfo(Log.WARN, "Expected better " + packageName 2862 + " but never showed up; reverting to system"); 2863 2864 final @ParseFlags int reparseFlags; 2865 final @ScanFlags int rescanFlags; 2866 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2867 reparseFlags = 2868 mDefParseFlags | 2869 PackageParser.PARSE_IS_SYSTEM_DIR; 2870 rescanFlags = 2871 scanFlags 2872 | SCAN_AS_SYSTEM 2873 | SCAN_AS_PRIVILEGED; 2874 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2875 reparseFlags = 2876 mDefParseFlags | 2877 PackageParser.PARSE_IS_SYSTEM_DIR; 2878 rescanFlags = 2879 scanFlags 2880 | SCAN_AS_SYSTEM; 2881 } else if (FileUtils.contains(privilegedVendorAppDir, scanFile) 2882 || FileUtils.contains(privilegedOdmAppDir, scanFile)) { 2883 reparseFlags = 2884 mDefParseFlags | 2885 PackageParser.PARSE_IS_SYSTEM_DIR; 2886 rescanFlags = 2887 scanFlags 2888 | SCAN_AS_SYSTEM 2889 | SCAN_AS_VENDOR 2890 | SCAN_AS_PRIVILEGED; 2891 } else if (FileUtils.contains(vendorAppDir, scanFile) 2892 || FileUtils.contains(odmAppDir, scanFile)) { 2893 reparseFlags = 2894 mDefParseFlags | 2895 PackageParser.PARSE_IS_SYSTEM_DIR; 2896 rescanFlags = 2897 scanFlags 2898 | SCAN_AS_SYSTEM 2899 | SCAN_AS_VENDOR; 2900 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2901 reparseFlags = 2902 mDefParseFlags | 2903 PackageParser.PARSE_IS_SYSTEM_DIR; 2904 rescanFlags = 2905 scanFlags 2906 | SCAN_AS_SYSTEM 2907 | SCAN_AS_OEM; 2908 } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) { 2909 reparseFlags = 2910 mDefParseFlags | 2911 PackageParser.PARSE_IS_SYSTEM_DIR; 2912 rescanFlags = 2913 scanFlags 2914 | SCAN_AS_SYSTEM 2915 | SCAN_AS_PRODUCT 2916 | SCAN_AS_PRIVILEGED; 2917 } else if (FileUtils.contains(productAppDir, scanFile)) { 2918 reparseFlags = 2919 mDefParseFlags | 2920 PackageParser.PARSE_IS_SYSTEM_DIR; 2921 rescanFlags = 2922 scanFlags 2923 | SCAN_AS_SYSTEM 2924 | SCAN_AS_PRODUCT; 2925 } else { 2926 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2927 continue; 2928 } 2929 2930 mSettings.enableSystemPackageLPw(packageName); 2931 2932 try { 2933 scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null); 2934 } catch (PackageManagerException e) { 2935 Slog.e(TAG, "Failed to parse original system package: " 2936 + e.getMessage()); 2937 } 2938 } 2939 } 2940 2941 // Uncompress and install any stubbed system applications. 2942 // This must be done last to ensure all stubs are replaced or disabled. 2943 decompressSystemApplications(stubSystemApps, scanFlags); 2944 2945 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get() 2946 - cachedSystemApps; 2947 2948 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime; 2949 final int dataPackagesCount = mPackages.size() - systemPackagesCount; 2950 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime 2951 + " ms, packageCount: " + dataPackagesCount 2952 + " , timePerPackage: " 2953 + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) 2954 + " , cached: " + cachedNonSystemApps); 2955 if (mIsUpgrade && dataPackagesCount > 0) { 2956 MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time", 2957 ((int) dataScanTime) / dataPackagesCount); 2958 } 2959 } 2960 mExpectingBetter.clear(); 2961 2962 // Resolve the storage manager. 2963 mStorageManagerPackage = getStorageManagerPackageName(); 2964 2965 // Resolve protected action filters. Only the setup wizard is allowed to 2966 // have a high priority filter for these actions. 2967 mSetupWizardPackage = getSetupWizardPackageName(); 2968 if (mProtectedFilters.size() > 0) { 2969 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2970 Slog.i(TAG, "No setup wizard;" 2971 + " All protected intents capped to priority 0"); 2972 } 2973 for (ActivityIntentInfo filter : mProtectedFilters) { 2974 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2975 if (DEBUG_FILTERS) { 2976 Slog.i(TAG, "Found setup wizard;" 2977 + " allow priority " + filter.getPriority() + ";" 2978 + " package: " + filter.activity.info.packageName 2979 + " activity: " + filter.activity.className 2980 + " priority: " + filter.getPriority()); 2981 } 2982 // skip setup wizard; allow it to keep the high priority filter 2983 continue; 2984 } 2985 if (DEBUG_FILTERS) { 2986 Slog.i(TAG, "Protected action; cap priority to 0;" 2987 + " package: " + filter.activity.info.packageName 2988 + " activity: " + filter.activity.className 2989 + " origPrio: " + filter.getPriority()); 2990 } 2991 filter.setPriority(0); 2992 } 2993 } 2994 2995 mSystemTextClassifierPackage = getSystemTextClassifierPackageName(); 2996 2997 mDeferProtectedFilters = false; 2998 mProtectedFilters.clear(); 2999 3000 // Now that we know all of the shared libraries, update all clients to have 3001 // the correct library paths. 3002 updateAllSharedLibrariesLPw(null); 3003 3004 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 3005 // NOTE: We ignore potential failures here during a system scan (like 3006 // the rest of the commands above) because there's precious little we 3007 // can do about it. A settings error is reported, though. 3008 final List<String> changedAbiCodePath = 3009 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 3010 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 3011 for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) { 3012 final String codePathString = changedAbiCodePath.get(i); 3013 try { 3014 mInstaller.rmdex(codePathString, 3015 getDexCodeInstructionSet(getPreferredInstructionSet())); 3016 } catch (InstallerException ignored) { 3017 } 3018 } 3019 } 3020 // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same 3021 // SELinux domain. 3022 setting.fixSeInfoLocked(); 3023 } 3024 3025 // Now that we know all the packages we are keeping, 3026 // read and update their last usage times. 3027 mPackageUsage.read(mPackages); 3028 mCompilerStats.read(); 3029 3030 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 3031 SystemClock.uptimeMillis()); 3032 Slog.i(TAG, "Time to scan packages: " 3033 + ((SystemClock.uptimeMillis()-startTime)/1000f) 3034 + " seconds"); 3035 3036 // If the platform SDK has changed since the last time we booted, 3037 // we need to re-grant app permission to catch any new ones that 3038 // appear. This is really a hack, and means that apps can in some 3039 // cases get permissions that the user didn't initially explicitly 3040 // allow... it would be nice to have some better way to handle 3041 // this situation. 3042 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 3043 if (sdkUpdated) { 3044 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 3045 + mSdkVersion + "; regranting permissions for internal storage"); 3046 } 3047 mPermissionManager.updateAllPermissions( 3048 StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(), 3049 mPermissionCallback); 3050 ver.sdkVersion = mSdkVersion; 3051 3052 // If this is the first boot or an update from pre-M, and it is a normal 3053 // boot, then we need to initialize the default preferred apps across 3054 // all defined users. 3055 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 3056 for (UserInfo user : sUserManager.getUsers(true)) { 3057 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 3058 applyFactoryDefaultBrowserLPw(user.id); 3059 primeDomainVerificationsLPw(user.id); 3060 } 3061 } 3062 3063 // Prepare storage for system user really early during boot, 3064 // since core system apps like SettingsProvider and SystemUI 3065 // can't wait for user to start 3066 final int storageFlags; 3067 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3068 storageFlags = StorageManager.FLAG_STORAGE_DE; 3069 } else { 3070 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 3071 } 3072 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 3073 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 3074 true /* onlyCoreApps */); 3075 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 3076 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync", 3077 Trace.TRACE_TAG_PACKAGE_MANAGER); 3078 traceLog.traceBegin("AppDataFixup"); 3079 try { 3080 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 3081 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 3082 } catch (InstallerException e) { 3083 Slog.w(TAG, "Trouble fixing GIDs", e); 3084 } 3085 traceLog.traceEnd(); 3086 3087 traceLog.traceBegin("AppDataPrepare"); 3088 if (deferPackages == null || deferPackages.isEmpty()) { 3089 return; 3090 } 3091 int count = 0; 3092 for (String pkgName : deferPackages) { 3093 PackageParser.Package pkg = null; 3094 synchronized (mPackages) { 3095 PackageSetting ps = mSettings.getPackageLPr(pkgName); 3096 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 3097 pkg = ps.pkg; 3098 } 3099 } 3100 if (pkg != null) { 3101 synchronized (mInstallLock) { 3102 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 3103 true /* maybeMigrateAppData */); 3104 } 3105 count++; 3106 } 3107 } 3108 traceLog.traceEnd(); 3109 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 3110 }, "prepareAppData"); 3111 3112 // If this is first boot after an OTA, and a normal boot, then 3113 // we need to clear code cache directories. 3114 // Note that we do *not* clear the application profiles. These remain valid 3115 // across OTAs and are used to drive profile verification (post OTA) and 3116 // profile compilation (without waiting to collect a fresh set of profiles). 3117 if (mIsUpgrade && !onlyCore) { 3118 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 3119 for (int i = 0; i < mSettings.mPackages.size(); i++) { 3120 final PackageSetting ps = mSettings.mPackages.valueAt(i); 3121 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 3122 // No apps are running this early, so no need to freeze 3123 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 3124 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 3125 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 3126 } 3127 } 3128 ver.fingerprint = Build.FINGERPRINT; 3129 } 3130 3131 checkDefaultBrowser(); 3132 3133 // clear only after permissions and other defaults have been updated 3134 mExistingSystemPackages.clear(); 3135 mPromoteSystemApps = false; 3136 3137 // All the changes are done during package scanning. 3138 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 3139 3140 // can downgrade to reader 3141 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 3142 mSettings.writeLPr(); 3143 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3144 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 3145 SystemClock.uptimeMillis()); 3146 3147 if (!mOnlyCore) { 3148 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 3149 mRequiredInstallerPackage = getRequiredInstallerLPr(); 3150 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 3151 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 3152 if (mIntentFilterVerifierComponent != null) { 3153 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 3154 mIntentFilterVerifierComponent); 3155 } else { 3156 mIntentFilterVerifier = null; 3157 } 3158 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3159 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 3160 SharedLibraryInfo.VERSION_UNDEFINED); 3161 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3162 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 3163 SharedLibraryInfo.VERSION_UNDEFINED); 3164 } else { 3165 mRequiredVerifierPackage = null; 3166 mRequiredInstallerPackage = null; 3167 mRequiredUninstallerPackage = null; 3168 mIntentFilterVerifierComponent = null; 3169 mIntentFilterVerifier = null; 3170 mServicesSystemSharedLibraryPackageName = null; 3171 mSharedSystemSharedLibraryPackageName = null; 3172 } 3173 3174 mInstallerService = new PackageInstallerService(context, this); 3175 final Pair<ComponentName, String> instantAppResolverComponent = 3176 getInstantAppResolverLPr(); 3177 if (instantAppResolverComponent != null) { 3178 if (DEBUG_INSTANT) { 3179 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 3180 } 3181 mInstantAppResolverConnection = new InstantAppResolverConnection( 3182 mContext, instantAppResolverComponent.first, 3183 instantAppResolverComponent.second); 3184 mInstantAppResolverSettingsComponent = 3185 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 3186 } else { 3187 mInstantAppResolverConnection = null; 3188 mInstantAppResolverSettingsComponent = null; 3189 } 3190 updateInstantAppInstallerLocked(null); 3191 3192 // Read and update the usage of dex files. 3193 // Do this at the end of PM init so that all the packages have their 3194 // data directory reconciled. 3195 // At this point we know the code paths of the packages, so we can validate 3196 // the disk file and build the internal cache. 3197 // The usage file is expected to be small so loading and verifying it 3198 // should take a fairly small time compare to the other activities (e.g. package 3199 // scanning). 3200 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3201 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 3202 for (int userId : currentUserIds) { 3203 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3204 } 3205 mDexManager.load(userPackages); 3206 if (mIsUpgrade) { 3207 MetricsLogger.histogram(null, "ota_package_manager_init_time", 3208 (int) (SystemClock.uptimeMillis() - startTime)); 3209 } 3210 } // synchronized (mPackages) 3211 } // synchronized (mInstallLock) 3212 3213 // Now after opening every single application zip, make sure they 3214 // are all flushed. Not really needed, but keeps things nice and 3215 // tidy. 3216 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3217 Runtime.getRuntime().gc(); 3218 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3219 3220 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 3221 FallbackCategoryProvider.loadFallbacks(); 3222 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3223 3224 // The initial scanning above does many calls into installd while 3225 // holding the mPackages lock, but we're mostly interested in yelling 3226 // once we have a booted system. 3227 mInstaller.setWarnIfHeld(mPackages); 3228 3229 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3230 } 3231 3232 /** 3233 * Uncompress and install stub applications. 3234 * <p>In order to save space on the system partition, some applications are shipped in a 3235 * compressed form. In addition the compressed bits for the full application, the 3236 * system image contains a tiny stub comprised of only the Android manifest. 3237 * <p>During the first boot, attempt to uncompress and install the full application. If 3238 * the application can't be installed for any reason, disable the stub and prevent 3239 * uncompressing the full application during future boots. 3240 * <p>In order to forcefully attempt an installation of a full application, go to app 3241 * settings and enable the application. 3242 */ 3243 private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) { 3244 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3245 final String pkgName = stubSystemApps.get(i); 3246 // skip if the system package is already disabled 3247 if (mSettings.isDisabledSystemPackageLPr(pkgName)) { 3248 stubSystemApps.remove(i); 3249 continue; 3250 } 3251 // skip if the package isn't installed (?!); this should never happen 3252 final PackageParser.Package pkg = mPackages.get(pkgName); 3253 if (pkg == null) { 3254 stubSystemApps.remove(i); 3255 continue; 3256 } 3257 // skip if the package has been disabled by the user 3258 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3259 if (ps != null) { 3260 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM); 3261 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) { 3262 stubSystemApps.remove(i); 3263 continue; 3264 } 3265 } 3266 3267 if (DEBUG_COMPRESSION) { 3268 Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName); 3269 } 3270 3271 // uncompress the binary to its eventual destination on /data 3272 final File scanFile = decompressPackage(pkg); 3273 if (scanFile == null) { 3274 continue; 3275 } 3276 3277 // install the package to replace the stub on /system 3278 try { 3279 mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/); 3280 removePackageLI(pkg, true /*chatty*/); 3281 scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null); 3282 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 3283 UserHandle.USER_SYSTEM, "android"); 3284 stubSystemApps.remove(i); 3285 continue; 3286 } catch (PackageManagerException e) { 3287 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage()); 3288 } 3289 3290 // any failed attempt to install the package will be cleaned up later 3291 } 3292 3293 // disable any stub still left; these failed to install the full application 3294 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3295 final String pkgName = stubSystemApps.get(i); 3296 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3297 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 3298 UserHandle.USER_SYSTEM, "android"); 3299 logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName); 3300 } 3301 } 3302 3303 /** 3304 * Decompresses the given package on the system image onto 3305 * the /data partition. 3306 * @return The directory the package was decompressed into. Otherwise, {@code null}. 3307 */ 3308 private File decompressPackage(PackageParser.Package pkg) { 3309 final File[] compressedFiles = getCompressedFiles(pkg.codePath); 3310 if (compressedFiles == null || compressedFiles.length == 0) { 3311 if (DEBUG_COMPRESSION) { 3312 Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath); 3313 } 3314 return null; 3315 } 3316 final File dstCodePath = 3317 getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName); 3318 int ret = PackageManager.INSTALL_SUCCEEDED; 3319 try { 3320 Os.mkdir(dstCodePath.getAbsolutePath(), 0755); 3321 Os.chmod(dstCodePath.getAbsolutePath(), 0755); 3322 for (File srcFile : compressedFiles) { 3323 final String srcFileName = srcFile.getName(); 3324 final String dstFileName = srcFileName.substring( 3325 0, srcFileName.length() - COMPRESSED_EXTENSION.length()); 3326 final File dstFile = new File(dstCodePath, dstFileName); 3327 ret = decompressFile(srcFile, dstFile); 3328 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3329 logCriticalInfo(Log.ERROR, "Failed to decompress" 3330 + "; pkg: " + pkg.packageName 3331 + ", file: " + dstFileName); 3332 break; 3333 } 3334 } 3335 } catch (ErrnoException e) { 3336 logCriticalInfo(Log.ERROR, "Failed to decompress" 3337 + "; pkg: " + pkg.packageName 3338 + ", err: " + e.errno); 3339 } 3340 if (ret == PackageManager.INSTALL_SUCCEEDED) { 3341 final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME); 3342 NativeLibraryHelper.Handle handle = null; 3343 try { 3344 handle = NativeLibraryHelper.Handle.create(dstCodePath); 3345 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 3346 null /*abiOverride*/); 3347 } catch (IOException e) { 3348 logCriticalInfo(Log.ERROR, "Failed to extract native libraries" 3349 + "; pkg: " + pkg.packageName); 3350 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3351 } finally { 3352 IoUtils.closeQuietly(handle); 3353 } 3354 } 3355 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3356 if (dstCodePath == null || !dstCodePath.exists()) { 3357 return null; 3358 } 3359 removeCodePathLI(dstCodePath); 3360 return null; 3361 } 3362 3363 return dstCodePath; 3364 } 3365 3366 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3367 // we're only interested in updating the installer appliction when 1) it's not 3368 // already set or 2) the modified package is the installer 3369 if (mInstantAppInstallerActivity != null 3370 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3371 .equals(modifiedPackage)) { 3372 return; 3373 } 3374 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3375 } 3376 3377 private static File preparePackageParserCache(boolean isUpgrade) { 3378 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3379 return null; 3380 } 3381 3382 // Disable package parsing on eng builds to allow for faster incremental development. 3383 if (Build.IS_ENG) { 3384 return null; 3385 } 3386 3387 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3388 Slog.i(TAG, "Disabling package parser cache due to system property."); 3389 return null; 3390 } 3391 3392 // The base directory for the package parser cache lives under /data/system/. 3393 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3394 "package_cache"); 3395 if (cacheBaseDir == null) { 3396 return null; 3397 } 3398 3399 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3400 // This also serves to "GC" unused entries when the package cache version changes (which 3401 // can only happen during upgrades). 3402 if (isUpgrade) { 3403 FileUtils.deleteContents(cacheBaseDir); 3404 } 3405 3406 3407 // Return the versioned package cache directory. This is something like 3408 // "/data/system/package_cache/1" 3409 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3410 3411 if (cacheDir == null) { 3412 // Something went wrong. Attempt to delete everything and return. 3413 Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir); 3414 FileUtils.deleteContentsAndDir(cacheBaseDir); 3415 return null; 3416 } 3417 3418 // The following is a workaround to aid development on non-numbered userdebug 3419 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3420 // the system partition is newer. 3421 // 3422 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3423 // that starts with "eng." to signify that this is an engineering build and not 3424 // destined for release. 3425 if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3426 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3427 3428 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3429 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3430 // in general and should not be used for production changes. In this specific case, 3431 // we know that they will work. 3432 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3433 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3434 FileUtils.deleteContents(cacheBaseDir); 3435 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3436 } 3437 } 3438 3439 return cacheDir; 3440 } 3441 3442 @Override 3443 public boolean isFirstBoot() { 3444 // allow instant applications 3445 return mFirstBoot; 3446 } 3447 3448 @Override 3449 public boolean isOnlyCoreApps() { 3450 // allow instant applications 3451 return mOnlyCore; 3452 } 3453 3454 @Override 3455 public boolean isUpgrade() { 3456 // allow instant applications 3457 // The system property allows testing ota flow when upgraded to the same image. 3458 return mIsUpgrade || SystemProperties.getBoolean( 3459 "persist.pm.mock-upgrade", false /* default */); 3460 } 3461 3462 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3463 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3464 3465 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3466 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3467 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3468 if (matches.size() == 1) { 3469 return matches.get(0).getComponentInfo().packageName; 3470 } else if (matches.size() == 0) { 3471 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3472 return null; 3473 } 3474 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3475 } 3476 3477 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3478 synchronized (mPackages) { 3479 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3480 if (libraryEntry == null) { 3481 throw new IllegalStateException("Missing required shared library:" + name); 3482 } 3483 return libraryEntry.apk; 3484 } 3485 } 3486 3487 private @NonNull String getRequiredInstallerLPr() { 3488 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3489 intent.addCategory(Intent.CATEGORY_DEFAULT); 3490 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3491 3492 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3493 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3494 UserHandle.USER_SYSTEM); 3495 if (matches.size() == 1) { 3496 ResolveInfo resolveInfo = matches.get(0); 3497 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3498 throw new RuntimeException("The installer must be a privileged app"); 3499 } 3500 return matches.get(0).getComponentInfo().packageName; 3501 } else { 3502 throw new RuntimeException("There must be exactly one installer; found " + matches); 3503 } 3504 } 3505 3506 private @NonNull String getRequiredUninstallerLPr() { 3507 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3508 intent.addCategory(Intent.CATEGORY_DEFAULT); 3509 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3510 3511 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3512 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3513 UserHandle.USER_SYSTEM); 3514 if (resolveInfo == null || 3515 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3516 throw new RuntimeException("There must be exactly one uninstaller; found " 3517 + resolveInfo); 3518 } 3519 return resolveInfo.getComponentInfo().packageName; 3520 } 3521 3522 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3523 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3524 3525 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3526 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3527 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3528 ResolveInfo best = null; 3529 final int N = matches.size(); 3530 for (int i = 0; i < N; i++) { 3531 final ResolveInfo cur = matches.get(i); 3532 final String packageName = cur.getComponentInfo().packageName; 3533 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3534 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3535 continue; 3536 } 3537 3538 if (best == null || cur.priority > best.priority) { 3539 best = cur; 3540 } 3541 } 3542 3543 if (best != null) { 3544 return best.getComponentInfo().getComponentName(); 3545 } 3546 Slog.w(TAG, "Intent filter verifier not found"); 3547 return null; 3548 } 3549 3550 @Override 3551 public @Nullable ComponentName getInstantAppResolverComponent() { 3552 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3553 return null; 3554 } 3555 synchronized (mPackages) { 3556 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3557 if (instantAppResolver == null) { 3558 return null; 3559 } 3560 return instantAppResolver.first; 3561 } 3562 } 3563 3564 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3565 final String[] packageArray = 3566 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3567 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3568 if (DEBUG_INSTANT) { 3569 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3570 } 3571 return null; 3572 } 3573 3574 final int callingUid = Binder.getCallingUid(); 3575 final int resolveFlags = 3576 MATCH_DIRECT_BOOT_AWARE 3577 | MATCH_DIRECT_BOOT_UNAWARE 3578 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3579 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3580 final Intent resolverIntent = new Intent(actionName); 3581 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3582 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3583 final int N = resolvers.size(); 3584 if (N == 0) { 3585 if (DEBUG_INSTANT) { 3586 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3587 } 3588 return null; 3589 } 3590 3591 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3592 for (int i = 0; i < N; i++) { 3593 final ResolveInfo info = resolvers.get(i); 3594 3595 if (info.serviceInfo == null) { 3596 continue; 3597 } 3598 3599 final String packageName = info.serviceInfo.packageName; 3600 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3601 if (DEBUG_INSTANT) { 3602 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3603 + " pkg: " + packageName + ", info:" + info); 3604 } 3605 continue; 3606 } 3607 3608 if (DEBUG_INSTANT) { 3609 Slog.v(TAG, "Ephemeral resolver found;" 3610 + " pkg: " + packageName + ", info:" + info); 3611 } 3612 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3613 } 3614 if (DEBUG_INSTANT) { 3615 Slog.v(TAG, "Ephemeral resolver NOT found"); 3616 } 3617 return null; 3618 } 3619 3620 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3621 String[] orderedActions = Build.IS_ENG 3622 ? new String[]{ 3623 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST", 3624 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE} 3625 : new String[]{ 3626 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}; 3627 3628 final int resolveFlags = 3629 MATCH_DIRECT_BOOT_AWARE 3630 | MATCH_DIRECT_BOOT_UNAWARE 3631 | Intent.FLAG_IGNORE_EPHEMERAL 3632 | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0); 3633 final Intent intent = new Intent(); 3634 intent.addCategory(Intent.CATEGORY_DEFAULT); 3635 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3636 List<ResolveInfo> matches = null; 3637 for (String action : orderedActions) { 3638 intent.setAction(action); 3639 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3640 resolveFlags, UserHandle.USER_SYSTEM); 3641 if (matches.isEmpty()) { 3642 if (DEBUG_INSTANT) { 3643 Slog.d(TAG, "Instant App installer not found with " + action); 3644 } 3645 } else { 3646 break; 3647 } 3648 } 3649 Iterator<ResolveInfo> iter = matches.iterator(); 3650 while (iter.hasNext()) { 3651 final ResolveInfo rInfo = iter.next(); 3652 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3653 if (ps != null) { 3654 final PermissionsState permissionsState = ps.getPermissionsState(); 3655 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0) 3656 || Build.IS_ENG) { 3657 continue; 3658 } 3659 } 3660 iter.remove(); 3661 } 3662 if (matches.size() == 0) { 3663 return null; 3664 } else if (matches.size() == 1) { 3665 return (ActivityInfo) matches.get(0).getComponentInfo(); 3666 } else { 3667 throw new RuntimeException( 3668 "There must be at most one ephemeral installer; found " + matches); 3669 } 3670 } 3671 3672 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3673 @NonNull ComponentName resolver) { 3674 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3675 .addCategory(Intent.CATEGORY_DEFAULT) 3676 .setPackage(resolver.getPackageName()); 3677 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3678 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3679 UserHandle.USER_SYSTEM); 3680 if (matches.isEmpty()) { 3681 return null; 3682 } 3683 return matches.get(0).getComponentInfo().getComponentName(); 3684 } 3685 3686 private void primeDomainVerificationsLPw(int userId) { 3687 if (DEBUG_DOMAIN_VERIFICATION) { 3688 Slog.d(TAG, "Priming domain verifications in user " + userId); 3689 } 3690 3691 SystemConfig systemConfig = SystemConfig.getInstance(); 3692 ArraySet<String> packages = systemConfig.getLinkedApps(); 3693 3694 for (String packageName : packages) { 3695 PackageParser.Package pkg = mPackages.get(packageName); 3696 if (pkg != null) { 3697 if (!pkg.isSystem()) { 3698 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3699 continue; 3700 } 3701 3702 ArraySet<String> domains = null; 3703 for (PackageParser.Activity a : pkg.activities) { 3704 for (ActivityIntentInfo filter : a.intents) { 3705 if (hasValidDomains(filter)) { 3706 if (domains == null) { 3707 domains = new ArraySet<String>(); 3708 } 3709 domains.addAll(filter.getHostsList()); 3710 } 3711 } 3712 } 3713 3714 if (domains != null && domains.size() > 0) { 3715 if (DEBUG_DOMAIN_VERIFICATION) { 3716 Slog.v(TAG, " + " + packageName); 3717 } 3718 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3719 // state w.r.t. the formal app-linkage "no verification attempted" state; 3720 // and then 'always' in the per-user state actually used for intent resolution. 3721 final IntentFilterVerificationInfo ivi; 3722 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3723 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3724 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3725 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3726 } else { 3727 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3728 + "' does not handle web links"); 3729 } 3730 } else { 3731 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3732 } 3733 } 3734 3735 scheduleWritePackageRestrictionsLocked(userId); 3736 scheduleWriteSettingsLocked(); 3737 } 3738 3739 private void applyFactoryDefaultBrowserLPw(int userId) { 3740 // The default browser app's package name is stored in a string resource, 3741 // with a product-specific overlay used for vendor customization. 3742 String browserPkg = mContext.getResources().getString( 3743 com.android.internal.R.string.default_browser); 3744 if (!TextUtils.isEmpty(browserPkg)) { 3745 // non-empty string => required to be a known package 3746 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3747 if (ps == null) { 3748 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3749 browserPkg = null; 3750 } else { 3751 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3752 } 3753 } 3754 3755 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3756 // default. If there's more than one, just leave everything alone. 3757 if (browserPkg == null) { 3758 calculateDefaultBrowserLPw(userId); 3759 } 3760 } 3761 3762 private void calculateDefaultBrowserLPw(int userId) { 3763 List<String> allBrowsers = resolveAllBrowserApps(userId); 3764 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3765 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3766 } 3767 3768 private List<String> resolveAllBrowserApps(int userId) { 3769 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3770 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3771 PackageManager.MATCH_ALL, userId); 3772 3773 final int count = list.size(); 3774 List<String> result = new ArrayList<String>(count); 3775 for (int i=0; i<count; i++) { 3776 ResolveInfo info = list.get(i); 3777 if (info.activityInfo == null 3778 || !info.handleAllWebDataURI 3779 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3780 || result.contains(info.activityInfo.packageName)) { 3781 continue; 3782 } 3783 result.add(info.activityInfo.packageName); 3784 } 3785 3786 return result; 3787 } 3788 3789 private boolean packageIsBrowser(String packageName, int userId) { 3790 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3791 PackageManager.MATCH_ALL, userId); 3792 final int N = list.size(); 3793 for (int i = 0; i < N; i++) { 3794 ResolveInfo info = list.get(i); 3795 if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) { 3796 return true; 3797 } 3798 } 3799 return false; 3800 } 3801 3802 private void checkDefaultBrowser() { 3803 final int myUserId = UserHandle.myUserId(); 3804 final String packageName = getDefaultBrowserPackageName(myUserId); 3805 if (packageName != null) { 3806 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3807 if (info == null) { 3808 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3809 synchronized (mPackages) { 3810 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3811 } 3812 } 3813 } 3814 } 3815 3816 @Override 3817 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3818 throws RemoteException { 3819 try { 3820 return super.onTransact(code, data, reply, flags); 3821 } catch (RuntimeException e) { 3822 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3823 Slog.wtf(TAG, "Package Manager Crash", e); 3824 } 3825 throw e; 3826 } 3827 } 3828 3829 static int[] appendInts(int[] cur, int[] add) { 3830 if (add == null) return cur; 3831 if (cur == null) return add; 3832 final int N = add.length; 3833 for (int i=0; i<N; i++) { 3834 cur = appendInt(cur, add[i]); 3835 } 3836 return cur; 3837 } 3838 3839 /** 3840 * Returns whether or not a full application can see an instant application. 3841 * <p> 3842 * Currently, there are three cases in which this can occur: 3843 * <ol> 3844 * <li>The calling application is a "special" process. Special processes 3845 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 3846 * <li>The calling application has the permission 3847 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 3848 * <li>The calling application is the default launcher on the 3849 * system partition.</li> 3850 * </ol> 3851 */ 3852 private boolean canViewInstantApps(int callingUid, int userId) { 3853 if (callingUid < Process.FIRST_APPLICATION_UID) { 3854 return true; 3855 } 3856 if (mContext.checkCallingOrSelfPermission( 3857 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3858 return true; 3859 } 3860 if (mContext.checkCallingOrSelfPermission( 3861 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3862 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3863 if (homeComponent != null 3864 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3865 return true; 3866 } 3867 } 3868 return false; 3869 } 3870 3871 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3872 if (!sUserManager.exists(userId)) return null; 3873 if (ps == null) { 3874 return null; 3875 } 3876 final int callingUid = Binder.getCallingUid(); 3877 // Filter out ephemeral app metadata: 3878 // * The system/shell/root can see metadata for any app 3879 // * An installed app can see metadata for 1) other installed apps 3880 // and 2) ephemeral apps that have explicitly interacted with it 3881 // * Ephemeral apps can only see their own data and exposed installed apps 3882 // * Holding a signature permission allows seeing instant apps 3883 if (filterAppAccessLPr(ps, callingUid, userId)) { 3884 return null; 3885 } 3886 3887 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3888 && ps.isSystem()) { 3889 flags |= MATCH_ANY_USER; 3890 } 3891 3892 final PackageUserState state = ps.readUserState(userId); 3893 PackageParser.Package p = ps.pkg; 3894 if (p != null) { 3895 final PermissionsState permissionsState = ps.getPermissionsState(); 3896 3897 // Compute GIDs only if requested 3898 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3899 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3900 // Compute granted permissions only if package has requested permissions 3901 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3902 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3903 3904 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3905 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3906 3907 if (packageInfo == null) { 3908 return null; 3909 } 3910 3911 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3912 resolveExternalPackageNameLPr(p); 3913 3914 return packageInfo; 3915 } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) { 3916 PackageInfo pi = new PackageInfo(); 3917 pi.packageName = ps.name; 3918 pi.setLongVersionCode(ps.versionCode); 3919 pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null; 3920 pi.firstInstallTime = ps.firstInstallTime; 3921 pi.lastUpdateTime = ps.lastUpdateTime; 3922 3923 ApplicationInfo ai = new ApplicationInfo(); 3924 ai.packageName = ps.name; 3925 ai.uid = UserHandle.getUid(userId, ps.appId); 3926 ai.primaryCpuAbi = ps.primaryCpuAbiString; 3927 ai.secondaryCpuAbi = ps.secondaryCpuAbiString; 3928 ai.versionCode = ps.versionCode; 3929 ai.flags = ps.pkgFlags; 3930 ai.privateFlags = ps.pkgPrivateFlags; 3931 pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId); 3932 3933 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for [" 3934 + ps.name + "]. Provides a minimum info."); 3935 return pi; 3936 } else { 3937 return null; 3938 } 3939 } 3940 3941 @Override 3942 public void checkPackageStartable(String packageName, int userId) { 3943 final int callingUid = Binder.getCallingUid(); 3944 if (getInstantAppPackageName(callingUid) != null) { 3945 throw new SecurityException("Instant applications don't have access to this method"); 3946 } 3947 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3948 synchronized (mPackages) { 3949 final PackageSetting ps = mSettings.mPackages.get(packageName); 3950 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 3951 throw new SecurityException("Package " + packageName + " was not found!"); 3952 } 3953 3954 if (!ps.getInstalled(userId)) { 3955 throw new SecurityException( 3956 "Package " + packageName + " was not installed for user " + userId + "!"); 3957 } 3958 3959 if (mSafeMode && !ps.isSystem()) { 3960 throw new SecurityException("Package " + packageName + " not a system app!"); 3961 } 3962 3963 if (mFrozenPackages.contains(packageName)) { 3964 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3965 } 3966 3967 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) { 3968 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3969 } 3970 } 3971 } 3972 3973 @Override 3974 public boolean isPackageAvailable(String packageName, int userId) { 3975 if (!sUserManager.exists(userId)) return false; 3976 final int callingUid = Binder.getCallingUid(); 3977 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 3978 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 3979 synchronized (mPackages) { 3980 PackageParser.Package p = mPackages.get(packageName); 3981 if (p != null) { 3982 final PackageSetting ps = (PackageSetting) p.mExtras; 3983 if (filterAppAccessLPr(ps, callingUid, userId)) { 3984 return false; 3985 } 3986 if (ps != null) { 3987 final PackageUserState state = ps.readUserState(userId); 3988 if (state != null) { 3989 return PackageParser.isAvailable(state); 3990 } 3991 } 3992 } 3993 } 3994 return false; 3995 } 3996 3997 @Override 3998 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3999 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 4000 flags, Binder.getCallingUid(), userId); 4001 } 4002 4003 @Override 4004 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 4005 int flags, int userId) { 4006 return getPackageInfoInternal(versionedPackage.getPackageName(), 4007 versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId); 4008 } 4009 4010 /** 4011 * Important: The provided filterCallingUid is used exclusively to filter out packages 4012 * that can be seen based on user state. It's typically the original caller uid prior 4013 * to clearing. Because it can only be provided by trusted code, it's value can be 4014 * trusted and will be used as-is; unlike userId which will be validated by this method. 4015 */ 4016 private PackageInfo getPackageInfoInternal(String packageName, long versionCode, 4017 int flags, int filterCallingUid, int userId) { 4018 if (!sUserManager.exists(userId)) return null; 4019 flags = updateFlagsForPackage(flags, userId, packageName); 4020 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4021 false /* requireFullPermission */, false /* checkShell */, "get package info"); 4022 4023 // reader 4024 synchronized (mPackages) { 4025 // Normalize package name to handle renamed packages and static libs 4026 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 4027 4028 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 4029 if (matchFactoryOnly) { 4030 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 4031 if (ps != null) { 4032 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4033 return null; 4034 } 4035 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4036 return null; 4037 } 4038 return generatePackageInfo(ps, flags, userId); 4039 } 4040 } 4041 4042 PackageParser.Package p = mPackages.get(packageName); 4043 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 4044 return null; 4045 } 4046 if (DEBUG_PACKAGE_INFO) 4047 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 4048 if (p != null) { 4049 final PackageSetting ps = (PackageSetting) p.mExtras; 4050 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4051 return null; 4052 } 4053 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 4054 return null; 4055 } 4056 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 4057 } 4058 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 4059 final PackageSetting ps = mSettings.mPackages.get(packageName); 4060 if (ps == null) return null; 4061 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4062 return null; 4063 } 4064 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4065 return null; 4066 } 4067 return generatePackageInfo(ps, flags, userId); 4068 } 4069 } 4070 return null; 4071 } 4072 4073 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 4074 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 4075 return true; 4076 } 4077 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 4078 return true; 4079 } 4080 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 4081 return true; 4082 } 4083 return false; 4084 } 4085 4086 private boolean isComponentVisibleToInstantApp( 4087 @Nullable ComponentName component, @ComponentType int type) { 4088 if (type == TYPE_ACTIVITY) { 4089 final PackageParser.Activity activity = mActivities.mActivities.get(component); 4090 if (activity == null) { 4091 return false; 4092 } 4093 final boolean visibleToInstantApp = 4094 (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 4095 final boolean explicitlyVisibleToInstantApp = 4096 (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 4097 return visibleToInstantApp && explicitlyVisibleToInstantApp; 4098 } else if (type == TYPE_RECEIVER) { 4099 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 4100 if (activity == null) { 4101 return false; 4102 } 4103 final boolean visibleToInstantApp = 4104 (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 4105 final boolean explicitlyVisibleToInstantApp = 4106 (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 4107 return visibleToInstantApp && !explicitlyVisibleToInstantApp; 4108 } else if (type == TYPE_SERVICE) { 4109 final PackageParser.Service service = mServices.mServices.get(component); 4110 return service != null 4111 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4112 : false; 4113 } else if (type == TYPE_PROVIDER) { 4114 final PackageParser.Provider provider = mProviders.mProviders.get(component); 4115 return provider != null 4116 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4117 : false; 4118 } else if (type == TYPE_UNKNOWN) { 4119 return isComponentVisibleToInstantApp(component); 4120 } 4121 return false; 4122 } 4123 4124 /** 4125 * Returns whether or not access to the application should be filtered. 4126 * <p> 4127 * Access may be limited based upon whether the calling or target applications 4128 * are instant applications. 4129 * 4130 * @see #canAccessInstantApps(int) 4131 */ 4132 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 4133 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 4134 // if we're in an isolated process, get the real calling UID 4135 if (Process.isIsolated(callingUid)) { 4136 callingUid = mIsolatedOwners.get(callingUid); 4137 } 4138 final String instantAppPkgName = getInstantAppPackageName(callingUid); 4139 final boolean callerIsInstantApp = instantAppPkgName != null; 4140 if (ps == null) { 4141 if (callerIsInstantApp) { 4142 // pretend the application exists, but, needs to be filtered 4143 return true; 4144 } 4145 return false; 4146 } 4147 // if the target and caller are the same application, don't filter 4148 if (isCallerSameApp(ps.name, callingUid)) { 4149 return false; 4150 } 4151 if (callerIsInstantApp) { 4152 // both caller and target are both instant, but, different applications, filter 4153 if (ps.getInstantApp(userId)) { 4154 return true; 4155 } 4156 // request for a specific component; if it hasn't been explicitly exposed through 4157 // property or instrumentation target, filter 4158 if (component != null) { 4159 final PackageParser.Instrumentation instrumentation = 4160 mInstrumentation.get(component); 4161 if (instrumentation != null 4162 && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) { 4163 return false; 4164 } 4165 return !isComponentVisibleToInstantApp(component, componentType); 4166 } 4167 // request for application; if no components have been explicitly exposed, filter 4168 return !ps.pkg.visibleToInstantApps; 4169 } 4170 if (ps.getInstantApp(userId)) { 4171 // caller can see all components of all instant applications, don't filter 4172 if (canViewInstantApps(callingUid, userId)) { 4173 return false; 4174 } 4175 // request for a specific instant application component, filter 4176 if (component != null) { 4177 return true; 4178 } 4179 // request for an instant application; if the caller hasn't been granted access, filter 4180 return !mInstantAppRegistry.isInstantAccessGranted( 4181 userId, UserHandle.getAppId(callingUid), ps.appId); 4182 } 4183 return false; 4184 } 4185 4186 /** 4187 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 4188 */ 4189 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 4190 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 4191 } 4192 4193 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 4194 int flags) { 4195 // Callers can access only the libs they depend on, otherwise they need to explicitly 4196 // ask for the shared libraries given the caller is allowed to access all static libs. 4197 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 4198 // System/shell/root get to see all static libs 4199 final int appId = UserHandle.getAppId(uid); 4200 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 4201 || appId == Process.ROOT_UID) { 4202 return false; 4203 } 4204 } 4205 4206 // No package means no static lib as it is always on internal storage 4207 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4208 return false; 4209 } 4210 4211 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 4212 ps.pkg.staticSharedLibVersion); 4213 if (libEntry == null) { 4214 return false; 4215 } 4216 4217 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 4218 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 4219 if (uidPackageNames == null) { 4220 return true; 4221 } 4222 4223 for (String uidPackageName : uidPackageNames) { 4224 if (ps.name.equals(uidPackageName)) { 4225 return false; 4226 } 4227 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 4228 if (uidPs != null) { 4229 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 4230 libEntry.info.getName()); 4231 if (index < 0) { 4232 continue; 4233 } 4234 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) { 4235 return false; 4236 } 4237 } 4238 } 4239 return true; 4240 } 4241 4242 @Override 4243 public String[] currentToCanonicalPackageNames(String[] names) { 4244 final int callingUid = Binder.getCallingUid(); 4245 if (getInstantAppPackageName(callingUid) != null) { 4246 return names; 4247 } 4248 final String[] out = new String[names.length]; 4249 // reader 4250 synchronized (mPackages) { 4251 final int callingUserId = UserHandle.getUserId(callingUid); 4252 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4253 for (int i=names.length-1; i>=0; i--) { 4254 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4255 boolean translateName = false; 4256 if (ps != null && ps.realName != null) { 4257 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 4258 translateName = !targetIsInstantApp 4259 || canViewInstantApps 4260 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4261 UserHandle.getAppId(callingUid), ps.appId); 4262 } 4263 out[i] = translateName ? ps.realName : names[i]; 4264 } 4265 } 4266 return out; 4267 } 4268 4269 @Override 4270 public String[] canonicalToCurrentPackageNames(String[] names) { 4271 final int callingUid = Binder.getCallingUid(); 4272 if (getInstantAppPackageName(callingUid) != null) { 4273 return names; 4274 } 4275 final String[] out = new String[names.length]; 4276 // reader 4277 synchronized (mPackages) { 4278 final int callingUserId = UserHandle.getUserId(callingUid); 4279 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4280 for (int i=names.length-1; i>=0; i--) { 4281 final String cur = mSettings.getRenamedPackageLPr(names[i]); 4282 boolean translateName = false; 4283 if (cur != null) { 4284 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4285 final boolean targetIsInstantApp = 4286 ps != null && ps.getInstantApp(callingUserId); 4287 translateName = !targetIsInstantApp 4288 || canViewInstantApps 4289 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4290 UserHandle.getAppId(callingUid), ps.appId); 4291 } 4292 out[i] = translateName ? cur : names[i]; 4293 } 4294 } 4295 return out; 4296 } 4297 4298 @Override 4299 public int getPackageUid(String packageName, int flags, int userId) { 4300 if (!sUserManager.exists(userId)) return -1; 4301 final int callingUid = Binder.getCallingUid(); 4302 flags = updateFlagsForPackage(flags, userId, packageName); 4303 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4304 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 4305 4306 // reader 4307 synchronized (mPackages) { 4308 final PackageParser.Package p = mPackages.get(packageName); 4309 if (p != null && p.isMatch(flags)) { 4310 PackageSetting ps = (PackageSetting) p.mExtras; 4311 if (filterAppAccessLPr(ps, callingUid, userId)) { 4312 return -1; 4313 } 4314 return UserHandle.getUid(userId, p.applicationInfo.uid); 4315 } 4316 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4317 final PackageSetting ps = mSettings.mPackages.get(packageName); 4318 if (ps != null && ps.isMatch(flags) 4319 && !filterAppAccessLPr(ps, callingUid, userId)) { 4320 return UserHandle.getUid(userId, ps.appId); 4321 } 4322 } 4323 } 4324 4325 return -1; 4326 } 4327 4328 @Override 4329 public int[] getPackageGids(String packageName, int flags, int userId) { 4330 if (!sUserManager.exists(userId)) return null; 4331 final int callingUid = Binder.getCallingUid(); 4332 flags = updateFlagsForPackage(flags, userId, packageName); 4333 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4334 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 4335 4336 // reader 4337 synchronized (mPackages) { 4338 final PackageParser.Package p = mPackages.get(packageName); 4339 if (p != null && p.isMatch(flags)) { 4340 PackageSetting ps = (PackageSetting) p.mExtras; 4341 if (filterAppAccessLPr(ps, callingUid, userId)) { 4342 return null; 4343 } 4344 // TODO: Shouldn't this be checking for package installed state for userId and 4345 // return null? 4346 return ps.getPermissionsState().computeGids(userId); 4347 } 4348 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4349 final PackageSetting ps = mSettings.mPackages.get(packageName); 4350 if (ps != null && ps.isMatch(flags) 4351 && !filterAppAccessLPr(ps, callingUid, userId)) { 4352 return ps.getPermissionsState().computeGids(userId); 4353 } 4354 } 4355 } 4356 4357 return null; 4358 } 4359 4360 @Override 4361 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4362 return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid()); 4363 } 4364 4365 @Override 4366 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName, 4367 int flags) { 4368 final List<PermissionInfo> permissionList = 4369 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()); 4370 return (permissionList == null) ? null : new ParceledListSlice<>(permissionList); 4371 } 4372 4373 @Override 4374 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) { 4375 return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid()); 4376 } 4377 4378 @Override 4379 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4380 final List<PermissionGroupInfo> permissionList = 4381 mPermissionManager.getAllPermissionGroups(flags, getCallingUid()); 4382 return (permissionList == null) 4383 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList); 4384 } 4385 4386 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4387 int filterCallingUid, int userId) { 4388 if (!sUserManager.exists(userId)) return null; 4389 PackageSetting ps = mSettings.mPackages.get(packageName); 4390 if (ps != null) { 4391 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4392 return null; 4393 } 4394 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4395 return null; 4396 } 4397 if (ps.pkg == null) { 4398 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4399 if (pInfo != null) { 4400 return pInfo.applicationInfo; 4401 } 4402 return null; 4403 } 4404 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4405 ps.readUserState(userId), userId); 4406 if (ai != null) { 4407 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4408 } 4409 return ai; 4410 } 4411 return null; 4412 } 4413 4414 @Override 4415 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4416 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4417 } 4418 4419 /** 4420 * Important: The provided filterCallingUid is used exclusively to filter out applications 4421 * that can be seen based on user state. It's typically the original caller uid prior 4422 * to clearing. Because it can only be provided by trusted code, it's value can be 4423 * trusted and will be used as-is; unlike userId which will be validated by this method. 4424 */ 4425 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4426 int filterCallingUid, int userId) { 4427 if (!sUserManager.exists(userId)) return null; 4428 flags = updateFlagsForApplication(flags, userId, packageName); 4429 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4430 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4431 4432 // writer 4433 synchronized (mPackages) { 4434 // Normalize package name to handle renamed packages and static libs 4435 packageName = resolveInternalPackageNameLPr(packageName, 4436 PackageManager.VERSION_CODE_HIGHEST); 4437 4438 PackageParser.Package p = mPackages.get(packageName); 4439 if (DEBUG_PACKAGE_INFO) Log.v( 4440 TAG, "getApplicationInfo " + packageName 4441 + ": " + p); 4442 if (p != null) { 4443 PackageSetting ps = mSettings.mPackages.get(packageName); 4444 if (ps == null) return null; 4445 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4446 return null; 4447 } 4448 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4449 return null; 4450 } 4451 // Note: isEnabledLP() does not apply here - always return info 4452 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4453 p, flags, ps.readUserState(userId), userId); 4454 if (ai != null) { 4455 ai.packageName = resolveExternalPackageNameLPr(p); 4456 } 4457 return ai; 4458 } 4459 if ("android".equals(packageName)||"system".equals(packageName)) { 4460 return mAndroidApplication; 4461 } 4462 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4463 // Already generates the external package name 4464 return generateApplicationInfoFromSettingsLPw(packageName, 4465 flags, filterCallingUid, userId); 4466 } 4467 } 4468 return null; 4469 } 4470 4471 private String normalizePackageNameLPr(String packageName) { 4472 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4473 return normalizedPackageName != null ? normalizedPackageName : packageName; 4474 } 4475 4476 @Override 4477 public void deletePreloadsFileCache() { 4478 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4479 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4480 } 4481 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4482 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4483 FileUtils.deleteContents(dir); 4484 } 4485 4486 @Override 4487 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4488 final int storageFlags, final IPackageDataObserver observer) { 4489 mContext.enforceCallingOrSelfPermission( 4490 android.Manifest.permission.CLEAR_APP_CACHE, null); 4491 mHandler.post(() -> { 4492 boolean success = false; 4493 try { 4494 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4495 success = true; 4496 } catch (IOException e) { 4497 Slog.w(TAG, e); 4498 } 4499 if (observer != null) { 4500 try { 4501 observer.onRemoveCompleted(null, success); 4502 } catch (RemoteException e) { 4503 Slog.w(TAG, e); 4504 } 4505 } 4506 }); 4507 } 4508 4509 @Override 4510 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4511 final int storageFlags, final IntentSender pi) { 4512 mContext.enforceCallingOrSelfPermission( 4513 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4514 mHandler.post(() -> { 4515 boolean success = false; 4516 try { 4517 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4518 success = true; 4519 } catch (IOException e) { 4520 Slog.w(TAG, e); 4521 } 4522 if (pi != null) { 4523 try { 4524 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4525 } catch (SendIntentException e) { 4526 Slog.w(TAG, e); 4527 } 4528 } 4529 }); 4530 } 4531 4532 /** 4533 * Blocking call to clear various types of cached data across the system 4534 * until the requested bytes are available. 4535 */ 4536 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4537 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4538 final File file = storage.findPathForUuid(volumeUuid); 4539 if (file.getUsableSpace() >= bytes) return; 4540 4541 if (ENABLE_FREE_CACHE_V2) { 4542 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4543 volumeUuid); 4544 final boolean aggressive = (storageFlags 4545 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4546 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags); 4547 4548 // 1. Pre-flight to determine if we have any chance to succeed 4549 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4550 if (internalVolume && (aggressive || SystemProperties 4551 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4552 deletePreloadsFileCache(); 4553 if (file.getUsableSpace() >= bytes) return; 4554 } 4555 4556 // 3. Consider parsed APK data (aggressive only) 4557 if (internalVolume && aggressive) { 4558 FileUtils.deleteContents(mCacheDir); 4559 if (file.getUsableSpace() >= bytes) return; 4560 } 4561 4562 // 4. Consider cached app data (above quotas) 4563 try { 4564 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4565 Installer.FLAG_FREE_CACHE_V2); 4566 } catch (InstallerException ignored) { 4567 } 4568 if (file.getUsableSpace() >= bytes) return; 4569 4570 // 5. Consider shared libraries with refcount=0 and age>min cache period 4571 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4572 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4573 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4574 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4575 return; 4576 } 4577 4578 // 6. Consider dexopt output (aggressive only) 4579 // TODO: Implement 4580 4581 // 7. Consider installed instant apps unused longer than min cache period 4582 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4583 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4584 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4585 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4586 return; 4587 } 4588 4589 // 8. Consider cached app data (below quotas) 4590 try { 4591 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4592 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4593 } catch (InstallerException ignored) { 4594 } 4595 if (file.getUsableSpace() >= bytes) return; 4596 4597 // 9. Consider DropBox entries 4598 // TODO: Implement 4599 4600 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4601 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4602 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4603 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4604 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4605 return; 4606 } 4607 } else { 4608 try { 4609 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4610 } catch (InstallerException ignored) { 4611 } 4612 if (file.getUsableSpace() >= bytes) return; 4613 } 4614 4615 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4616 } 4617 4618 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4619 throws IOException { 4620 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4621 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4622 4623 List<VersionedPackage> packagesToDelete = null; 4624 final long now = System.currentTimeMillis(); 4625 4626 synchronized (mPackages) { 4627 final int[] allUsers = sUserManager.getUserIds(); 4628 final int libCount = mSharedLibraries.size(); 4629 for (int i = 0; i < libCount; i++) { 4630 final LongSparseArray<SharedLibraryEntry> versionedLib 4631 = mSharedLibraries.valueAt(i); 4632 if (versionedLib == null) { 4633 continue; 4634 } 4635 final int versionCount = versionedLib.size(); 4636 for (int j = 0; j < versionCount; j++) { 4637 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4638 // Skip packages that are not static shared libs. 4639 if (!libInfo.isStatic()) { 4640 break; 4641 } 4642 // Important: We skip static shared libs used for some user since 4643 // in such a case we need to keep the APK on the device. The check for 4644 // a lib being used for any user is performed by the uninstall call. 4645 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4646 // Resolve the package name - we use synthetic package names internally 4647 final String internalPackageName = resolveInternalPackageNameLPr( 4648 declaringPackage.getPackageName(), 4649 declaringPackage.getLongVersionCode()); 4650 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4651 // Skip unused static shared libs cached less than the min period 4652 // to prevent pruning a lib needed by a subsequently installed package. 4653 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4654 continue; 4655 } 4656 if (packagesToDelete == null) { 4657 packagesToDelete = new ArrayList<>(); 4658 } 4659 packagesToDelete.add(new VersionedPackage(internalPackageName, 4660 declaringPackage.getLongVersionCode())); 4661 } 4662 } 4663 } 4664 4665 if (packagesToDelete != null) { 4666 final int packageCount = packagesToDelete.size(); 4667 for (int i = 0; i < packageCount; i++) { 4668 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4669 // Delete the package synchronously (will fail of the lib used for any user). 4670 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(), 4671 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4672 == PackageManager.DELETE_SUCCEEDED) { 4673 if (volume.getUsableSpace() >= neededSpace) { 4674 return true; 4675 } 4676 } 4677 } 4678 } 4679 4680 return false; 4681 } 4682 4683 /** 4684 * Update given flags based on encryption status of current user. 4685 */ 4686 private int updateFlags(int flags, int userId) { 4687 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4688 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4689 // Caller expressed an explicit opinion about what encryption 4690 // aware/unaware components they want to see, so fall through and 4691 // give them what they want 4692 } else { 4693 // Caller expressed no opinion, so match based on user state 4694 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4695 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4696 } else { 4697 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4698 } 4699 } 4700 return flags; 4701 } 4702 4703 private UserManagerInternal getUserManagerInternal() { 4704 if (mUserManagerInternal == null) { 4705 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4706 } 4707 return mUserManagerInternal; 4708 } 4709 4710 private ActivityManagerInternal getActivityManagerInternal() { 4711 if (mActivityManagerInternal == null) { 4712 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class); 4713 } 4714 return mActivityManagerInternal; 4715 } 4716 4717 4718 private DeviceIdleController.LocalService getDeviceIdleController() { 4719 if (mDeviceIdleController == null) { 4720 mDeviceIdleController = 4721 LocalServices.getService(DeviceIdleController.LocalService.class); 4722 } 4723 return mDeviceIdleController; 4724 } 4725 4726 /** 4727 * Update given flags when being used to request {@link PackageInfo}. 4728 */ 4729 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4730 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4731 boolean triaged = true; 4732 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4733 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4734 // Caller is asking for component details, so they'd better be 4735 // asking for specific encryption matching behavior, or be triaged 4736 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4737 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4738 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4739 triaged = false; 4740 } 4741 } 4742 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4743 | PackageManager.MATCH_SYSTEM_ONLY 4744 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4745 triaged = false; 4746 } 4747 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4748 mPermissionManager.enforceCrossUserPermission( 4749 Binder.getCallingUid(), userId, false, false, 4750 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4751 + Debug.getCallers(5)); 4752 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4753 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4754 // If the caller wants all packages and has a restricted profile associated with it, 4755 // then match all users. This is to make sure that launchers that need to access work 4756 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4757 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4758 flags |= PackageManager.MATCH_ANY_USER; 4759 } 4760 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4761 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4762 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4763 } 4764 return updateFlags(flags, userId); 4765 } 4766 4767 /** 4768 * Update given flags when being used to request {@link ApplicationInfo}. 4769 */ 4770 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4771 return updateFlagsForPackage(flags, userId, cookie); 4772 } 4773 4774 /** 4775 * Update given flags when being used to request {@link ComponentInfo}. 4776 */ 4777 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4778 if (cookie instanceof Intent) { 4779 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4780 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4781 } 4782 } 4783 4784 boolean triaged = true; 4785 // Caller is asking for component details, so they'd better be 4786 // asking for specific encryption matching behavior, or be triaged 4787 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4788 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4789 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4790 triaged = false; 4791 } 4792 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4793 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4794 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4795 } 4796 4797 return updateFlags(flags, userId); 4798 } 4799 4800 /** 4801 * Update given intent when being used to request {@link ResolveInfo}. 4802 */ 4803 private Intent updateIntentForResolve(Intent intent) { 4804 if (intent.getSelector() != null) { 4805 intent = intent.getSelector(); 4806 } 4807 if (DEBUG_PREFERRED) { 4808 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4809 } 4810 return intent; 4811 } 4812 4813 /** 4814 * Update given flags when being used to request {@link ResolveInfo}. 4815 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4816 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4817 * flag set. However, this flag is only honoured in three circumstances: 4818 * <ul> 4819 * <li>when called from a system process</li> 4820 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4821 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4822 * action and a {@code android.intent.category.BROWSABLE} category</li> 4823 * </ul> 4824 */ 4825 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4826 return updateFlagsForResolve(flags, userId, intent, callingUid, 4827 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4828 } 4829 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4830 boolean wantInstantApps) { 4831 return updateFlagsForResolve(flags, userId, intent, callingUid, 4832 wantInstantApps, false /*onlyExposedExplicitly*/); 4833 } 4834 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4835 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4836 // Safe mode means we shouldn't match any third-party components 4837 if (mSafeMode) { 4838 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4839 } 4840 if (getInstantAppPackageName(callingUid) != null) { 4841 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4842 if (onlyExposedExplicitly) { 4843 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4844 } 4845 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4846 flags |= PackageManager.MATCH_INSTANT; 4847 } else { 4848 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 4849 final boolean allowMatchInstant = wantInstantApps 4850 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 4851 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4852 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4853 if (!allowMatchInstant) { 4854 flags &= ~PackageManager.MATCH_INSTANT; 4855 } 4856 } 4857 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4858 } 4859 4860 @Override 4861 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4862 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 4863 } 4864 4865 /** 4866 * Important: The provided filterCallingUid is used exclusively to filter out activities 4867 * that can be seen based on user state. It's typically the original caller uid prior 4868 * to clearing. Because it can only be provided by trusted code, it's value can be 4869 * trusted and will be used as-is; unlike userId which will be validated by this method. 4870 */ 4871 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 4872 int filterCallingUid, int userId) { 4873 if (!sUserManager.exists(userId)) return null; 4874 flags = updateFlagsForComponent(flags, userId, component); 4875 4876 if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) { 4877 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4878 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4879 } 4880 4881 synchronized (mPackages) { 4882 PackageParser.Activity a = mActivities.mActivities.get(component); 4883 4884 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4885 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4886 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4887 if (ps == null) return null; 4888 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 4889 return null; 4890 } 4891 return PackageParser.generateActivityInfo( 4892 a, flags, ps.readUserState(userId), userId); 4893 } 4894 if (mResolveComponentName.equals(component)) { 4895 return PackageParser.generateActivityInfo( 4896 mResolveActivity, flags, new PackageUserState(), userId); 4897 } 4898 } 4899 return null; 4900 } 4901 4902 private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) { 4903 if (!getActivityManagerInternal().isCallerRecents(callingUid)) { 4904 return false; 4905 } 4906 final long token = Binder.clearCallingIdentity(); 4907 try { 4908 final int callingUserId = UserHandle.getUserId(callingUid); 4909 if (ActivityManager.getCurrentUser() != callingUserId) { 4910 return false; 4911 } 4912 return sUserManager.isSameProfileGroup(callingUserId, targetUserId); 4913 } finally { 4914 Binder.restoreCallingIdentity(token); 4915 } 4916 } 4917 4918 @Override 4919 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4920 String resolvedType) { 4921 synchronized (mPackages) { 4922 if (component.equals(mResolveComponentName)) { 4923 // The resolver supports EVERYTHING! 4924 return true; 4925 } 4926 final int callingUid = Binder.getCallingUid(); 4927 final int callingUserId = UserHandle.getUserId(callingUid); 4928 PackageParser.Activity a = mActivities.mActivities.get(component); 4929 if (a == null) { 4930 return false; 4931 } 4932 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4933 if (ps == null) { 4934 return false; 4935 } 4936 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4937 return false; 4938 } 4939 for (int i=0; i<a.intents.size(); i++) { 4940 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4941 intent.getData(), intent.getCategories(), TAG) >= 0) { 4942 return true; 4943 } 4944 } 4945 return false; 4946 } 4947 } 4948 4949 @Override 4950 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4951 if (!sUserManager.exists(userId)) return null; 4952 final int callingUid = Binder.getCallingUid(); 4953 flags = updateFlagsForComponent(flags, userId, component); 4954 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4955 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4956 synchronized (mPackages) { 4957 PackageParser.Activity a = mReceivers.mActivities.get(component); 4958 if (DEBUG_PACKAGE_INFO) Log.v( 4959 TAG, "getReceiverInfo " + component + ": " + a); 4960 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4961 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4962 if (ps == null) return null; 4963 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4964 return null; 4965 } 4966 return PackageParser.generateActivityInfo( 4967 a, flags, ps.readUserState(userId), userId); 4968 } 4969 } 4970 return null; 4971 } 4972 4973 @Override 4974 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4975 int flags, int userId) { 4976 if (!sUserManager.exists(userId)) return null; 4977 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4978 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4979 return null; 4980 } 4981 4982 flags = updateFlagsForPackage(flags, userId, null); 4983 4984 final boolean canSeeStaticLibraries = 4985 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4986 == PERMISSION_GRANTED 4987 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4988 == PERMISSION_GRANTED 4989 || canRequestPackageInstallsInternal(packageName, 4990 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 4991 false /* throwIfPermNotDeclared*/) 4992 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4993 == PERMISSION_GRANTED; 4994 4995 synchronized (mPackages) { 4996 List<SharedLibraryInfo> result = null; 4997 4998 final int libCount = mSharedLibraries.size(); 4999 for (int i = 0; i < libCount; i++) { 5000 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 5001 if (versionedLib == null) { 5002 continue; 5003 } 5004 5005 final int versionCount = versionedLib.size(); 5006 for (int j = 0; j < versionCount; j++) { 5007 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 5008 if (!canSeeStaticLibraries && libInfo.isStatic()) { 5009 break; 5010 } 5011 final long identity = Binder.clearCallingIdentity(); 5012 try { 5013 PackageInfo packageInfo = getPackageInfoVersioned( 5014 libInfo.getDeclaringPackage(), flags 5015 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 5016 if (packageInfo == null) { 5017 continue; 5018 } 5019 } finally { 5020 Binder.restoreCallingIdentity(identity); 5021 } 5022 5023 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 5024 libInfo.getLongVersion(), libInfo.getType(), 5025 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 5026 flags, userId)); 5027 5028 if (result == null) { 5029 result = new ArrayList<>(); 5030 } 5031 result.add(resLibInfo); 5032 } 5033 } 5034 5035 return result != null ? new ParceledListSlice<>(result) : null; 5036 } 5037 } 5038 5039 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 5040 SharedLibraryInfo libInfo, int flags, int userId) { 5041 List<VersionedPackage> versionedPackages = null; 5042 final int packageCount = mSettings.mPackages.size(); 5043 for (int i = 0; i < packageCount; i++) { 5044 PackageSetting ps = mSettings.mPackages.valueAt(i); 5045 5046 if (ps == null) { 5047 continue; 5048 } 5049 5050 if (!ps.getUserState().get(userId).isAvailable(flags)) { 5051 continue; 5052 } 5053 5054 final String libName = libInfo.getName(); 5055 if (libInfo.isStatic()) { 5056 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 5057 if (libIdx < 0) { 5058 continue; 5059 } 5060 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) { 5061 continue; 5062 } 5063 if (versionedPackages == null) { 5064 versionedPackages = new ArrayList<>(); 5065 } 5066 // If the dependent is a static shared lib, use the public package name 5067 String dependentPackageName = ps.name; 5068 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 5069 dependentPackageName = ps.pkg.manifestPackageName; 5070 } 5071 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 5072 } else if (ps.pkg != null) { 5073 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 5074 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 5075 if (versionedPackages == null) { 5076 versionedPackages = new ArrayList<>(); 5077 } 5078 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 5079 } 5080 } 5081 } 5082 5083 return versionedPackages; 5084 } 5085 5086 @Override 5087 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 5088 if (!sUserManager.exists(userId)) return null; 5089 final int callingUid = Binder.getCallingUid(); 5090 flags = updateFlagsForComponent(flags, userId, component); 5091 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5092 false /* requireFullPermission */, false /* checkShell */, "get service info"); 5093 synchronized (mPackages) { 5094 PackageParser.Service s = mServices.mServices.get(component); 5095 if (DEBUG_PACKAGE_INFO) Log.v( 5096 TAG, "getServiceInfo " + component + ": " + s); 5097 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 5098 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5099 if (ps == null) return null; 5100 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 5101 return null; 5102 } 5103 return PackageParser.generateServiceInfo( 5104 s, flags, ps.readUserState(userId), userId); 5105 } 5106 } 5107 return null; 5108 } 5109 5110 @Override 5111 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 5112 if (!sUserManager.exists(userId)) return null; 5113 final int callingUid = Binder.getCallingUid(); 5114 flags = updateFlagsForComponent(flags, userId, component); 5115 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5116 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 5117 synchronized (mPackages) { 5118 PackageParser.Provider p = mProviders.mProviders.get(component); 5119 if (DEBUG_PACKAGE_INFO) Log.v( 5120 TAG, "getProviderInfo " + component + ": " + p); 5121 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 5122 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5123 if (ps == null) return null; 5124 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 5125 return null; 5126 } 5127 return PackageParser.generateProviderInfo( 5128 p, flags, ps.readUserState(userId), userId); 5129 } 5130 } 5131 return null; 5132 } 5133 5134 @Override 5135 public String[] getSystemSharedLibraryNames() { 5136 // allow instant applications 5137 synchronized (mPackages) { 5138 Set<String> libs = null; 5139 final int libCount = mSharedLibraries.size(); 5140 for (int i = 0; i < libCount; i++) { 5141 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 5142 if (versionedLib == null) { 5143 continue; 5144 } 5145 final int versionCount = versionedLib.size(); 5146 for (int j = 0; j < versionCount; j++) { 5147 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 5148 if (!libEntry.info.isStatic()) { 5149 if (libs == null) { 5150 libs = new ArraySet<>(); 5151 } 5152 libs.add(libEntry.info.getName()); 5153 break; 5154 } 5155 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 5156 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 5157 UserHandle.getUserId(Binder.getCallingUid()), 5158 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 5159 if (libs == null) { 5160 libs = new ArraySet<>(); 5161 } 5162 libs.add(libEntry.info.getName()); 5163 break; 5164 } 5165 } 5166 } 5167 5168 if (libs != null) { 5169 String[] libsArray = new String[libs.size()]; 5170 libs.toArray(libsArray); 5171 return libsArray; 5172 } 5173 5174 return null; 5175 } 5176 } 5177 5178 @Override 5179 public @NonNull String getServicesSystemSharedLibraryPackageName() { 5180 // allow instant applications 5181 synchronized (mPackages) { 5182 return mServicesSystemSharedLibraryPackageName; 5183 } 5184 } 5185 5186 @Override 5187 public @NonNull String getSharedSystemSharedLibraryPackageName() { 5188 // allow instant applications 5189 synchronized (mPackages) { 5190 return mSharedSystemSharedLibraryPackageName; 5191 } 5192 } 5193 5194 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 5195 for (int i = userList.length - 1; i >= 0; --i) { 5196 final int userId = userList[i]; 5197 // don't add instant app to the list of updates 5198 if (pkgSetting.getInstantApp(userId)) { 5199 continue; 5200 } 5201 SparseArray<String> changedPackages = mChangedPackages.get(userId); 5202 if (changedPackages == null) { 5203 changedPackages = new SparseArray<>(); 5204 mChangedPackages.put(userId, changedPackages); 5205 } 5206 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 5207 if (sequenceNumbers == null) { 5208 sequenceNumbers = new HashMap<>(); 5209 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 5210 } 5211 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 5212 if (sequenceNumber != null) { 5213 changedPackages.remove(sequenceNumber); 5214 } 5215 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 5216 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 5217 } 5218 mChangedPackagesSequenceNumber++; 5219 } 5220 5221 @Override 5222 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5223 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5224 return null; 5225 } 5226 synchronized (mPackages) { 5227 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 5228 return null; 5229 } 5230 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 5231 if (changedPackages == null) { 5232 return null; 5233 } 5234 final List<String> packageNames = 5235 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 5236 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 5237 final String packageName = changedPackages.get(i); 5238 if (packageName != null) { 5239 packageNames.add(packageName); 5240 } 5241 } 5242 return packageNames.isEmpty() 5243 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 5244 } 5245 } 5246 5247 @Override 5248 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5249 // allow instant applications 5250 ArrayList<FeatureInfo> res; 5251 synchronized (mAvailableFeatures) { 5252 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5253 res.addAll(mAvailableFeatures.values()); 5254 } 5255 final FeatureInfo fi = new FeatureInfo(); 5256 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5257 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5258 res.add(fi); 5259 5260 return new ParceledListSlice<>(res); 5261 } 5262 5263 @Override 5264 public boolean hasSystemFeature(String name, int version) { 5265 // allow instant applications 5266 synchronized (mAvailableFeatures) { 5267 final FeatureInfo feat = mAvailableFeatures.get(name); 5268 if (feat == null) { 5269 return false; 5270 } else { 5271 return feat.version >= version; 5272 } 5273 } 5274 } 5275 5276 @Override 5277 public int checkPermission(String permName, String pkgName, int userId) { 5278 return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId); 5279 } 5280 5281 @Override 5282 public int checkUidPermission(String permName, int uid) { 5283 synchronized (mPackages) { 5284 final String[] packageNames = getPackagesForUid(uid); 5285 final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0) 5286 ? mPackages.get(packageNames[0]) 5287 : null; 5288 return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid()); 5289 } 5290 } 5291 5292 @Override 5293 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5294 if (UserHandle.getCallingUserId() != userId) { 5295 mContext.enforceCallingPermission( 5296 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5297 "isPermissionRevokedByPolicy for user " + userId); 5298 } 5299 5300 if (checkPermission(permission, packageName, userId) 5301 == PackageManager.PERMISSION_GRANTED) { 5302 return false; 5303 } 5304 5305 final int callingUid = Binder.getCallingUid(); 5306 if (getInstantAppPackageName(callingUid) != null) { 5307 if (!isCallerSameApp(packageName, callingUid)) { 5308 return false; 5309 } 5310 } else { 5311 if (isInstantApp(packageName, userId)) { 5312 return false; 5313 } 5314 } 5315 5316 final long identity = Binder.clearCallingIdentity(); 5317 try { 5318 final int flags = getPermissionFlags(permission, packageName, userId); 5319 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5320 } finally { 5321 Binder.restoreCallingIdentity(identity); 5322 } 5323 } 5324 5325 @Override 5326 public String getPermissionControllerPackageName() { 5327 synchronized (mPackages) { 5328 return mRequiredInstallerPackage; 5329 } 5330 } 5331 5332 private boolean addDynamicPermission(PermissionInfo info, final boolean async) { 5333 return mPermissionManager.addDynamicPermission( 5334 info, async, getCallingUid(), new PermissionCallback() { 5335 @Override 5336 public void onPermissionChanged() { 5337 if (!async) { 5338 mSettings.writeLPr(); 5339 } else { 5340 scheduleWriteSettingsLocked(); 5341 } 5342 } 5343 }); 5344 } 5345 5346 @Override 5347 public boolean addPermission(PermissionInfo info) { 5348 synchronized (mPackages) { 5349 return addDynamicPermission(info, false); 5350 } 5351 } 5352 5353 @Override 5354 public boolean addPermissionAsync(PermissionInfo info) { 5355 synchronized (mPackages) { 5356 return addDynamicPermission(info, true); 5357 } 5358 } 5359 5360 @Override 5361 public void removePermission(String permName) { 5362 mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback); 5363 } 5364 5365 @Override 5366 public void grantRuntimePermission(String packageName, String permName, final int userId) { 5367 mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/, 5368 getCallingUid(), userId, mPermissionCallback); 5369 } 5370 5371 @Override 5372 public void revokeRuntimePermission(String packageName, String permName, int userId) { 5373 mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/, 5374 getCallingUid(), userId, mPermissionCallback); 5375 } 5376 5377 @Override 5378 public void resetRuntimePermissions() { 5379 mContext.enforceCallingOrSelfPermission( 5380 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5381 "revokeRuntimePermission"); 5382 5383 int callingUid = Binder.getCallingUid(); 5384 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5385 mContext.enforceCallingOrSelfPermission( 5386 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5387 "resetRuntimePermissions"); 5388 } 5389 5390 synchronized (mPackages) { 5391 mPermissionManager.updateAllPermissions( 5392 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 5393 mPermissionCallback); 5394 for (int userId : UserManagerService.getInstance().getUserIds()) { 5395 final int packageCount = mPackages.size(); 5396 for (int i = 0; i < packageCount; i++) { 5397 PackageParser.Package pkg = mPackages.valueAt(i); 5398 if (!(pkg.mExtras instanceof PackageSetting)) { 5399 continue; 5400 } 5401 PackageSetting ps = (PackageSetting) pkg.mExtras; 5402 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5403 } 5404 } 5405 } 5406 } 5407 5408 @Override 5409 public int getPermissionFlags(String permName, String packageName, int userId) { 5410 return mPermissionManager.getPermissionFlags( 5411 permName, packageName, getCallingUid(), userId); 5412 } 5413 5414 @Override 5415 public void updatePermissionFlags(String permName, String packageName, int flagMask, 5416 int flagValues, int userId) { 5417 mPermissionManager.updatePermissionFlags( 5418 permName, packageName, flagMask, flagValues, getCallingUid(), userId, 5419 mPermissionCallback); 5420 } 5421 5422 /** 5423 * Update the permission flags for all packages and runtime permissions of a user in order 5424 * to allow device or profile owner to remove POLICY_FIXED. 5425 */ 5426 @Override 5427 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5428 synchronized (mPackages) { 5429 final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps( 5430 flagMask, flagValues, getCallingUid(), userId, mPackages.values(), 5431 mPermissionCallback); 5432 if (changed) { 5433 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5434 } 5435 } 5436 } 5437 5438 @Override 5439 public boolean shouldShowRequestPermissionRationale(String permissionName, 5440 String packageName, int userId) { 5441 if (UserHandle.getCallingUserId() != userId) { 5442 mContext.enforceCallingPermission( 5443 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5444 "canShowRequestPermissionRationale for user " + userId); 5445 } 5446 5447 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5448 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5449 return false; 5450 } 5451 5452 if (checkPermission(permissionName, packageName, userId) 5453 == PackageManager.PERMISSION_GRANTED) { 5454 return false; 5455 } 5456 5457 final int flags; 5458 5459 final long identity = Binder.clearCallingIdentity(); 5460 try { 5461 flags = getPermissionFlags(permissionName, 5462 packageName, userId); 5463 } finally { 5464 Binder.restoreCallingIdentity(identity); 5465 } 5466 5467 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5468 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5469 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5470 5471 if ((flags & fixedFlags) != 0) { 5472 return false; 5473 } 5474 5475 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5476 } 5477 5478 @Override 5479 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5480 mContext.enforceCallingOrSelfPermission( 5481 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5482 "addOnPermissionsChangeListener"); 5483 5484 synchronized (mPackages) { 5485 mOnPermissionChangeListeners.addListenerLocked(listener); 5486 } 5487 } 5488 5489 @Override 5490 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5491 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5492 throw new SecurityException("Instant applications don't have access to this method"); 5493 } 5494 synchronized (mPackages) { 5495 mOnPermissionChangeListeners.removeListenerLocked(listener); 5496 } 5497 } 5498 5499 @Override 5500 public boolean isProtectedBroadcast(String actionName) { 5501 // allow instant applications 5502 synchronized (mProtectedBroadcasts) { 5503 if (mProtectedBroadcasts.contains(actionName)) { 5504 return true; 5505 } else if (actionName != null) { 5506 // TODO: remove these terrible hacks 5507 if (actionName.startsWith("android.net.netmon.lingerExpired") 5508 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5509 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5510 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5511 return true; 5512 } 5513 } 5514 } 5515 return false; 5516 } 5517 5518 @Override 5519 public int checkSignatures(String pkg1, String pkg2) { 5520 synchronized (mPackages) { 5521 final PackageParser.Package p1 = mPackages.get(pkg1); 5522 final PackageParser.Package p2 = mPackages.get(pkg2); 5523 if (p1 == null || p1.mExtras == null 5524 || p2 == null || p2.mExtras == null) { 5525 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5526 } 5527 final int callingUid = Binder.getCallingUid(); 5528 final int callingUserId = UserHandle.getUserId(callingUid); 5529 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 5530 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 5531 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 5532 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 5533 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5534 } 5535 return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures); 5536 } 5537 } 5538 5539 @Override 5540 public int checkUidSignatures(int uid1, int uid2) { 5541 final int callingUid = Binder.getCallingUid(); 5542 final int callingUserId = UserHandle.getUserId(callingUid); 5543 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5544 // Map to base uids. 5545 uid1 = UserHandle.getAppId(uid1); 5546 uid2 = UserHandle.getAppId(uid2); 5547 // reader 5548 synchronized (mPackages) { 5549 Signature[] s1; 5550 Signature[] s2; 5551 Object obj = mSettings.getUserIdLPr(uid1); 5552 if (obj != null) { 5553 if (obj instanceof SharedUserSetting) { 5554 if (isCallerInstantApp) { 5555 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5556 } 5557 s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5558 } else if (obj instanceof PackageSetting) { 5559 final PackageSetting ps = (PackageSetting) obj; 5560 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5561 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5562 } 5563 s1 = ps.signatures.mSigningDetails.signatures; 5564 } else { 5565 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5566 } 5567 } else { 5568 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5569 } 5570 obj = mSettings.getUserIdLPr(uid2); 5571 if (obj != null) { 5572 if (obj instanceof SharedUserSetting) { 5573 if (isCallerInstantApp) { 5574 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5575 } 5576 s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5577 } else if (obj instanceof PackageSetting) { 5578 final PackageSetting ps = (PackageSetting) obj; 5579 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5580 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5581 } 5582 s2 = ps.signatures.mSigningDetails.signatures; 5583 } else { 5584 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5585 } 5586 } else { 5587 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5588 } 5589 return compareSignatures(s1, s2); 5590 } 5591 } 5592 5593 @Override 5594 public boolean hasSigningCertificate( 5595 String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) { 5596 5597 synchronized (mPackages) { 5598 final PackageParser.Package p = mPackages.get(packageName); 5599 if (p == null || p.mExtras == null) { 5600 return false; 5601 } 5602 final int callingUid = Binder.getCallingUid(); 5603 final int callingUserId = UserHandle.getUserId(callingUid); 5604 final PackageSetting ps = (PackageSetting) p.mExtras; 5605 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5606 return false; 5607 } 5608 switch (type) { 5609 case CERT_INPUT_RAW_X509: 5610 return p.mSigningDetails.hasCertificate(certificate); 5611 case CERT_INPUT_SHA256: 5612 return p.mSigningDetails.hasSha256Certificate(certificate); 5613 default: 5614 return false; 5615 } 5616 } 5617 } 5618 5619 @Override 5620 public boolean hasUidSigningCertificate( 5621 int uid, byte[] certificate, @PackageManager.CertificateInputType int type) { 5622 final int callingUid = Binder.getCallingUid(); 5623 final int callingUserId = UserHandle.getUserId(callingUid); 5624 // Map to base uids. 5625 uid = UserHandle.getAppId(uid); 5626 // reader 5627 synchronized (mPackages) { 5628 final PackageParser.SigningDetails signingDetails; 5629 final Object obj = mSettings.getUserIdLPr(uid); 5630 if (obj != null) { 5631 if (obj instanceof SharedUserSetting) { 5632 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5633 if (isCallerInstantApp) { 5634 return false; 5635 } 5636 signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails; 5637 } else if (obj instanceof PackageSetting) { 5638 final PackageSetting ps = (PackageSetting) obj; 5639 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5640 return false; 5641 } 5642 signingDetails = ps.signatures.mSigningDetails; 5643 } else { 5644 return false; 5645 } 5646 } else { 5647 return false; 5648 } 5649 switch (type) { 5650 case CERT_INPUT_RAW_X509: 5651 return signingDetails.hasCertificate(certificate); 5652 case CERT_INPUT_SHA256: 5653 return signingDetails.hasSha256Certificate(certificate); 5654 default: 5655 return false; 5656 } 5657 } 5658 } 5659 5660 /** 5661 * This method should typically only be used when granting or revoking 5662 * permissions, since the app may immediately restart after this call. 5663 * <p> 5664 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5665 * guard your work against the app being relaunched. 5666 */ 5667 private void killUid(int appId, int userId, String reason) { 5668 final long identity = Binder.clearCallingIdentity(); 5669 try { 5670 IActivityManager am = ActivityManager.getService(); 5671 if (am != null) { 5672 try { 5673 am.killUid(appId, userId, reason); 5674 } catch (RemoteException e) { 5675 /* ignore - same process */ 5676 } 5677 } 5678 } finally { 5679 Binder.restoreCallingIdentity(identity); 5680 } 5681 } 5682 5683 /** 5684 * If the database version for this type of package (internal storage or 5685 * external storage) is less than the version where package signatures 5686 * were updated, return true. 5687 */ 5688 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5689 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5690 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5691 } 5692 5693 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5694 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5695 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5696 } 5697 5698 @Override 5699 public List<String> getAllPackages() { 5700 final int callingUid = Binder.getCallingUid(); 5701 final int callingUserId = UserHandle.getUserId(callingUid); 5702 synchronized (mPackages) { 5703 if (canViewInstantApps(callingUid, callingUserId)) { 5704 return new ArrayList<String>(mPackages.keySet()); 5705 } 5706 final String instantAppPkgName = getInstantAppPackageName(callingUid); 5707 final List<String> result = new ArrayList<>(); 5708 if (instantAppPkgName != null) { 5709 // caller is an instant application; filter unexposed applications 5710 for (PackageParser.Package pkg : mPackages.values()) { 5711 if (!pkg.visibleToInstantApps) { 5712 continue; 5713 } 5714 result.add(pkg.packageName); 5715 } 5716 } else { 5717 // caller is a normal application; filter instant applications 5718 for (PackageParser.Package pkg : mPackages.values()) { 5719 final PackageSetting ps = 5720 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 5721 if (ps != null 5722 && ps.getInstantApp(callingUserId) 5723 && !mInstantAppRegistry.isInstantAccessGranted( 5724 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 5725 continue; 5726 } 5727 result.add(pkg.packageName); 5728 } 5729 } 5730 return result; 5731 } 5732 } 5733 5734 @Override 5735 public String[] getPackagesForUid(int uid) { 5736 final int callingUid = Binder.getCallingUid(); 5737 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5738 final int userId = UserHandle.getUserId(uid); 5739 uid = UserHandle.getAppId(uid); 5740 // reader 5741 synchronized (mPackages) { 5742 Object obj = mSettings.getUserIdLPr(uid); 5743 if (obj instanceof SharedUserSetting) { 5744 if (isCallerInstantApp) { 5745 return null; 5746 } 5747 final SharedUserSetting sus = (SharedUserSetting) obj; 5748 final int N = sus.packages.size(); 5749 String[] res = new String[N]; 5750 final Iterator<PackageSetting> it = sus.packages.iterator(); 5751 int i = 0; 5752 while (it.hasNext()) { 5753 PackageSetting ps = it.next(); 5754 if (ps.getInstalled(userId)) { 5755 res[i++] = ps.name; 5756 } else { 5757 res = ArrayUtils.removeElement(String.class, res, res[i]); 5758 } 5759 } 5760 return res; 5761 } else if (obj instanceof PackageSetting) { 5762 final PackageSetting ps = (PackageSetting) obj; 5763 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 5764 return new String[]{ps.name}; 5765 } 5766 } 5767 } 5768 return null; 5769 } 5770 5771 @Override 5772 public String getNameForUid(int uid) { 5773 final int callingUid = Binder.getCallingUid(); 5774 if (getInstantAppPackageName(callingUid) != null) { 5775 return null; 5776 } 5777 synchronized (mPackages) { 5778 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5779 if (obj instanceof SharedUserSetting) { 5780 final SharedUserSetting sus = (SharedUserSetting) obj; 5781 return sus.name + ":" + sus.userId; 5782 } else if (obj instanceof PackageSetting) { 5783 final PackageSetting ps = (PackageSetting) obj; 5784 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5785 return null; 5786 } 5787 return ps.name; 5788 } 5789 return null; 5790 } 5791 } 5792 5793 @Override 5794 public String[] getNamesForUids(int[] uids) { 5795 if (uids == null || uids.length == 0) { 5796 return null; 5797 } 5798 final int callingUid = Binder.getCallingUid(); 5799 if (getInstantAppPackageName(callingUid) != null) { 5800 return null; 5801 } 5802 final String[] names = new String[uids.length]; 5803 synchronized (mPackages) { 5804 for (int i = uids.length - 1; i >= 0; i--) { 5805 final int uid = uids[i]; 5806 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5807 if (obj instanceof SharedUserSetting) { 5808 final SharedUserSetting sus = (SharedUserSetting) obj; 5809 names[i] = "shared:" + sus.name; 5810 } else if (obj instanceof PackageSetting) { 5811 final PackageSetting ps = (PackageSetting) obj; 5812 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5813 names[i] = null; 5814 } else { 5815 names[i] = ps.name; 5816 } 5817 } else { 5818 names[i] = null; 5819 } 5820 } 5821 } 5822 return names; 5823 } 5824 5825 @Override 5826 public int getUidForSharedUser(String sharedUserName) { 5827 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5828 return -1; 5829 } 5830 if (sharedUserName == null) { 5831 return -1; 5832 } 5833 // reader 5834 synchronized (mPackages) { 5835 SharedUserSetting suid; 5836 try { 5837 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5838 if (suid != null) { 5839 return suid.userId; 5840 } 5841 } catch (PackageManagerException ignore) { 5842 // can't happen, but, still need to catch it 5843 } 5844 return -1; 5845 } 5846 } 5847 5848 @Override 5849 public int getFlagsForUid(int uid) { 5850 final int callingUid = Binder.getCallingUid(); 5851 if (getInstantAppPackageName(callingUid) != null) { 5852 return 0; 5853 } 5854 synchronized (mPackages) { 5855 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5856 if (obj instanceof SharedUserSetting) { 5857 final SharedUserSetting sus = (SharedUserSetting) obj; 5858 return sus.pkgFlags; 5859 } else if (obj instanceof PackageSetting) { 5860 final PackageSetting ps = (PackageSetting) obj; 5861 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5862 return 0; 5863 } 5864 return ps.pkgFlags; 5865 } 5866 } 5867 return 0; 5868 } 5869 5870 @Override 5871 public int getPrivateFlagsForUid(int uid) { 5872 final int callingUid = Binder.getCallingUid(); 5873 if (getInstantAppPackageName(callingUid) != null) { 5874 return 0; 5875 } 5876 synchronized (mPackages) { 5877 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5878 if (obj instanceof SharedUserSetting) { 5879 final SharedUserSetting sus = (SharedUserSetting) obj; 5880 return sus.pkgPrivateFlags; 5881 } else if (obj instanceof PackageSetting) { 5882 final PackageSetting ps = (PackageSetting) obj; 5883 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5884 return 0; 5885 } 5886 return ps.pkgPrivateFlags; 5887 } 5888 } 5889 return 0; 5890 } 5891 5892 @Override 5893 public boolean isUidPrivileged(int uid) { 5894 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5895 return false; 5896 } 5897 uid = UserHandle.getAppId(uid); 5898 // reader 5899 synchronized (mPackages) { 5900 Object obj = mSettings.getUserIdLPr(uid); 5901 if (obj instanceof SharedUserSetting) { 5902 final SharedUserSetting sus = (SharedUserSetting) obj; 5903 final Iterator<PackageSetting> it = sus.packages.iterator(); 5904 while (it.hasNext()) { 5905 if (it.next().isPrivileged()) { 5906 return true; 5907 } 5908 } 5909 } else if (obj instanceof PackageSetting) { 5910 final PackageSetting ps = (PackageSetting) obj; 5911 return ps.isPrivileged(); 5912 } 5913 } 5914 return false; 5915 } 5916 5917 @Override 5918 public String[] getAppOpPermissionPackages(String permName) { 5919 return mPermissionManager.getAppOpPermissionPackages(permName); 5920 } 5921 5922 @Override 5923 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5924 int flags, int userId) { 5925 return resolveIntentInternal( 5926 intent, resolvedType, flags, userId, false /*resolveForStart*/); 5927 } 5928 5929 /** 5930 * Normally instant apps can only be resolved when they're visible to the caller. 5931 * However, if {@code resolveForStart} is {@code true}, all instant apps are visible 5932 * since we need to allow the system to start any installed application. 5933 */ 5934 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5935 int flags, int userId, boolean resolveForStart) { 5936 try { 5937 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5938 5939 if (!sUserManager.exists(userId)) return null; 5940 final int callingUid = Binder.getCallingUid(); 5941 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 5942 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5943 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5944 5945 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5946 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5947 flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/); 5948 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5949 5950 final ResolveInfo bestChoice = 5951 chooseBestActivity(intent, resolvedType, flags, query, userId); 5952 return bestChoice; 5953 } finally { 5954 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5955 } 5956 } 5957 5958 @Override 5959 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5960 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5961 throw new SecurityException( 5962 "findPersistentPreferredActivity can only be run by the system"); 5963 } 5964 if (!sUserManager.exists(userId)) { 5965 return null; 5966 } 5967 final int callingUid = Binder.getCallingUid(); 5968 intent = updateIntentForResolve(intent); 5969 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5970 final int flags = updateFlagsForResolve( 5971 0, userId, intent, callingUid, false /*includeInstantApps*/); 5972 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5973 userId); 5974 synchronized (mPackages) { 5975 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5976 userId); 5977 } 5978 } 5979 5980 @Override 5981 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5982 IntentFilter filter, int match, ComponentName activity) { 5983 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5984 return; 5985 } 5986 final int userId = UserHandle.getCallingUserId(); 5987 if (DEBUG_PREFERRED) { 5988 Log.v(TAG, "setLastChosenActivity intent=" + intent 5989 + " resolvedType=" + resolvedType 5990 + " flags=" + flags 5991 + " filter=" + filter 5992 + " match=" + match 5993 + " activity=" + activity); 5994 filter.dump(new PrintStreamPrinter(System.out), " "); 5995 } 5996 intent.setComponent(null); 5997 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5998 userId); 5999 // Find any earlier preferred or last chosen entries and nuke them 6000 findPreferredActivity(intent, resolvedType, 6001 flags, query, 0, false, true, false, userId); 6002 // Add the new activity as the last chosen for this filter 6003 addPreferredActivityInternal(filter, match, null, activity, false, userId, 6004 "Setting last chosen"); 6005 } 6006 6007 @Override 6008 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 6009 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6010 return null; 6011 } 6012 final int userId = UserHandle.getCallingUserId(); 6013 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 6014 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6015 userId); 6016 return findPreferredActivity(intent, resolvedType, flags, query, 0, 6017 false, false, false, userId); 6018 } 6019 6020 /** 6021 * Returns whether or not instant apps have been disabled remotely. 6022 */ 6023 private boolean areWebInstantAppsDisabled() { 6024 return mWebInstantAppsDisabled; 6025 } 6026 6027 private boolean isInstantAppResolutionAllowed( 6028 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 6029 boolean skipPackageCheck) { 6030 if (mInstantAppResolverConnection == null) { 6031 return false; 6032 } 6033 if (mInstantAppInstallerActivity == null) { 6034 return false; 6035 } 6036 if (intent.getComponent() != null) { 6037 return false; 6038 } 6039 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 6040 return false; 6041 } 6042 if (!skipPackageCheck && intent.getPackage() != null) { 6043 return false; 6044 } 6045 if (!intent.isWebIntent()) { 6046 // for non web intents, we should not resolve externally if an app already exists to 6047 // handle it or if the caller didn't explicitly request it. 6048 if ((resolvedActivities != null && resolvedActivities.size() != 0) 6049 || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) { 6050 return false; 6051 } 6052 } else { 6053 if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) { 6054 return false; 6055 } else if (areWebInstantAppsDisabled()) { 6056 return false; 6057 } 6058 } 6059 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 6060 // Or if there's already an ephemeral app installed that handles the action 6061 synchronized (mPackages) { 6062 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 6063 for (int n = 0; n < count; n++) { 6064 final ResolveInfo info = resolvedActivities.get(n); 6065 final String packageName = info.activityInfo.packageName; 6066 final PackageSetting ps = mSettings.mPackages.get(packageName); 6067 if (ps != null) { 6068 // only check domain verification status if the app is not a browser 6069 if (!info.handleAllWebDataURI) { 6070 // Try to get the status from User settings first 6071 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6072 final int status = (int) (packedStatus >> 32); 6073 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 6074 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6075 if (DEBUG_INSTANT) { 6076 Slog.v(TAG, "DENY instant app;" 6077 + " pkg: " + packageName + ", status: " + status); 6078 } 6079 return false; 6080 } 6081 } 6082 if (ps.getInstantApp(userId)) { 6083 if (DEBUG_INSTANT) { 6084 Slog.v(TAG, "DENY instant app installed;" 6085 + " pkg: " + packageName); 6086 } 6087 return false; 6088 } 6089 } 6090 } 6091 } 6092 // We've exhausted all ways to deny ephemeral application; let the system look for them. 6093 return true; 6094 } 6095 6096 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 6097 Intent origIntent, String resolvedType, String callingPackage, 6098 Bundle verificationBundle, int userId) { 6099 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 6100 new InstantAppRequest(responseObj, origIntent, resolvedType, 6101 callingPackage, userId, verificationBundle, false /*resolveForStart*/)); 6102 mHandler.sendMessage(msg); 6103 } 6104 6105 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 6106 int flags, List<ResolveInfo> query, int userId) { 6107 if (query != null) { 6108 final int N = query.size(); 6109 if (N == 1) { 6110 return query.get(0); 6111 } else if (N > 1) { 6112 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 6113 // If there is more than one activity with the same priority, 6114 // then let the user decide between them. 6115 ResolveInfo r0 = query.get(0); 6116 ResolveInfo r1 = query.get(1); 6117 if (DEBUG_INTENT_MATCHING || debug) { 6118 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 6119 + r1.activityInfo.name + "=" + r1.priority); 6120 } 6121 // If the first activity has a higher priority, or a different 6122 // default, then it is always desirable to pick it. 6123 if (r0.priority != r1.priority 6124 || r0.preferredOrder != r1.preferredOrder 6125 || r0.isDefault != r1.isDefault) { 6126 return query.get(0); 6127 } 6128 // If we have saved a preference for a preferred activity for 6129 // this Intent, use that. 6130 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 6131 flags, query, r0.priority, true, false, debug, userId); 6132 if (ri != null) { 6133 return ri; 6134 } 6135 // If we have an ephemeral app, use it 6136 for (int i = 0; i < N; i++) { 6137 ri = query.get(i); 6138 if (ri.activityInfo.applicationInfo.isInstantApp()) { 6139 final String packageName = ri.activityInfo.packageName; 6140 final PackageSetting ps = mSettings.mPackages.get(packageName); 6141 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6142 final int status = (int)(packedStatus >> 32); 6143 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6144 return ri; 6145 } 6146 } 6147 } 6148 ri = new ResolveInfo(mResolveInfo); 6149 ri.activityInfo = new ActivityInfo(ri.activityInfo); 6150 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 6151 // If all of the options come from the same package, show the application's 6152 // label and icon instead of the generic resolver's. 6153 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 6154 // and then throw away the ResolveInfo itself, meaning that the caller loses 6155 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 6156 // a fallback for this case; we only set the target package's resources on 6157 // the ResolveInfo, not the ActivityInfo. 6158 final String intentPackage = intent.getPackage(); 6159 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 6160 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 6161 ri.resolvePackageName = intentPackage; 6162 if (userNeedsBadging(userId)) { 6163 ri.noResourceId = true; 6164 } else { 6165 ri.icon = appi.icon; 6166 } 6167 ri.iconResourceId = appi.icon; 6168 ri.labelRes = appi.labelRes; 6169 } 6170 ri.activityInfo.applicationInfo = new ApplicationInfo( 6171 ri.activityInfo.applicationInfo); 6172 if (userId != 0) { 6173 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6174 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6175 } 6176 // Make sure that the resolver is displayable in car mode 6177 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6178 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6179 return ri; 6180 } 6181 } 6182 return null; 6183 } 6184 6185 /** 6186 * Return true if the given list is not empty and all of its contents have 6187 * an activityInfo with the given package name. 6188 */ 6189 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6190 if (ArrayUtils.isEmpty(list)) { 6191 return false; 6192 } 6193 for (int i = 0, N = list.size(); i < N; i++) { 6194 final ResolveInfo ri = list.get(i); 6195 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6196 if (ai == null || !packageName.equals(ai.packageName)) { 6197 return false; 6198 } 6199 } 6200 return true; 6201 } 6202 6203 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6204 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6205 final int N = query.size(); 6206 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6207 .get(userId); 6208 // Get the list of persistent preferred activities that handle the intent 6209 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6210 List<PersistentPreferredActivity> pprefs = ppir != null 6211 ? ppir.queryIntent(intent, resolvedType, 6212 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6213 userId) 6214 : null; 6215 if (pprefs != null && pprefs.size() > 0) { 6216 final int M = pprefs.size(); 6217 for (int i=0; i<M; i++) { 6218 final PersistentPreferredActivity ppa = pprefs.get(i); 6219 if (DEBUG_PREFERRED || debug) { 6220 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6221 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6222 + "\n component=" + ppa.mComponent); 6223 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6224 } 6225 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6226 flags | MATCH_DISABLED_COMPONENTS, userId); 6227 if (DEBUG_PREFERRED || debug) { 6228 Slog.v(TAG, "Found persistent preferred activity:"); 6229 if (ai != null) { 6230 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6231 } else { 6232 Slog.v(TAG, " null"); 6233 } 6234 } 6235 if (ai == null) { 6236 // This previously registered persistent preferred activity 6237 // component is no longer known. Ignore it and do NOT remove it. 6238 continue; 6239 } 6240 for (int j=0; j<N; j++) { 6241 final ResolveInfo ri = query.get(j); 6242 if (!ri.activityInfo.applicationInfo.packageName 6243 .equals(ai.applicationInfo.packageName)) { 6244 continue; 6245 } 6246 if (!ri.activityInfo.name.equals(ai.name)) { 6247 continue; 6248 } 6249 // Found a persistent preference that can handle the intent. 6250 if (DEBUG_PREFERRED || debug) { 6251 Slog.v(TAG, "Returning persistent preferred activity: " + 6252 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6253 } 6254 return ri; 6255 } 6256 } 6257 } 6258 return null; 6259 } 6260 6261 // TODO: handle preferred activities missing while user has amnesia 6262 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6263 List<ResolveInfo> query, int priority, boolean always, 6264 boolean removeMatches, boolean debug, int userId) { 6265 if (!sUserManager.exists(userId)) return null; 6266 final int callingUid = Binder.getCallingUid(); 6267 flags = updateFlagsForResolve( 6268 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6269 intent = updateIntentForResolve(intent); 6270 // writer 6271 synchronized (mPackages) { 6272 // Try to find a matching persistent preferred activity. 6273 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6274 debug, userId); 6275 6276 // If a persistent preferred activity matched, use it. 6277 if (pri != null) { 6278 return pri; 6279 } 6280 6281 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6282 // Get the list of preferred activities that handle the intent 6283 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6284 List<PreferredActivity> prefs = pir != null 6285 ? pir.queryIntent(intent, resolvedType, 6286 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6287 userId) 6288 : null; 6289 if (prefs != null && prefs.size() > 0) { 6290 boolean changed = false; 6291 try { 6292 // First figure out how good the original match set is. 6293 // We will only allow preferred activities that came 6294 // from the same match quality. 6295 int match = 0; 6296 6297 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6298 6299 final int N = query.size(); 6300 for (int j=0; j<N; j++) { 6301 final ResolveInfo ri = query.get(j); 6302 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6303 + ": 0x" + Integer.toHexString(match)); 6304 if (ri.match > match) { 6305 match = ri.match; 6306 } 6307 } 6308 6309 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6310 + Integer.toHexString(match)); 6311 6312 match &= IntentFilter.MATCH_CATEGORY_MASK; 6313 final int M = prefs.size(); 6314 for (int i=0; i<M; i++) { 6315 final PreferredActivity pa = prefs.get(i); 6316 if (DEBUG_PREFERRED || debug) { 6317 Slog.v(TAG, "Checking PreferredActivity ds=" 6318 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6319 + "\n component=" + pa.mPref.mComponent); 6320 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6321 } 6322 if (pa.mPref.mMatch != match) { 6323 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6324 + Integer.toHexString(pa.mPref.mMatch)); 6325 continue; 6326 } 6327 // If it's not an "always" type preferred activity and that's what we're 6328 // looking for, skip it. 6329 if (always && !pa.mPref.mAlways) { 6330 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6331 continue; 6332 } 6333 final ActivityInfo ai = getActivityInfo( 6334 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6335 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6336 userId); 6337 if (DEBUG_PREFERRED || debug) { 6338 Slog.v(TAG, "Found preferred activity:"); 6339 if (ai != null) { 6340 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6341 } else { 6342 Slog.v(TAG, " null"); 6343 } 6344 } 6345 if (ai == null) { 6346 // This previously registered preferred activity 6347 // component is no longer known. Most likely an update 6348 // to the app was installed and in the new version this 6349 // component no longer exists. Clean it up by removing 6350 // it from the preferred activities list, and skip it. 6351 Slog.w(TAG, "Removing dangling preferred activity: " 6352 + pa.mPref.mComponent); 6353 pir.removeFilter(pa); 6354 changed = true; 6355 continue; 6356 } 6357 for (int j=0; j<N; j++) { 6358 final ResolveInfo ri = query.get(j); 6359 if (!ri.activityInfo.applicationInfo.packageName 6360 .equals(ai.applicationInfo.packageName)) { 6361 continue; 6362 } 6363 if (!ri.activityInfo.name.equals(ai.name)) { 6364 continue; 6365 } 6366 6367 if (removeMatches) { 6368 pir.removeFilter(pa); 6369 changed = true; 6370 if (DEBUG_PREFERRED) { 6371 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6372 } 6373 break; 6374 } 6375 6376 // Okay we found a previously set preferred or last chosen app. 6377 // If the result set is different from when this 6378 // was created, and is not a subset of the preferred set, we need to 6379 // clear it and re-ask the user their preference, if we're looking for 6380 // an "always" type entry. 6381 if (always && !pa.mPref.sameSet(query)) { 6382 if (pa.mPref.isSuperset(query)) { 6383 // some components of the set are no longer present in 6384 // the query, but the preferred activity can still be reused 6385 if (DEBUG_PREFERRED) { 6386 Slog.i(TAG, "Result set changed, but PreferredActivity is" 6387 + " still valid as only non-preferred components" 6388 + " were removed for " + intent + " type " 6389 + resolvedType); 6390 } 6391 // remove obsolete components and re-add the up-to-date filter 6392 PreferredActivity freshPa = new PreferredActivity(pa, 6393 pa.mPref.mMatch, 6394 pa.mPref.discardObsoleteComponents(query), 6395 pa.mPref.mComponent, 6396 pa.mPref.mAlways); 6397 pir.removeFilter(pa); 6398 pir.addFilter(freshPa); 6399 changed = true; 6400 } else { 6401 Slog.i(TAG, 6402 "Result set changed, dropping preferred activity for " 6403 + intent + " type " + resolvedType); 6404 if (DEBUG_PREFERRED) { 6405 Slog.v(TAG, "Removing preferred activity since set changed " 6406 + pa.mPref.mComponent); 6407 } 6408 pir.removeFilter(pa); 6409 // Re-add the filter as a "last chosen" entry (!always) 6410 PreferredActivity lastChosen = new PreferredActivity( 6411 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6412 pir.addFilter(lastChosen); 6413 changed = true; 6414 return null; 6415 } 6416 } 6417 6418 // Yay! Either the set matched or we're looking for the last chosen 6419 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6420 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6421 return ri; 6422 } 6423 } 6424 } finally { 6425 if (changed) { 6426 if (DEBUG_PREFERRED) { 6427 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6428 } 6429 scheduleWritePackageRestrictionsLocked(userId); 6430 } 6431 } 6432 } 6433 } 6434 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6435 return null; 6436 } 6437 6438 /* 6439 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6440 */ 6441 @Override 6442 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6443 int targetUserId) { 6444 mContext.enforceCallingOrSelfPermission( 6445 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6446 List<CrossProfileIntentFilter> matches = 6447 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6448 if (matches != null) { 6449 int size = matches.size(); 6450 for (int i = 0; i < size; i++) { 6451 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6452 } 6453 } 6454 if (intent.hasWebURI()) { 6455 // cross-profile app linking works only towards the parent. 6456 final int callingUid = Binder.getCallingUid(); 6457 final UserInfo parent = getProfileParent(sourceUserId); 6458 synchronized(mPackages) { 6459 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6460 false /*includeInstantApps*/); 6461 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6462 intent, resolvedType, flags, sourceUserId, parent.id); 6463 return xpDomainInfo != null; 6464 } 6465 } 6466 return false; 6467 } 6468 6469 private UserInfo getProfileParent(int userId) { 6470 final long identity = Binder.clearCallingIdentity(); 6471 try { 6472 return sUserManager.getProfileParent(userId); 6473 } finally { 6474 Binder.restoreCallingIdentity(identity); 6475 } 6476 } 6477 6478 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6479 String resolvedType, int userId) { 6480 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6481 if (resolver != null) { 6482 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6483 } 6484 return null; 6485 } 6486 6487 @Override 6488 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6489 String resolvedType, int flags, int userId) { 6490 try { 6491 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6492 6493 return new ParceledListSlice<>( 6494 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6495 } finally { 6496 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6497 } 6498 } 6499 6500 /** 6501 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6502 * instant, returns {@code null}. 6503 */ 6504 private String getInstantAppPackageName(int callingUid) { 6505 synchronized (mPackages) { 6506 // If the caller is an isolated app use the owner's uid for the lookup. 6507 if (Process.isIsolated(callingUid)) { 6508 callingUid = mIsolatedOwners.get(callingUid); 6509 } 6510 final int appId = UserHandle.getAppId(callingUid); 6511 final Object obj = mSettings.getUserIdLPr(appId); 6512 if (obj instanceof PackageSetting) { 6513 final PackageSetting ps = (PackageSetting) obj; 6514 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6515 return isInstantApp ? ps.pkg.packageName : null; 6516 } 6517 } 6518 return null; 6519 } 6520 6521 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6522 String resolvedType, int flags, int userId) { 6523 return queryIntentActivitiesInternal( 6524 intent, resolvedType, flags, Binder.getCallingUid(), userId, 6525 false /*resolveForStart*/, true /*allowDynamicSplits*/); 6526 } 6527 6528 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6529 String resolvedType, int flags, int filterCallingUid, int userId, 6530 boolean resolveForStart, boolean allowDynamicSplits) { 6531 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6532 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 6533 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 6534 false /* requireFullPermission */, false /* checkShell */, 6535 "query intent activities"); 6536 final String pkgName = intent.getPackage(); 6537 ComponentName comp = intent.getComponent(); 6538 if (comp == null) { 6539 if (intent.getSelector() != null) { 6540 intent = intent.getSelector(); 6541 comp = intent.getComponent(); 6542 } 6543 } 6544 6545 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 6546 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6547 if (comp != null) { 6548 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6549 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6550 if (ai != null) { 6551 // When specifying an explicit component, we prevent the activity from being 6552 // used when either 1) the calling package is normal and the activity is within 6553 // an ephemeral application or 2) the calling package is ephemeral and the 6554 // activity is not visible to ephemeral applications. 6555 final boolean matchInstantApp = 6556 (flags & PackageManager.MATCH_INSTANT) != 0; 6557 final boolean matchVisibleToInstantAppOnly = 6558 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6559 final boolean matchExplicitlyVisibleOnly = 6560 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6561 final boolean isCallerInstantApp = 6562 instantAppPkgName != null; 6563 final boolean isTargetSameInstantApp = 6564 comp.getPackageName().equals(instantAppPkgName); 6565 final boolean isTargetInstantApp = 6566 (ai.applicationInfo.privateFlags 6567 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6568 final boolean isTargetVisibleToInstantApp = 6569 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6570 final boolean isTargetExplicitlyVisibleToInstantApp = 6571 isTargetVisibleToInstantApp 6572 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6573 final boolean isTargetHiddenFromInstantApp = 6574 !isTargetVisibleToInstantApp 6575 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6576 final boolean blockResolution = 6577 !isTargetSameInstantApp 6578 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6579 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6580 && isTargetHiddenFromInstantApp)); 6581 if (!blockResolution) { 6582 final ResolveInfo ri = new ResolveInfo(); 6583 ri.activityInfo = ai; 6584 list.add(ri); 6585 } 6586 } 6587 return applyPostResolutionFilter( 6588 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent); 6589 } 6590 6591 // reader 6592 boolean sortResult = false; 6593 boolean addInstant = false; 6594 List<ResolveInfo> result; 6595 synchronized (mPackages) { 6596 if (pkgName == null) { 6597 List<CrossProfileIntentFilter> matchingFilters = 6598 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6599 // Check for results that need to skip the current profile. 6600 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6601 resolvedType, flags, userId); 6602 if (xpResolveInfo != null) { 6603 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6604 xpResult.add(xpResolveInfo); 6605 return applyPostResolutionFilter( 6606 filterIfNotSystemUser(xpResult, userId), instantAppPkgName, 6607 allowDynamicSplits, filterCallingUid, userId, intent); 6608 } 6609 6610 // Check for results in the current profile. 6611 result = filterIfNotSystemUser(mActivities.queryIntent( 6612 intent, resolvedType, flags, userId), userId); 6613 addInstant = isInstantAppResolutionAllowed(intent, result, userId, 6614 false /*skipPackageCheck*/); 6615 // Check for cross profile results. 6616 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6617 xpResolveInfo = queryCrossProfileIntents( 6618 matchingFilters, intent, resolvedType, flags, userId, 6619 hasNonNegativePriorityResult); 6620 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6621 boolean isVisibleToUser = filterIfNotSystemUser( 6622 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6623 if (isVisibleToUser) { 6624 result.add(xpResolveInfo); 6625 sortResult = true; 6626 } 6627 } 6628 if (intent.hasWebURI()) { 6629 CrossProfileDomainInfo xpDomainInfo = null; 6630 final UserInfo parent = getProfileParent(userId); 6631 if (parent != null) { 6632 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6633 flags, userId, parent.id); 6634 } 6635 if (xpDomainInfo != null) { 6636 if (xpResolveInfo != null) { 6637 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6638 // in the result. 6639 result.remove(xpResolveInfo); 6640 } 6641 if (result.size() == 0 && !addInstant) { 6642 // No result in current profile, but found candidate in parent user. 6643 // And we are not going to add emphemeral app, so we can return the 6644 // result straight away. 6645 result.add(xpDomainInfo.resolveInfo); 6646 return applyPostResolutionFilter(result, instantAppPkgName, 6647 allowDynamicSplits, filterCallingUid, userId, intent); 6648 } 6649 } else if (result.size() <= 1 && !addInstant) { 6650 // No result in parent user and <= 1 result in current profile, and we 6651 // are not going to add emphemeral app, so we can return the result without 6652 // further processing. 6653 return applyPostResolutionFilter(result, instantAppPkgName, 6654 allowDynamicSplits, filterCallingUid, userId, intent); 6655 } 6656 // We have more than one candidate (combining results from current and parent 6657 // profile), so we need filtering and sorting. 6658 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6659 intent, flags, result, xpDomainInfo, userId); 6660 sortResult = true; 6661 } 6662 } else { 6663 final PackageParser.Package pkg = mPackages.get(pkgName); 6664 result = null; 6665 if (pkg != null) { 6666 result = filterIfNotSystemUser( 6667 mActivities.queryIntentForPackage( 6668 intent, resolvedType, flags, pkg.activities, userId), 6669 userId); 6670 } 6671 if (result == null || result.size() == 0) { 6672 // the caller wants to resolve for a particular package; however, there 6673 // were no installed results, so, try to find an ephemeral result 6674 addInstant = isInstantAppResolutionAllowed( 6675 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6676 if (result == null) { 6677 result = new ArrayList<>(); 6678 } 6679 } 6680 } 6681 } 6682 if (addInstant) { 6683 result = maybeAddInstantAppInstaller( 6684 result, intent, resolvedType, flags, userId, resolveForStart); 6685 } 6686 if (sortResult) { 6687 Collections.sort(result, mResolvePrioritySorter); 6688 } 6689 return applyPostResolutionFilter( 6690 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent); 6691 } 6692 6693 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 6694 String resolvedType, int flags, int userId, boolean resolveForStart) { 6695 // first, check to see if we've got an instant app already installed 6696 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 6697 ResolveInfo localInstantApp = null; 6698 boolean blockResolution = false; 6699 if (!alreadyResolvedLocally) { 6700 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 6701 flags 6702 | PackageManager.GET_RESOLVED_FILTER 6703 | PackageManager.MATCH_INSTANT 6704 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 6705 userId); 6706 for (int i = instantApps.size() - 1; i >= 0; --i) { 6707 final ResolveInfo info = instantApps.get(i); 6708 final String packageName = info.activityInfo.packageName; 6709 final PackageSetting ps = mSettings.mPackages.get(packageName); 6710 if (ps.getInstantApp(userId)) { 6711 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6712 final int status = (int)(packedStatus >> 32); 6713 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6714 // there's a local instant application installed, but, the user has 6715 // chosen to never use it; skip resolution and don't acknowledge 6716 // an instant application is even available 6717 if (DEBUG_INSTANT) { 6718 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 6719 } 6720 blockResolution = true; 6721 break; 6722 } else { 6723 // we have a locally installed instant application; skip resolution 6724 // but acknowledge there's an instant application available 6725 if (DEBUG_INSTANT) { 6726 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 6727 } 6728 localInstantApp = info; 6729 break; 6730 } 6731 } 6732 } 6733 } 6734 // no app installed, let's see if one's available 6735 AuxiliaryResolveInfo auxiliaryResponse = null; 6736 if (!blockResolution) { 6737 if (localInstantApp == null) { 6738 // we don't have an instant app locally, resolve externally 6739 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6740 final InstantAppRequest requestObject = new InstantAppRequest( 6741 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6742 null /*callingPackage*/, userId, null /*verificationBundle*/, 6743 resolveForStart); 6744 auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne( 6745 mInstantAppResolverConnection, requestObject); 6746 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6747 } else { 6748 // we have an instant application locally, but, we can't admit that since 6749 // callers shouldn't be able to determine prior browsing. create a dummy 6750 // auxiliary response so the downstream code behaves as if there's an 6751 // instant application available externally. when it comes time to start 6752 // the instant application, we'll do the right thing. 6753 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 6754 auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */, 6755 ai.packageName, ai.versionCode, null /* splitName */); 6756 } 6757 } 6758 if (intent.isWebIntent() && auxiliaryResponse == null) { 6759 return result; 6760 } 6761 final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6762 if (ps == null 6763 || ps.getUserState().get(userId) == null 6764 || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) { 6765 return result; 6766 } 6767 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6768 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6769 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6770 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6771 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6772 // add a non-generic filter 6773 ephemeralInstaller.filter = new IntentFilter(); 6774 if (intent.getAction() != null) { 6775 ephemeralInstaller.filter.addAction(intent.getAction()); 6776 } 6777 if (intent.getData() != null && intent.getData().getPath() != null) { 6778 ephemeralInstaller.filter.addDataPath( 6779 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6780 } 6781 ephemeralInstaller.isInstantAppAvailable = true; 6782 // make sure this resolver is the default 6783 ephemeralInstaller.isDefault = true; 6784 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6785 if (DEBUG_INSTANT) { 6786 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6787 } 6788 6789 result.add(ephemeralInstaller); 6790 return result; 6791 } 6792 6793 private static class CrossProfileDomainInfo { 6794 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6795 ResolveInfo resolveInfo; 6796 /* Best domain verification status of the activities found in the other profile */ 6797 int bestDomainVerificationStatus; 6798 } 6799 6800 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6801 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6802 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6803 sourceUserId)) { 6804 return null; 6805 } 6806 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6807 resolvedType, flags, parentUserId); 6808 6809 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6810 return null; 6811 } 6812 CrossProfileDomainInfo result = null; 6813 int size = resultTargetUser.size(); 6814 for (int i = 0; i < size; i++) { 6815 ResolveInfo riTargetUser = resultTargetUser.get(i); 6816 // Intent filter verification is only for filters that specify a host. So don't return 6817 // those that handle all web uris. 6818 if (riTargetUser.handleAllWebDataURI) { 6819 continue; 6820 } 6821 String packageName = riTargetUser.activityInfo.packageName; 6822 PackageSetting ps = mSettings.mPackages.get(packageName); 6823 if (ps == null) { 6824 continue; 6825 } 6826 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6827 int status = (int)(verificationState >> 32); 6828 if (result == null) { 6829 result = new CrossProfileDomainInfo(); 6830 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6831 sourceUserId, parentUserId); 6832 result.bestDomainVerificationStatus = status; 6833 } else { 6834 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6835 result.bestDomainVerificationStatus); 6836 } 6837 } 6838 // Don't consider matches with status NEVER across profiles. 6839 if (result != null && result.bestDomainVerificationStatus 6840 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6841 return null; 6842 } 6843 return result; 6844 } 6845 6846 /** 6847 * Verification statuses are ordered from the worse to the best, except for 6848 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6849 */ 6850 private int bestDomainVerificationStatus(int status1, int status2) { 6851 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6852 return status2; 6853 } 6854 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6855 return status1; 6856 } 6857 return (int) MathUtils.max(status1, status2); 6858 } 6859 6860 private boolean isUserEnabled(int userId) { 6861 long callingId = Binder.clearCallingIdentity(); 6862 try { 6863 UserInfo userInfo = sUserManager.getUserInfo(userId); 6864 return userInfo != null && userInfo.isEnabled(); 6865 } finally { 6866 Binder.restoreCallingIdentity(callingId); 6867 } 6868 } 6869 6870 /** 6871 * Filter out activities with systemUserOnly flag set, when current user is not System. 6872 * 6873 * @return filtered list 6874 */ 6875 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6876 if (userId == UserHandle.USER_SYSTEM) { 6877 return resolveInfos; 6878 } 6879 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6880 ResolveInfo info = resolveInfos.get(i); 6881 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6882 resolveInfos.remove(i); 6883 } 6884 } 6885 return resolveInfos; 6886 } 6887 6888 /** 6889 * Filters out ephemeral activities. 6890 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6891 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6892 * 6893 * @param resolveInfos The pre-filtered list of resolved activities 6894 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6895 * is performed. 6896 * @param intent 6897 * @return A filtered list of resolved activities. 6898 */ 6899 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6900 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId, 6901 Intent intent) { 6902 final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled(); 6903 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6904 final ResolveInfo info = resolveInfos.get(i); 6905 // remove locally resolved instant app web results when disabled 6906 if (info.isInstantAppAvailable && blockInstant) { 6907 resolveInfos.remove(i); 6908 continue; 6909 } 6910 // allow activities that are defined in the provided package 6911 if (allowDynamicSplits 6912 && info.activityInfo != null 6913 && info.activityInfo.splitName != null 6914 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6915 info.activityInfo.splitName)) { 6916 if (mInstantAppInstallerActivity == null) { 6917 if (DEBUG_INSTALL) { 6918 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 6919 } 6920 resolveInfos.remove(i); 6921 continue; 6922 } 6923 if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) { 6924 resolveInfos.remove(i); 6925 continue; 6926 } 6927 // requested activity is defined in a split that hasn't been installed yet. 6928 // add the installer to the resolve list 6929 if (DEBUG_INSTALL) { 6930 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 6931 } 6932 final ResolveInfo installerInfo = new ResolveInfo( 6933 mInstantAppInstallerInfo); 6934 final ComponentName installFailureActivity = findInstallFailureActivity( 6935 info.activityInfo.packageName, filterCallingUid, userId); 6936 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6937 installFailureActivity, 6938 info.activityInfo.packageName, 6939 info.activityInfo.applicationInfo.versionCode, 6940 info.activityInfo.splitName); 6941 // add a non-generic filter 6942 installerInfo.filter = new IntentFilter(); 6943 6944 // This resolve info may appear in the chooser UI, so let us make it 6945 // look as the one it replaces as far as the user is concerned which 6946 // requires loading the correct label and icon for the resolve info. 6947 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6948 installerInfo.labelRes = info.resolveLabelResId(); 6949 installerInfo.icon = info.resolveIconResId(); 6950 installerInfo.isInstantAppAvailable = true; 6951 resolveInfos.set(i, installerInfo); 6952 continue; 6953 } 6954 // caller is a full app, don't need to apply any other filtering 6955 if (ephemeralPkgName == null) { 6956 continue; 6957 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 6958 // caller is same app; don't need to apply any other filtering 6959 continue; 6960 } 6961 // allow activities that have been explicitly exposed to ephemeral apps 6962 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6963 if (!isEphemeralApp 6964 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 6965 continue; 6966 } 6967 resolveInfos.remove(i); 6968 } 6969 return resolveInfos; 6970 } 6971 6972 /** 6973 * Returns the activity component that can handle install failures. 6974 * <p>By default, the instant application installer handles failures. However, an 6975 * application may want to handle failures on its own. Applications do this by 6976 * creating an activity with an intent filter that handles the action 6977 * {@link Intent#ACTION_INSTALL_FAILURE}. 6978 */ 6979 private @Nullable ComponentName findInstallFailureActivity( 6980 String packageName, int filterCallingUid, int userId) { 6981 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 6982 failureActivityIntent.setPackage(packageName); 6983 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 6984 final List<ResolveInfo> result = queryIntentActivitiesInternal( 6985 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId, 6986 false /*resolveForStart*/, false /*allowDynamicSplits*/); 6987 final int NR = result.size(); 6988 if (NR > 0) { 6989 for (int i = 0; i < NR; i++) { 6990 final ResolveInfo info = result.get(i); 6991 if (info.activityInfo.splitName != null) { 6992 continue; 6993 } 6994 return new ComponentName(packageName, info.activityInfo.name); 6995 } 6996 } 6997 return null; 6998 } 6999 7000 /** 7001 * @param resolveInfos list of resolve infos in descending priority order 7002 * @return if the list contains a resolve info with non-negative priority 7003 */ 7004 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 7005 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 7006 } 7007 7008 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 7009 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 7010 int userId) { 7011 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 7012 7013 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7014 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 7015 candidates.size()); 7016 } 7017 7018 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 7019 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 7020 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 7021 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 7022 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 7023 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 7024 7025 synchronized (mPackages) { 7026 final int count = candidates.size(); 7027 // First, try to use linked apps. Partition the candidates into four lists: 7028 // one for the final results, one for the "do not use ever", one for "undefined status" 7029 // and finally one for "browser app type". 7030 for (int n=0; n<count; n++) { 7031 ResolveInfo info = candidates.get(n); 7032 String packageName = info.activityInfo.packageName; 7033 PackageSetting ps = mSettings.mPackages.get(packageName); 7034 if (ps != null) { 7035 // Add to the special match all list (Browser use case) 7036 if (info.handleAllWebDataURI) { 7037 matchAllList.add(info); 7038 continue; 7039 } 7040 // Try to get the status from User settings first 7041 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 7042 int status = (int)(packedStatus >> 32); 7043 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 7044 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 7045 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7046 Slog.i(TAG, " + always: " + info.activityInfo.packageName 7047 + " : linkgen=" + linkGeneration); 7048 } 7049 // Use link-enabled generation as preferredOrder, i.e. 7050 // prefer newly-enabled over earlier-enabled. 7051 info.preferredOrder = linkGeneration; 7052 alwaysList.add(info); 7053 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7054 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7055 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 7056 } 7057 neverList.add(info); 7058 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 7059 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7060 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 7061 } 7062 alwaysAskList.add(info); 7063 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 7064 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 7065 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7066 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 7067 } 7068 undefinedList.add(info); 7069 } 7070 } 7071 } 7072 7073 // We'll want to include browser possibilities in a few cases 7074 boolean includeBrowser = false; 7075 7076 // First try to add the "always" resolution(s) for the current user, if any 7077 if (alwaysList.size() > 0) { 7078 result.addAll(alwaysList); 7079 } else { 7080 // Add all undefined apps as we want them to appear in the disambiguation dialog. 7081 result.addAll(undefinedList); 7082 // Maybe add one for the other profile. 7083 if (xpDomainInfo != null && ( 7084 xpDomainInfo.bestDomainVerificationStatus 7085 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 7086 result.add(xpDomainInfo.resolveInfo); 7087 } 7088 includeBrowser = true; 7089 } 7090 7091 // The presence of any 'always ask' alternatives means we'll also offer browsers. 7092 // If there were 'always' entries their preferred order has been set, so we also 7093 // back that off to make the alternatives equivalent 7094 if (alwaysAskList.size() > 0) { 7095 for (ResolveInfo i : result) { 7096 i.preferredOrder = 0; 7097 } 7098 result.addAll(alwaysAskList); 7099 includeBrowser = true; 7100 } 7101 7102 if (includeBrowser) { 7103 // Also add browsers (all of them or only the default one) 7104 if (DEBUG_DOMAIN_VERIFICATION) { 7105 Slog.v(TAG, " ...including browsers in candidate set"); 7106 } 7107 if ((matchFlags & MATCH_ALL) != 0) { 7108 result.addAll(matchAllList); 7109 } else { 7110 // Browser/generic handling case. If there's a default browser, go straight 7111 // to that (but only if there is no other higher-priority match). 7112 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 7113 int maxMatchPrio = 0; 7114 ResolveInfo defaultBrowserMatch = null; 7115 final int numCandidates = matchAllList.size(); 7116 for (int n = 0; n < numCandidates; n++) { 7117 ResolveInfo info = matchAllList.get(n); 7118 // track the highest overall match priority... 7119 if (info.priority > maxMatchPrio) { 7120 maxMatchPrio = info.priority; 7121 } 7122 // ...and the highest-priority default browser match 7123 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 7124 if (defaultBrowserMatch == null 7125 || (defaultBrowserMatch.priority < info.priority)) { 7126 if (debug) { 7127 Slog.v(TAG, "Considering default browser match " + info); 7128 } 7129 defaultBrowserMatch = info; 7130 } 7131 } 7132 } 7133 if (defaultBrowserMatch != null 7134 && defaultBrowserMatch.priority >= maxMatchPrio 7135 && !TextUtils.isEmpty(defaultBrowserPackageName)) 7136 { 7137 if (debug) { 7138 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 7139 } 7140 result.add(defaultBrowserMatch); 7141 } else { 7142 result.addAll(matchAllList); 7143 } 7144 } 7145 7146 // If there is nothing selected, add all candidates and remove the ones that the user 7147 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 7148 if (result.size() == 0) { 7149 result.addAll(candidates); 7150 result.removeAll(neverList); 7151 } 7152 } 7153 } 7154 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7155 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 7156 result.size()); 7157 for (ResolveInfo info : result) { 7158 Slog.v(TAG, " + " + info.activityInfo); 7159 } 7160 } 7161 return result; 7162 } 7163 7164 // Returns a packed value as a long: 7165 // 7166 // high 'int'-sized word: link status: undefined/ask/never/always. 7167 // low 'int'-sized word: relative priority among 'always' results. 7168 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 7169 long result = ps.getDomainVerificationStatusForUser(userId); 7170 // if none available, get the master status 7171 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 7172 if (ps.getIntentFilterVerificationInfo() != null) { 7173 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 7174 } 7175 } 7176 return result; 7177 } 7178 7179 private ResolveInfo querySkipCurrentProfileIntents( 7180 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7181 int flags, int sourceUserId) { 7182 if (matchingFilters != null) { 7183 int size = matchingFilters.size(); 7184 for (int i = 0; i < size; i ++) { 7185 CrossProfileIntentFilter filter = matchingFilters.get(i); 7186 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 7187 // Checking if there are activities in the target user that can handle the 7188 // intent. 7189 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7190 resolvedType, flags, sourceUserId); 7191 if (resolveInfo != null) { 7192 return resolveInfo; 7193 } 7194 } 7195 } 7196 } 7197 return null; 7198 } 7199 7200 // Return matching ResolveInfo in target user if any. 7201 private ResolveInfo queryCrossProfileIntents( 7202 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7203 int flags, int sourceUserId, boolean matchInCurrentProfile) { 7204 if (matchingFilters != null) { 7205 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 7206 // match the same intent. For performance reasons, it is better not to 7207 // run queryIntent twice for the same userId 7208 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 7209 int size = matchingFilters.size(); 7210 for (int i = 0; i < size; i++) { 7211 CrossProfileIntentFilter filter = matchingFilters.get(i); 7212 int targetUserId = filter.getTargetUserId(); 7213 boolean skipCurrentProfile = 7214 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 7215 boolean skipCurrentProfileIfNoMatchFound = 7216 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 7217 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 7218 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 7219 // Checking if there are activities in the target user that can handle the 7220 // intent. 7221 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7222 resolvedType, flags, sourceUserId); 7223 if (resolveInfo != null) return resolveInfo; 7224 alreadyTriedUserIds.put(targetUserId, true); 7225 } 7226 } 7227 } 7228 return null; 7229 } 7230 7231 /** 7232 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 7233 * will forward the intent to the filter's target user. 7234 * Otherwise, returns null. 7235 */ 7236 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 7237 String resolvedType, int flags, int sourceUserId) { 7238 int targetUserId = filter.getTargetUserId(); 7239 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7240 resolvedType, flags, targetUserId); 7241 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7242 // If all the matches in the target profile are suspended, return null. 7243 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7244 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7245 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7246 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7247 targetUserId); 7248 } 7249 } 7250 } 7251 return null; 7252 } 7253 7254 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7255 int sourceUserId, int targetUserId) { 7256 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7257 long ident = Binder.clearCallingIdentity(); 7258 boolean targetIsProfile; 7259 try { 7260 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7261 } finally { 7262 Binder.restoreCallingIdentity(ident); 7263 } 7264 String className; 7265 if (targetIsProfile) { 7266 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7267 } else { 7268 className = FORWARD_INTENT_TO_PARENT; 7269 } 7270 ComponentName forwardingActivityComponentName = new ComponentName( 7271 mAndroidApplication.packageName, className); 7272 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7273 sourceUserId); 7274 if (!targetIsProfile) { 7275 forwardingActivityInfo.showUserIcon = targetUserId; 7276 forwardingResolveInfo.noResourceId = true; 7277 } 7278 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7279 forwardingResolveInfo.priority = 0; 7280 forwardingResolveInfo.preferredOrder = 0; 7281 forwardingResolveInfo.match = 0; 7282 forwardingResolveInfo.isDefault = true; 7283 forwardingResolveInfo.filter = filter; 7284 forwardingResolveInfo.targetUserId = targetUserId; 7285 return forwardingResolveInfo; 7286 } 7287 7288 @Override 7289 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7290 Intent[] specifics, String[] specificTypes, Intent intent, 7291 String resolvedType, int flags, int userId) { 7292 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7293 specificTypes, intent, resolvedType, flags, userId)); 7294 } 7295 7296 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7297 Intent[] specifics, String[] specificTypes, Intent intent, 7298 String resolvedType, int flags, int userId) { 7299 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7300 final int callingUid = Binder.getCallingUid(); 7301 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7302 false /*includeInstantApps*/); 7303 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7304 false /*requireFullPermission*/, false /*checkShell*/, 7305 "query intent activity options"); 7306 final String resultsAction = intent.getAction(); 7307 7308 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7309 | PackageManager.GET_RESOLVED_FILTER, userId); 7310 7311 if (DEBUG_INTENT_MATCHING) { 7312 Log.v(TAG, "Query " + intent + ": " + results); 7313 } 7314 7315 int specificsPos = 0; 7316 int N; 7317 7318 // todo: note that the algorithm used here is O(N^2). This 7319 // isn't a problem in our current environment, but if we start running 7320 // into situations where we have more than 5 or 10 matches then this 7321 // should probably be changed to something smarter... 7322 7323 // First we go through and resolve each of the specific items 7324 // that were supplied, taking care of removing any corresponding 7325 // duplicate items in the generic resolve list. 7326 if (specifics != null) { 7327 for (int i=0; i<specifics.length; i++) { 7328 final Intent sintent = specifics[i]; 7329 if (sintent == null) { 7330 continue; 7331 } 7332 7333 if (DEBUG_INTENT_MATCHING) { 7334 Log.v(TAG, "Specific #" + i + ": " + sintent); 7335 } 7336 7337 String action = sintent.getAction(); 7338 if (resultsAction != null && resultsAction.equals(action)) { 7339 // If this action was explicitly requested, then don't 7340 // remove things that have it. 7341 action = null; 7342 } 7343 7344 ResolveInfo ri = null; 7345 ActivityInfo ai = null; 7346 7347 ComponentName comp = sintent.getComponent(); 7348 if (comp == null) { 7349 ri = resolveIntent( 7350 sintent, 7351 specificTypes != null ? specificTypes[i] : null, 7352 flags, userId); 7353 if (ri == null) { 7354 continue; 7355 } 7356 if (ri == mResolveInfo) { 7357 // ACK! Must do something better with this. 7358 } 7359 ai = ri.activityInfo; 7360 comp = new ComponentName(ai.applicationInfo.packageName, 7361 ai.name); 7362 } else { 7363 ai = getActivityInfo(comp, flags, userId); 7364 if (ai == null) { 7365 continue; 7366 } 7367 } 7368 7369 // Look for any generic query activities that are duplicates 7370 // of this specific one, and remove them from the results. 7371 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7372 N = results.size(); 7373 int j; 7374 for (j=specificsPos; j<N; j++) { 7375 ResolveInfo sri = results.get(j); 7376 if ((sri.activityInfo.name.equals(comp.getClassName()) 7377 && sri.activityInfo.applicationInfo.packageName.equals( 7378 comp.getPackageName())) 7379 || (action != null && sri.filter.matchAction(action))) { 7380 results.remove(j); 7381 if (DEBUG_INTENT_MATCHING) Log.v( 7382 TAG, "Removing duplicate item from " + j 7383 + " due to specific " + specificsPos); 7384 if (ri == null) { 7385 ri = sri; 7386 } 7387 j--; 7388 N--; 7389 } 7390 } 7391 7392 // Add this specific item to its proper place. 7393 if (ri == null) { 7394 ri = new ResolveInfo(); 7395 ri.activityInfo = ai; 7396 } 7397 results.add(specificsPos, ri); 7398 ri.specificIndex = i; 7399 specificsPos++; 7400 } 7401 } 7402 7403 // Now we go through the remaining generic results and remove any 7404 // duplicate actions that are found here. 7405 N = results.size(); 7406 for (int i=specificsPos; i<N-1; i++) { 7407 final ResolveInfo rii = results.get(i); 7408 if (rii.filter == null) { 7409 continue; 7410 } 7411 7412 // Iterate over all of the actions of this result's intent 7413 // filter... typically this should be just one. 7414 final Iterator<String> it = rii.filter.actionsIterator(); 7415 if (it == null) { 7416 continue; 7417 } 7418 while (it.hasNext()) { 7419 final String action = it.next(); 7420 if (resultsAction != null && resultsAction.equals(action)) { 7421 // If this action was explicitly requested, then don't 7422 // remove things that have it. 7423 continue; 7424 } 7425 for (int j=i+1; j<N; j++) { 7426 final ResolveInfo rij = results.get(j); 7427 if (rij.filter != null && rij.filter.hasAction(action)) { 7428 results.remove(j); 7429 if (DEBUG_INTENT_MATCHING) Log.v( 7430 TAG, "Removing duplicate item from " + j 7431 + " due to action " + action + " at " + i); 7432 j--; 7433 N--; 7434 } 7435 } 7436 } 7437 7438 // If the caller didn't request filter information, drop it now 7439 // so we don't have to marshall/unmarshall it. 7440 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7441 rii.filter = null; 7442 } 7443 } 7444 7445 // Filter out the caller activity if so requested. 7446 if (caller != null) { 7447 N = results.size(); 7448 for (int i=0; i<N; i++) { 7449 ActivityInfo ainfo = results.get(i).activityInfo; 7450 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7451 && caller.getClassName().equals(ainfo.name)) { 7452 results.remove(i); 7453 break; 7454 } 7455 } 7456 } 7457 7458 // If the caller didn't request filter information, 7459 // drop them now so we don't have to 7460 // marshall/unmarshall it. 7461 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7462 N = results.size(); 7463 for (int i=0; i<N; i++) { 7464 results.get(i).filter = null; 7465 } 7466 } 7467 7468 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7469 return results; 7470 } 7471 7472 @Override 7473 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7474 String resolvedType, int flags, int userId) { 7475 return new ParceledListSlice<>( 7476 queryIntentReceiversInternal(intent, resolvedType, flags, userId, 7477 false /*allowDynamicSplits*/)); 7478 } 7479 7480 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7481 String resolvedType, int flags, int userId, boolean allowDynamicSplits) { 7482 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7483 final int callingUid = Binder.getCallingUid(); 7484 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7485 false /*requireFullPermission*/, false /*checkShell*/, 7486 "query intent receivers"); 7487 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7488 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7489 false /*includeInstantApps*/); 7490 ComponentName comp = intent.getComponent(); 7491 if (comp == null) { 7492 if (intent.getSelector() != null) { 7493 intent = intent.getSelector(); 7494 comp = intent.getComponent(); 7495 } 7496 } 7497 if (comp != null) { 7498 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7499 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7500 if (ai != null) { 7501 // When specifying an explicit component, we prevent the activity from being 7502 // used when either 1) the calling package is normal and the activity is within 7503 // an instant application or 2) the calling package is ephemeral and the 7504 // activity is not visible to instant applications. 7505 final boolean matchInstantApp = 7506 (flags & PackageManager.MATCH_INSTANT) != 0; 7507 final boolean matchVisibleToInstantAppOnly = 7508 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7509 final boolean matchExplicitlyVisibleOnly = 7510 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7511 final boolean isCallerInstantApp = 7512 instantAppPkgName != null; 7513 final boolean isTargetSameInstantApp = 7514 comp.getPackageName().equals(instantAppPkgName); 7515 final boolean isTargetInstantApp = 7516 (ai.applicationInfo.privateFlags 7517 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7518 final boolean isTargetVisibleToInstantApp = 7519 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7520 final boolean isTargetExplicitlyVisibleToInstantApp = 7521 isTargetVisibleToInstantApp 7522 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7523 final boolean isTargetHiddenFromInstantApp = 7524 !isTargetVisibleToInstantApp 7525 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7526 final boolean blockResolution = 7527 !isTargetSameInstantApp 7528 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7529 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7530 && isTargetHiddenFromInstantApp)); 7531 if (!blockResolution) { 7532 ResolveInfo ri = new ResolveInfo(); 7533 ri.activityInfo = ai; 7534 list.add(ri); 7535 } 7536 } 7537 return applyPostResolutionFilter( 7538 list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent); 7539 } 7540 7541 // reader 7542 synchronized (mPackages) { 7543 String pkgName = intent.getPackage(); 7544 if (pkgName == null) { 7545 final List<ResolveInfo> result = 7546 mReceivers.queryIntent(intent, resolvedType, flags, userId); 7547 return applyPostResolutionFilter( 7548 result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent); 7549 } 7550 final PackageParser.Package pkg = mPackages.get(pkgName); 7551 if (pkg != null) { 7552 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 7553 intent, resolvedType, flags, pkg.receivers, userId); 7554 return applyPostResolutionFilter( 7555 result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent); 7556 } 7557 return Collections.emptyList(); 7558 } 7559 } 7560 7561 @Override 7562 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7563 final int callingUid = Binder.getCallingUid(); 7564 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7565 } 7566 7567 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7568 int userId, int callingUid) { 7569 if (!sUserManager.exists(userId)) return null; 7570 flags = updateFlagsForResolve( 7571 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7572 List<ResolveInfo> query = queryIntentServicesInternal( 7573 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7574 if (query != null) { 7575 if (query.size() >= 1) { 7576 // If there is more than one service with the same priority, 7577 // just arbitrarily pick the first one. 7578 return query.get(0); 7579 } 7580 } 7581 return null; 7582 } 7583 7584 @Override 7585 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7586 String resolvedType, int flags, int userId) { 7587 final int callingUid = Binder.getCallingUid(); 7588 return new ParceledListSlice<>(queryIntentServicesInternal( 7589 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7590 } 7591 7592 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7593 String resolvedType, int flags, int userId, int callingUid, 7594 boolean includeInstantApps) { 7595 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7596 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7597 false /*requireFullPermission*/, false /*checkShell*/, 7598 "query intent receivers"); 7599 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7600 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7601 ComponentName comp = intent.getComponent(); 7602 if (comp == null) { 7603 if (intent.getSelector() != null) { 7604 intent = intent.getSelector(); 7605 comp = intent.getComponent(); 7606 } 7607 } 7608 if (comp != null) { 7609 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7610 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7611 if (si != null) { 7612 // When specifying an explicit component, we prevent the service from being 7613 // used when either 1) the service is in an instant application and the 7614 // caller is not the same instant application or 2) the calling package is 7615 // ephemeral and the activity is not visible to ephemeral applications. 7616 final boolean matchInstantApp = 7617 (flags & PackageManager.MATCH_INSTANT) != 0; 7618 final boolean matchVisibleToInstantAppOnly = 7619 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7620 final boolean isCallerInstantApp = 7621 instantAppPkgName != null; 7622 final boolean isTargetSameInstantApp = 7623 comp.getPackageName().equals(instantAppPkgName); 7624 final boolean isTargetInstantApp = 7625 (si.applicationInfo.privateFlags 7626 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7627 final boolean isTargetHiddenFromInstantApp = 7628 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7629 final boolean blockResolution = 7630 !isTargetSameInstantApp 7631 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7632 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7633 && isTargetHiddenFromInstantApp)); 7634 if (!blockResolution) { 7635 final ResolveInfo ri = new ResolveInfo(); 7636 ri.serviceInfo = si; 7637 list.add(ri); 7638 } 7639 } 7640 return list; 7641 } 7642 7643 // reader 7644 synchronized (mPackages) { 7645 String pkgName = intent.getPackage(); 7646 if (pkgName == null) { 7647 return applyPostServiceResolutionFilter( 7648 mServices.queryIntent(intent, resolvedType, flags, userId), 7649 instantAppPkgName); 7650 } 7651 final PackageParser.Package pkg = mPackages.get(pkgName); 7652 if (pkg != null) { 7653 return applyPostServiceResolutionFilter( 7654 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7655 userId), 7656 instantAppPkgName); 7657 } 7658 return Collections.emptyList(); 7659 } 7660 } 7661 7662 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7663 String instantAppPkgName) { 7664 if (instantAppPkgName == null) { 7665 return resolveInfos; 7666 } 7667 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7668 final ResolveInfo info = resolveInfos.get(i); 7669 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7670 // allow services that are defined in the provided package 7671 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7672 if (info.serviceInfo.splitName != null 7673 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7674 info.serviceInfo.splitName)) { 7675 // requested service is defined in a split that hasn't been installed yet. 7676 // add the installer to the resolve list 7677 if (DEBUG_INSTANT) { 7678 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7679 } 7680 final ResolveInfo installerInfo = new ResolveInfo( 7681 mInstantAppInstallerInfo); 7682 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7683 null /* installFailureActivity */, 7684 info.serviceInfo.packageName, 7685 info.serviceInfo.applicationInfo.versionCode, 7686 info.serviceInfo.splitName); 7687 // add a non-generic filter 7688 installerInfo.filter = new IntentFilter(); 7689 // load resources from the correct package 7690 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7691 resolveInfos.set(i, installerInfo); 7692 } 7693 continue; 7694 } 7695 // allow services that have been explicitly exposed to ephemeral apps 7696 if (!isEphemeralApp 7697 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7698 continue; 7699 } 7700 resolveInfos.remove(i); 7701 } 7702 return resolveInfos; 7703 } 7704 7705 @Override 7706 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7707 String resolvedType, int flags, int userId) { 7708 return new ParceledListSlice<>( 7709 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7710 } 7711 7712 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7713 Intent intent, String resolvedType, int flags, int userId) { 7714 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7715 final int callingUid = Binder.getCallingUid(); 7716 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7717 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7718 false /*includeInstantApps*/); 7719 ComponentName comp = intent.getComponent(); 7720 if (comp == null) { 7721 if (intent.getSelector() != null) { 7722 intent = intent.getSelector(); 7723 comp = intent.getComponent(); 7724 } 7725 } 7726 if (comp != null) { 7727 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7728 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7729 if (pi != null) { 7730 // When specifying an explicit component, we prevent the provider from being 7731 // used when either 1) the provider is in an instant application and the 7732 // caller is not the same instant application or 2) the calling package is an 7733 // instant application and the provider is not visible to instant applications. 7734 final boolean matchInstantApp = 7735 (flags & PackageManager.MATCH_INSTANT) != 0; 7736 final boolean matchVisibleToInstantAppOnly = 7737 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7738 final boolean isCallerInstantApp = 7739 instantAppPkgName != null; 7740 final boolean isTargetSameInstantApp = 7741 comp.getPackageName().equals(instantAppPkgName); 7742 final boolean isTargetInstantApp = 7743 (pi.applicationInfo.privateFlags 7744 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7745 final boolean isTargetHiddenFromInstantApp = 7746 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7747 final boolean blockResolution = 7748 !isTargetSameInstantApp 7749 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7750 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7751 && isTargetHiddenFromInstantApp)); 7752 if (!blockResolution) { 7753 final ResolveInfo ri = new ResolveInfo(); 7754 ri.providerInfo = pi; 7755 list.add(ri); 7756 } 7757 } 7758 return list; 7759 } 7760 7761 // reader 7762 synchronized (mPackages) { 7763 String pkgName = intent.getPackage(); 7764 if (pkgName == null) { 7765 return applyPostContentProviderResolutionFilter( 7766 mProviders.queryIntent(intent, resolvedType, flags, userId), 7767 instantAppPkgName); 7768 } 7769 final PackageParser.Package pkg = mPackages.get(pkgName); 7770 if (pkg != null) { 7771 return applyPostContentProviderResolutionFilter( 7772 mProviders.queryIntentForPackage( 7773 intent, resolvedType, flags, pkg.providers, userId), 7774 instantAppPkgName); 7775 } 7776 return Collections.emptyList(); 7777 } 7778 } 7779 7780 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7781 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7782 if (instantAppPkgName == null) { 7783 return resolveInfos; 7784 } 7785 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7786 final ResolveInfo info = resolveInfos.get(i); 7787 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7788 // allow providers that are defined in the provided package 7789 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7790 if (info.providerInfo.splitName != null 7791 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7792 info.providerInfo.splitName)) { 7793 // requested provider is defined in a split that hasn't been installed yet. 7794 // add the installer to the resolve list 7795 if (DEBUG_INSTANT) { 7796 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7797 } 7798 final ResolveInfo installerInfo = new ResolveInfo( 7799 mInstantAppInstallerInfo); 7800 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7801 null /*failureActivity*/, 7802 info.providerInfo.packageName, 7803 info.providerInfo.applicationInfo.versionCode, 7804 info.providerInfo.splitName); 7805 // add a non-generic filter 7806 installerInfo.filter = new IntentFilter(); 7807 // load resources from the correct package 7808 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7809 resolveInfos.set(i, installerInfo); 7810 } 7811 continue; 7812 } 7813 // allow providers that have been explicitly exposed to instant applications 7814 if (!isEphemeralApp 7815 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7816 continue; 7817 } 7818 resolveInfos.remove(i); 7819 } 7820 return resolveInfos; 7821 } 7822 7823 @Override 7824 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7825 final int callingUid = Binder.getCallingUid(); 7826 if (getInstantAppPackageName(callingUid) != null) { 7827 return ParceledListSlice.emptyList(); 7828 } 7829 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7830 flags = updateFlagsForPackage(flags, userId, null); 7831 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7832 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7833 true /* requireFullPermission */, false /* checkShell */, 7834 "get installed packages"); 7835 7836 // writer 7837 synchronized (mPackages) { 7838 ArrayList<PackageInfo> list; 7839 if (listUninstalled) { 7840 list = new ArrayList<>(mSettings.mPackages.size()); 7841 for (PackageSetting ps : mSettings.mPackages.values()) { 7842 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7843 continue; 7844 } 7845 if (filterAppAccessLPr(ps, callingUid, userId)) { 7846 continue; 7847 } 7848 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7849 if (pi != null) { 7850 list.add(pi); 7851 } 7852 } 7853 } else { 7854 list = new ArrayList<>(mPackages.size()); 7855 for (PackageParser.Package p : mPackages.values()) { 7856 final PackageSetting ps = (PackageSetting) p.mExtras; 7857 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7858 continue; 7859 } 7860 if (filterAppAccessLPr(ps, callingUid, userId)) { 7861 continue; 7862 } 7863 final PackageInfo pi = generatePackageInfo((PackageSetting) 7864 p.mExtras, flags, userId); 7865 if (pi != null) { 7866 list.add(pi); 7867 } 7868 } 7869 } 7870 7871 return new ParceledListSlice<>(list); 7872 } 7873 } 7874 7875 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7876 String[] permissions, boolean[] tmp, int flags, int userId) { 7877 int numMatch = 0; 7878 final PermissionsState permissionsState = ps.getPermissionsState(); 7879 for (int i=0; i<permissions.length; i++) { 7880 final String permission = permissions[i]; 7881 if (permissionsState.hasPermission(permission, userId)) { 7882 tmp[i] = true; 7883 numMatch++; 7884 } else { 7885 tmp[i] = false; 7886 } 7887 } 7888 if (numMatch == 0) { 7889 return; 7890 } 7891 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7892 7893 // The above might return null in cases of uninstalled apps or install-state 7894 // skew across users/profiles. 7895 if (pi != null) { 7896 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7897 if (numMatch == permissions.length) { 7898 pi.requestedPermissions = permissions; 7899 } else { 7900 pi.requestedPermissions = new String[numMatch]; 7901 numMatch = 0; 7902 for (int i=0; i<permissions.length; i++) { 7903 if (tmp[i]) { 7904 pi.requestedPermissions[numMatch] = permissions[i]; 7905 numMatch++; 7906 } 7907 } 7908 } 7909 } 7910 list.add(pi); 7911 } 7912 } 7913 7914 @Override 7915 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7916 String[] permissions, int flags, int userId) { 7917 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7918 flags = updateFlagsForPackage(flags, userId, permissions); 7919 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7920 true /* requireFullPermission */, false /* checkShell */, 7921 "get packages holding permissions"); 7922 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7923 7924 // writer 7925 synchronized (mPackages) { 7926 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7927 boolean[] tmpBools = new boolean[permissions.length]; 7928 if (listUninstalled) { 7929 for (PackageSetting ps : mSettings.mPackages.values()) { 7930 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7931 userId); 7932 } 7933 } else { 7934 for (PackageParser.Package pkg : mPackages.values()) { 7935 PackageSetting ps = (PackageSetting)pkg.mExtras; 7936 if (ps != null) { 7937 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7938 userId); 7939 } 7940 } 7941 } 7942 7943 return new ParceledListSlice<PackageInfo>(list); 7944 } 7945 } 7946 7947 @Override 7948 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7949 final int callingUid = Binder.getCallingUid(); 7950 if (getInstantAppPackageName(callingUid) != null) { 7951 return ParceledListSlice.emptyList(); 7952 } 7953 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7954 flags = updateFlagsForApplication(flags, userId, null); 7955 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7956 7957 // writer 7958 synchronized (mPackages) { 7959 ArrayList<ApplicationInfo> list; 7960 if (listUninstalled) { 7961 list = new ArrayList<>(mSettings.mPackages.size()); 7962 for (PackageSetting ps : mSettings.mPackages.values()) { 7963 ApplicationInfo ai; 7964 int effectiveFlags = flags; 7965 if (ps.isSystem()) { 7966 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7967 } 7968 if (ps.pkg != null) { 7969 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7970 continue; 7971 } 7972 if (filterAppAccessLPr(ps, callingUid, userId)) { 7973 continue; 7974 } 7975 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7976 ps.readUserState(userId), userId); 7977 if (ai != null) { 7978 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7979 } 7980 } else { 7981 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7982 // and already converts to externally visible package name 7983 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7984 callingUid, effectiveFlags, userId); 7985 } 7986 if (ai != null) { 7987 list.add(ai); 7988 } 7989 } 7990 } else { 7991 list = new ArrayList<>(mPackages.size()); 7992 for (PackageParser.Package p : mPackages.values()) { 7993 if (p.mExtras != null) { 7994 PackageSetting ps = (PackageSetting) p.mExtras; 7995 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 7996 continue; 7997 } 7998 if (filterAppAccessLPr(ps, callingUid, userId)) { 7999 continue; 8000 } 8001 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8002 ps.readUserState(userId), userId); 8003 if (ai != null) { 8004 ai.packageName = resolveExternalPackageNameLPr(p); 8005 list.add(ai); 8006 } 8007 } 8008 } 8009 } 8010 8011 return new ParceledListSlice<>(list); 8012 } 8013 } 8014 8015 @Override 8016 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 8017 if (HIDE_EPHEMERAL_APIS) { 8018 return null; 8019 } 8020 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8021 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8022 "getEphemeralApplications"); 8023 } 8024 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8025 true /* requireFullPermission */, false /* checkShell */, 8026 "getEphemeralApplications"); 8027 synchronized (mPackages) { 8028 List<InstantAppInfo> instantApps = mInstantAppRegistry 8029 .getInstantAppsLPr(userId); 8030 if (instantApps != null) { 8031 return new ParceledListSlice<>(instantApps); 8032 } 8033 } 8034 return null; 8035 } 8036 8037 @Override 8038 public boolean isInstantApp(String packageName, int userId) { 8039 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8040 true /* requireFullPermission */, false /* checkShell */, 8041 "isInstantApp"); 8042 if (HIDE_EPHEMERAL_APIS) { 8043 return false; 8044 } 8045 8046 synchronized (mPackages) { 8047 int callingUid = Binder.getCallingUid(); 8048 if (Process.isIsolated(callingUid)) { 8049 callingUid = mIsolatedOwners.get(callingUid); 8050 } 8051 final PackageSetting ps = mSettings.mPackages.get(packageName); 8052 PackageParser.Package pkg = mPackages.get(packageName); 8053 final boolean returnAllowed = 8054 ps != null 8055 && (isCallerSameApp(packageName, callingUid) 8056 || canViewInstantApps(callingUid, userId) 8057 || mInstantAppRegistry.isInstantAccessGranted( 8058 userId, UserHandle.getAppId(callingUid), ps.appId)); 8059 if (returnAllowed) { 8060 return ps.getInstantApp(userId); 8061 } 8062 } 8063 return false; 8064 } 8065 8066 @Override 8067 public byte[] getInstantAppCookie(String packageName, int userId) { 8068 if (HIDE_EPHEMERAL_APIS) { 8069 return null; 8070 } 8071 8072 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8073 true /* requireFullPermission */, false /* checkShell */, 8074 "getInstantAppCookie"); 8075 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8076 return null; 8077 } 8078 synchronized (mPackages) { 8079 return mInstantAppRegistry.getInstantAppCookieLPw( 8080 packageName, userId); 8081 } 8082 } 8083 8084 @Override 8085 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 8086 if (HIDE_EPHEMERAL_APIS) { 8087 return true; 8088 } 8089 8090 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8091 true /* requireFullPermission */, true /* checkShell */, 8092 "setInstantAppCookie"); 8093 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8094 return false; 8095 } 8096 synchronized (mPackages) { 8097 return mInstantAppRegistry.setInstantAppCookieLPw( 8098 packageName, cookie, userId); 8099 } 8100 } 8101 8102 @Override 8103 public Bitmap getInstantAppIcon(String packageName, int userId) { 8104 if (HIDE_EPHEMERAL_APIS) { 8105 return null; 8106 } 8107 8108 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8109 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8110 "getInstantAppIcon"); 8111 } 8112 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8113 true /* requireFullPermission */, false /* checkShell */, 8114 "getInstantAppIcon"); 8115 8116 synchronized (mPackages) { 8117 return mInstantAppRegistry.getInstantAppIconLPw( 8118 packageName, userId); 8119 } 8120 } 8121 8122 private boolean isCallerSameApp(String packageName, int uid) { 8123 PackageParser.Package pkg = mPackages.get(packageName); 8124 return pkg != null 8125 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 8126 } 8127 8128 @Override 8129 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 8130 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8131 return ParceledListSlice.emptyList(); 8132 } 8133 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 8134 } 8135 8136 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 8137 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 8138 8139 // reader 8140 synchronized (mPackages) { 8141 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 8142 final int userId = UserHandle.getCallingUserId(); 8143 while (i.hasNext()) { 8144 final PackageParser.Package p = i.next(); 8145 if (p.applicationInfo == null) continue; 8146 8147 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 8148 && !p.applicationInfo.isDirectBootAware(); 8149 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 8150 && p.applicationInfo.isDirectBootAware(); 8151 8152 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 8153 && (!mSafeMode || isSystemApp(p)) 8154 && (matchesUnaware || matchesAware)) { 8155 PackageSetting ps = mSettings.mPackages.get(p.packageName); 8156 if (ps != null) { 8157 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8158 ps.readUserState(userId), userId); 8159 if (ai != null) { 8160 finalList.add(ai); 8161 } 8162 } 8163 } 8164 } 8165 } 8166 8167 return finalList; 8168 } 8169 8170 @Override 8171 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 8172 return resolveContentProviderInternal(name, flags, userId); 8173 } 8174 8175 private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) { 8176 if (!sUserManager.exists(userId)) return null; 8177 flags = updateFlagsForComponent(flags, userId, name); 8178 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 8179 // reader 8180 synchronized (mPackages) { 8181 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 8182 PackageSetting ps = provider != null 8183 ? mSettings.mPackages.get(provider.owner.packageName) 8184 : null; 8185 if (ps != null) { 8186 final boolean isInstantApp = ps.getInstantApp(userId); 8187 // normal application; filter out instant application provider 8188 if (instantAppPkgName == null && isInstantApp) { 8189 return null; 8190 } 8191 // instant application; filter out other instant applications 8192 if (instantAppPkgName != null 8193 && isInstantApp 8194 && !provider.owner.packageName.equals(instantAppPkgName)) { 8195 return null; 8196 } 8197 // instant application; filter out non-exposed provider 8198 if (instantAppPkgName != null 8199 && !isInstantApp 8200 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 8201 return null; 8202 } 8203 // provider not enabled 8204 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 8205 return null; 8206 } 8207 return PackageParser.generateProviderInfo( 8208 provider, flags, ps.readUserState(userId), userId); 8209 } 8210 return null; 8211 } 8212 } 8213 8214 /** 8215 * @deprecated 8216 */ 8217 @Deprecated 8218 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 8219 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8220 return; 8221 } 8222 // reader 8223 synchronized (mPackages) { 8224 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 8225 .entrySet().iterator(); 8226 final int userId = UserHandle.getCallingUserId(); 8227 while (i.hasNext()) { 8228 Map.Entry<String, PackageParser.Provider> entry = i.next(); 8229 PackageParser.Provider p = entry.getValue(); 8230 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8231 8232 if (ps != null && p.syncable 8233 && (!mSafeMode || (p.info.applicationInfo.flags 8234 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 8235 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 8236 ps.readUserState(userId), userId); 8237 if (info != null) { 8238 outNames.add(entry.getKey()); 8239 outInfo.add(info); 8240 } 8241 } 8242 } 8243 } 8244 } 8245 8246 @Override 8247 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8248 int uid, int flags, String metaDataKey) { 8249 final int callingUid = Binder.getCallingUid(); 8250 final int userId = processName != null ? UserHandle.getUserId(uid) 8251 : UserHandle.getCallingUserId(); 8252 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8253 flags = updateFlagsForComponent(flags, userId, processName); 8254 ArrayList<ProviderInfo> finalList = null; 8255 // reader 8256 synchronized (mPackages) { 8257 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 8258 while (i.hasNext()) { 8259 final PackageParser.Provider p = i.next(); 8260 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8261 if (ps != null && p.info.authority != null 8262 && (processName == null 8263 || (p.info.processName.equals(processName) 8264 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 8265 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 8266 8267 // See PM.queryContentProviders()'s javadoc for why we have the metaData 8268 // parameter. 8269 if (metaDataKey != null 8270 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 8271 continue; 8272 } 8273 final ComponentName component = 8274 new ComponentName(p.info.packageName, p.info.name); 8275 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8276 continue; 8277 } 8278 if (finalList == null) { 8279 finalList = new ArrayList<ProviderInfo>(3); 8280 } 8281 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8282 ps.readUserState(userId), userId); 8283 if (info != null) { 8284 finalList.add(info); 8285 } 8286 } 8287 } 8288 } 8289 8290 if (finalList != null) { 8291 Collections.sort(finalList, mProviderInitOrderSorter); 8292 return new ParceledListSlice<ProviderInfo>(finalList); 8293 } 8294 8295 return ParceledListSlice.emptyList(); 8296 } 8297 8298 @Override 8299 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8300 // reader 8301 synchronized (mPackages) { 8302 final int callingUid = Binder.getCallingUid(); 8303 final int callingUserId = UserHandle.getUserId(callingUid); 8304 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8305 if (ps == null) return null; 8306 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8307 return null; 8308 } 8309 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8310 return PackageParser.generateInstrumentationInfo(i, flags); 8311 } 8312 } 8313 8314 @Override 8315 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8316 String targetPackage, int flags) { 8317 final int callingUid = Binder.getCallingUid(); 8318 final int callingUserId = UserHandle.getUserId(callingUid); 8319 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8320 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8321 return ParceledListSlice.emptyList(); 8322 } 8323 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8324 } 8325 8326 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8327 int flags) { 8328 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 8329 8330 // reader 8331 synchronized (mPackages) { 8332 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8333 while (i.hasNext()) { 8334 final PackageParser.Instrumentation p = i.next(); 8335 if (targetPackage == null 8336 || targetPackage.equals(p.info.targetPackage)) { 8337 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8338 flags); 8339 if (ii != null) { 8340 finalList.add(ii); 8341 } 8342 } 8343 } 8344 } 8345 8346 return finalList; 8347 } 8348 8349 private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) { 8350 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]"); 8351 try { 8352 scanDirLI(scanDir, parseFlags, scanFlags, currentTime); 8353 } finally { 8354 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8355 } 8356 } 8357 8358 private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) { 8359 final File[] files = scanDir.listFiles(); 8360 if (ArrayUtils.isEmpty(files)) { 8361 Log.d(TAG, "No files in app dir " + scanDir); 8362 return; 8363 } 8364 8365 if (DEBUG_PACKAGE_SCANNING) { 8366 Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags 8367 + " flags=0x" + Integer.toHexString(parseFlags)); 8368 } 8369 try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8370 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8371 mParallelPackageParserCallback)) { 8372 // Submit files for parsing in parallel 8373 int fileCount = 0; 8374 for (File file : files) { 8375 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8376 && !PackageInstallerService.isStageName(file.getName()); 8377 if (!isPackage) { 8378 // Ignore entries which are not packages 8379 continue; 8380 } 8381 parallelPackageParser.submit(file, parseFlags); 8382 fileCount++; 8383 } 8384 8385 // Process results one by one 8386 for (; fileCount > 0; fileCount--) { 8387 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8388 Throwable throwable = parseResult.throwable; 8389 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8390 8391 if (throwable == null) { 8392 // TODO(toddke): move lower in the scan chain 8393 // Static shared libraries have synthetic package names 8394 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8395 renameStaticSharedLibraryPackage(parseResult.pkg); 8396 } 8397 try { 8398 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8399 scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags, 8400 currentTime, null); 8401 } 8402 } catch (PackageManagerException e) { 8403 errorCode = e.error; 8404 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8405 } 8406 } else if (throwable instanceof PackageParser.PackageParserException) { 8407 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8408 throwable; 8409 errorCode = e.error; 8410 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8411 } else { 8412 throw new IllegalStateException("Unexpected exception occurred while parsing " 8413 + parseResult.scanFile, throwable); 8414 } 8415 8416 // Delete invalid userdata apps 8417 if ((scanFlags & SCAN_AS_SYSTEM) == 0 && 8418 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8419 logCriticalInfo(Log.WARN, 8420 "Deleting invalid package at " + parseResult.scanFile); 8421 removeCodePathLI(parseResult.scanFile); 8422 } 8423 } 8424 } 8425 } 8426 8427 public static void reportSettingsProblem(int priority, String msg) { 8428 logCriticalInfo(priority, msg); 8429 } 8430 8431 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, 8432 boolean forceCollect, boolean skipVerify) throws PackageManagerException { 8433 // When upgrading from pre-N MR1, verify the package time stamp using the package 8434 // directory and not the APK file. 8435 final long lastModifiedTime = mIsPreNMR1Upgrade 8436 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg); 8437 if (ps != null && !forceCollect 8438 && ps.codePathString.equals(pkg.codePath) 8439 && ps.timeStamp == lastModifiedTime 8440 && !isCompatSignatureUpdateNeeded(pkg) 8441 && !isRecoverSignatureUpdateNeeded(pkg)) { 8442 if (ps.signatures.mSigningDetails.signatures != null 8443 && ps.signatures.mSigningDetails.signatures.length != 0 8444 && ps.signatures.mSigningDetails.signatureSchemeVersion 8445 != SignatureSchemeVersion.UNKNOWN) { 8446 // Optimization: reuse the existing cached signing data 8447 // if the package appears to be unchanged. 8448 pkg.mSigningDetails = 8449 new PackageParser.SigningDetails(ps.signatures.mSigningDetails); 8450 return; 8451 } 8452 8453 Slog.w(TAG, "PackageSetting for " + ps.name 8454 + " is missing signatures. Collecting certs again to recover them."); 8455 } else { 8456 Slog.i(TAG, pkg.codePath + " changed; collecting certs" + 8457 (forceCollect ? " (forced)" : "")); 8458 } 8459 8460 try { 8461 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8462 PackageParser.collectCertificates(pkg, skipVerify); 8463 } catch (PackageParserException e) { 8464 throw PackageManagerException.from(e); 8465 } finally { 8466 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8467 } 8468 } 8469 8470 /** 8471 * Traces a package scan. 8472 * @see #scanPackageLI(File, int, int, long, UserHandle) 8473 */ 8474 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8475 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8476 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8477 try { 8478 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8479 } finally { 8480 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8481 } 8482 } 8483 8484 /** 8485 * Scans a package and returns the newly parsed package. 8486 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8487 */ 8488 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8489 long currentTime, UserHandle user) throws PackageManagerException { 8490 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8491 PackageParser pp = new PackageParser(); 8492 pp.setSeparateProcesses(mSeparateProcesses); 8493 pp.setOnlyCoreApps(mOnlyCore); 8494 pp.setDisplayMetrics(mMetrics); 8495 pp.setCallback(mPackageParserCallback); 8496 8497 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8498 final PackageParser.Package pkg; 8499 try { 8500 pkg = pp.parsePackage(scanFile, parseFlags); 8501 } catch (PackageParserException e) { 8502 throw PackageManagerException.from(e); 8503 } finally { 8504 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8505 } 8506 8507 // Static shared libraries have synthetic package names 8508 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8509 renameStaticSharedLibraryPackage(pkg); 8510 } 8511 8512 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8513 } 8514 8515 /** 8516 * Scans a package and returns the newly parsed package. 8517 * @throws PackageManagerException on a parse error. 8518 */ 8519 private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg, 8520 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8521 @Nullable UserHandle user) 8522 throws PackageManagerException { 8523 // If the package has children and this is the first dive in the function 8524 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8525 // packages (parent and children) would be successfully scanned before the 8526 // actual scan since scanning mutates internal state and we want to atomically 8527 // install the package and its children. 8528 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8529 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8530 scanFlags |= SCAN_CHECK_ONLY; 8531 } 8532 } else { 8533 scanFlags &= ~SCAN_CHECK_ONLY; 8534 } 8535 8536 // Scan the parent 8537 PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags, 8538 scanFlags, currentTime, user); 8539 8540 // Scan the children 8541 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8542 for (int i = 0; i < childCount; i++) { 8543 PackageParser.Package childPackage = pkg.childPackages.get(i); 8544 addForInitLI(childPackage, parseFlags, scanFlags, 8545 currentTime, user); 8546 } 8547 8548 8549 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8550 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8551 } 8552 8553 return scannedPkg; 8554 } 8555 8556 /** 8557 * Returns if full apk verification can be skipped for the whole package, including the splits. 8558 */ 8559 private boolean canSkipFullPackageVerification(PackageParser.Package pkg) { 8560 if (!canSkipFullApkVerification(pkg.baseCodePath)) { 8561 return false; 8562 } 8563 // TODO: Allow base and splits to be verified individually. 8564 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8565 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8566 if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) { 8567 return false; 8568 } 8569 } 8570 } 8571 return true; 8572 } 8573 8574 /** 8575 * Returns if full apk verification can be skipped, depending on current FSVerity setup and 8576 * whether the apk contains signed root hash. Note that the signer's certificate still needs to 8577 * match one in a trusted source, and should be done separately. 8578 */ 8579 private boolean canSkipFullApkVerification(String apkPath) { 8580 byte[] rootHashObserved = null; 8581 try { 8582 rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath); 8583 if (rootHashObserved == null) { 8584 return false; // APK does not contain Merkle tree root hash. 8585 } 8586 synchronized (mInstallLock) { 8587 // Returns whether the observed root hash matches what kernel has. 8588 mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved); 8589 return true; 8590 } 8591 } catch (InstallerException | IOException | DigestException | 8592 NoSuchAlgorithmException e) { 8593 Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e); 8594 } 8595 return false; 8596 } 8597 8598 /** 8599 * Adds a new package to the internal data structures during platform initialization. 8600 * <p>After adding, the package is known to the system and available for querying. 8601 * <p>For packages located on the device ROM [eg. packages located in /system, /vendor, 8602 * etc...], additional checks are performed. Basic verification [such as ensuring 8603 * matching signatures, checking version codes, etc...] occurs if the package is 8604 * identical to a previously known package. If the package fails a signature check, 8605 * the version installed on /data will be removed. If the version of the new package 8606 * is less than or equal than the version on /data, it will be ignored. 8607 * <p>Regardless of the package location, the results are applied to the internal 8608 * structures and the package is made available to the rest of the system. 8609 * <p>NOTE: The return value should be removed. It's the passed in package object. 8610 */ 8611 private PackageParser.Package addForInitLI(PackageParser.Package pkg, 8612 @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8613 @Nullable UserHandle user) 8614 throws PackageManagerException { 8615 final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0; 8616 final String renamedPkgName; 8617 final PackageSetting disabledPkgSetting; 8618 final boolean isSystemPkgUpdated; 8619 final boolean pkgAlreadyExists; 8620 PackageSetting pkgSetting; 8621 8622 // NOTE: installPackageLI() has the same code to setup the package's 8623 // application info. This probably should be done lower in the call 8624 // stack [such as scanPackageOnly()]. However, we verify the application 8625 // info prior to that [in scanPackageNew()] and thus have to setup 8626 // the application info early. 8627 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8628 pkg.setApplicationInfoCodePath(pkg.codePath); 8629 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8630 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8631 pkg.setApplicationInfoResourcePath(pkg.codePath); 8632 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 8633 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8634 8635 synchronized (mPackages) { 8636 renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8637 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 8638 if (realPkgName != null) { 8639 ensurePackageRenamed(pkg, renamedPkgName); 8640 } 8641 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 8642 final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName); 8643 pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting; 8644 pkgAlreadyExists = pkgSetting != null; 8645 final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName; 8646 disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName); 8647 isSystemPkgUpdated = disabledPkgSetting != null; 8648 8649 if (DEBUG_INSTALL && isSystemPkgUpdated) { 8650 Slog.d(TAG, "updatedPkg = " + disabledPkgSetting); 8651 } 8652 8653 final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null) 8654 ? mSettings.getSharedUserLPw(pkg.mSharedUserId, 8655 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true) 8656 : null; 8657 if (DEBUG_PACKAGE_SCANNING 8658 && (parseFlags & PackageParser.PARSE_CHATTY) != 0 8659 && sharedUserSetting != null) { 8660 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 8661 + " (uid=" + sharedUserSetting.userId + "):" 8662 + " packages=" + sharedUserSetting.packages); 8663 } 8664 8665 if (scanSystemPartition) { 8666 // Potentially prune child packages. If the application on the /system 8667 // partition has been updated via OTA, but, is still disabled by a 8668 // version on /data, cycle through all of its children packages and 8669 // remove children that are no longer defined. 8670 if (isSystemPkgUpdated) { 8671 final int scannedChildCount = (pkg.childPackages != null) 8672 ? pkg.childPackages.size() : 0; 8673 final int disabledChildCount = disabledPkgSetting.childPackageNames != null 8674 ? disabledPkgSetting.childPackageNames.size() : 0; 8675 for (int i = 0; i < disabledChildCount; i++) { 8676 String disabledChildPackageName = 8677 disabledPkgSetting.childPackageNames.get(i); 8678 boolean disabledPackageAvailable = false; 8679 for (int j = 0; j < scannedChildCount; j++) { 8680 PackageParser.Package childPkg = pkg.childPackages.get(j); 8681 if (childPkg.packageName.equals(disabledChildPackageName)) { 8682 disabledPackageAvailable = true; 8683 break; 8684 } 8685 } 8686 if (!disabledPackageAvailable) { 8687 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8688 } 8689 } 8690 // we're updating the disabled package, so, scan it as the package setting 8691 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, 8692 disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */, 8693 null /* originalPkgSetting */, null, parseFlags, scanFlags, 8694 (pkg == mPlatformPackage), user); 8695 applyPolicy(pkg, parseFlags, scanFlags); 8696 scanPackageOnlyLI(request, mFactoryTest, -1L); 8697 } 8698 } 8699 } 8700 8701 final boolean newPkgChangedPaths = 8702 pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath); 8703 final boolean newPkgVersionGreater = 8704 pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode; 8705 final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated 8706 && newPkgChangedPaths && newPkgVersionGreater; 8707 if (isSystemPkgBetter) { 8708 // The version of the application on /system is greater than the version on 8709 // /data. Switch back to the application on /system. 8710 // It's safe to assume the application on /system will correctly scan. If not, 8711 // there won't be a working copy of the application. 8712 synchronized (mPackages) { 8713 // just remove the loaded entries from package lists 8714 mPackages.remove(pkgSetting.name); 8715 } 8716 8717 logCriticalInfo(Log.WARN, 8718 "System package updated;" 8719 + " name: " + pkgSetting.name 8720 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8721 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8722 8723 final InstallArgs args = createInstallArgsForExisting( 8724 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8725 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8726 args.cleanUpResourcesLI(); 8727 synchronized (mPackages) { 8728 mSettings.enableSystemPackageLPw(pkgSetting.name); 8729 } 8730 } 8731 8732 if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) { 8733 // The version of the application on the /system partition is less than or 8734 // equal to the version on the /data partition. Throw an exception and use 8735 // the application already installed on the /data partition. 8736 throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at " 8737 + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode 8738 + " better than this " + pkg.getLongVersionCode()); 8739 } 8740 8741 // Verify certificates against what was last scanned. If it is an updated priv app, we will 8742 // force re-collecting certificate. 8743 final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced( 8744 disabledPkgSetting); 8745 // Full APK verification can be skipped during certificate collection, only if the file is 8746 // in verified partition, or can be verified on access (when apk verity is enabled). In both 8747 // cases, only data in Signing Block is verified instead of the whole file. 8748 final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) || 8749 (forceCollect && canSkipFullPackageVerification(pkg)); 8750 collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify); 8751 8752 boolean shouldHideSystemApp = false; 8753 // A new application appeared on /system, but, we already have a copy of 8754 // the application installed on /data. 8755 if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists 8756 && !pkgSetting.isSystem()) { 8757 8758 if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails, 8759 PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) { 8760 logCriticalInfo(Log.WARN, 8761 "System package signature mismatch;" 8762 + " name: " + pkgSetting.name); 8763 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8764 "scanPackageInternalLI")) { 8765 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8766 } 8767 pkgSetting = null; 8768 } else if (newPkgVersionGreater) { 8769 // The application on /system is newer than the application on /data. 8770 // Simply remove the application on /data [keeping application data] 8771 // and replace it with the version on /system. 8772 logCriticalInfo(Log.WARN, 8773 "System package enabled;" 8774 + " name: " + pkgSetting.name 8775 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8776 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8777 InstallArgs args = createInstallArgsForExisting( 8778 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8779 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8780 synchronized (mInstallLock) { 8781 args.cleanUpResourcesLI(); 8782 } 8783 } else { 8784 // The application on /system is older than the application on /data. Hide 8785 // the application on /system and the version on /data will be scanned later 8786 // and re-added like an update. 8787 shouldHideSystemApp = true; 8788 logCriticalInfo(Log.INFO, 8789 "System package disabled;" 8790 + " name: " + pkgSetting.name 8791 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8792 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8793 } 8794 } 8795 8796 final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags 8797 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8798 8799 if (shouldHideSystemApp) { 8800 synchronized (mPackages) { 8801 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8802 } 8803 } 8804 return scannedPkg; 8805 } 8806 8807 private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8808 // Derive the new package synthetic package name 8809 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8810 + pkg.staticSharedLibVersion); 8811 } 8812 8813 private static String fixProcessName(String defProcessName, 8814 String processName) { 8815 if (processName == null) { 8816 return defProcessName; 8817 } 8818 return processName; 8819 } 8820 8821 /** 8822 * Enforces that only the system UID or root's UID can call a method exposed 8823 * via Binder. 8824 * 8825 * @param message used as message if SecurityException is thrown 8826 * @throws SecurityException if the caller is not system or root 8827 */ 8828 private static final void enforceSystemOrRoot(String message) { 8829 final int uid = Binder.getCallingUid(); 8830 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 8831 throw new SecurityException(message); 8832 } 8833 } 8834 8835 @Override 8836 public void performFstrimIfNeeded() { 8837 enforceSystemOrRoot("Only the system can request fstrim"); 8838 8839 // Before everything else, see whether we need to fstrim. 8840 try { 8841 IStorageManager sm = PackageHelper.getStorageManager(); 8842 if (sm != null) { 8843 boolean doTrim = false; 8844 final long interval = android.provider.Settings.Global.getLong( 8845 mContext.getContentResolver(), 8846 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8847 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8848 if (interval > 0) { 8849 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8850 if (timeSinceLast > interval) { 8851 doTrim = true; 8852 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8853 + "; running immediately"); 8854 } 8855 } 8856 if (doTrim) { 8857 final boolean dexOptDialogShown; 8858 synchronized (mPackages) { 8859 dexOptDialogShown = mDexOptDialogShown; 8860 } 8861 if (!isFirstBoot() && dexOptDialogShown) { 8862 try { 8863 ActivityManager.getService().showBootMessage( 8864 mContext.getResources().getString( 8865 R.string.android_upgrading_fstrim), true); 8866 } catch (RemoteException e) { 8867 } 8868 } 8869 sm.runMaintenance(); 8870 } 8871 } else { 8872 Slog.e(TAG, "storageManager service unavailable!"); 8873 } 8874 } catch (RemoteException e) { 8875 // Can't happen; StorageManagerService is local 8876 } 8877 } 8878 8879 @Override 8880 public void updatePackagesIfNeeded() { 8881 enforceSystemOrRoot("Only the system can request package update"); 8882 8883 // We need to re-extract after an OTA. 8884 boolean causeUpgrade = isUpgrade(); 8885 8886 // First boot or factory reset. 8887 // Note: we also handle devices that are upgrading to N right now as if it is their 8888 // first boot, as they do not have profile data. 8889 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8890 8891 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8892 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8893 8894 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8895 return; 8896 } 8897 8898 List<PackageParser.Package> pkgs; 8899 synchronized (mPackages) { 8900 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8901 } 8902 8903 final long startTime = System.nanoTime(); 8904 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8905 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 8906 false /* bootComplete */); 8907 8908 final int elapsedTimeSeconds = 8909 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8910 8911 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8912 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8913 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8914 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8915 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8916 } 8917 8918 /* 8919 * Return the prebuilt profile path given a package base code path. 8920 */ 8921 private static String getPrebuildProfilePath(PackageParser.Package pkg) { 8922 return pkg.baseCodePath + ".prof"; 8923 } 8924 8925 /** 8926 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8927 * containing statistics about the invocation. The array consists of three elements, 8928 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8929 * and {@code numberOfPackagesFailed}. 8930 */ 8931 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8932 final int compilationReason, boolean bootComplete) { 8933 8934 int numberOfPackagesVisited = 0; 8935 int numberOfPackagesOptimized = 0; 8936 int numberOfPackagesSkipped = 0; 8937 int numberOfPackagesFailed = 0; 8938 final int numberOfPackagesToDexopt = pkgs.size(); 8939 8940 for (PackageParser.Package pkg : pkgs) { 8941 numberOfPackagesVisited++; 8942 8943 boolean useProfileForDexopt = false; 8944 8945 if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) { 8946 // Copy over initial preopt profiles since we won't get any JIT samples for methods 8947 // that are already compiled. 8948 File profileFile = new File(getPrebuildProfilePath(pkg)); 8949 // Copy profile if it exists. 8950 if (profileFile.exists()) { 8951 try { 8952 // We could also do this lazily before calling dexopt in 8953 // PackageDexOptimizer to prevent this happening on first boot. The issue 8954 // is that we don't have a good way to say "do this only once". 8955 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8956 pkg.applicationInfo.uid, pkg.packageName, 8957 ArtManager.getProfileName(null))) { 8958 Log.e(TAG, "Installer failed to copy system profile!"); 8959 } else { 8960 // Disabled as this causes speed-profile compilation during first boot 8961 // even if things are already compiled. 8962 // useProfileForDexopt = true; 8963 } 8964 } catch (Exception e) { 8965 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", 8966 e); 8967 } 8968 } else { 8969 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8970 // Handle compressed APKs in this path. Only do this for stubs with profiles to 8971 // minimize the number off apps being speed-profile compiled during first boot. 8972 // The other paths will not change the filter. 8973 if (disabledPs != null && disabledPs.pkg.isStub) { 8974 // The package is the stub one, remove the stub suffix to get the normal 8975 // package and APK names. 8976 String systemProfilePath = 8977 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, ""); 8978 profileFile = new File(systemProfilePath); 8979 // If we have a profile for a compressed APK, copy it to the reference 8980 // location. 8981 // Note that copying the profile here will cause it to override the 8982 // reference profile every OTA even though the existing reference profile 8983 // may have more data. We can't copy during decompression since the 8984 // directories are not set up at that point. 8985 if (profileFile.exists()) { 8986 try { 8987 // We could also do this lazily before calling dexopt in 8988 // PackageDexOptimizer to prevent this happening on first boot. The 8989 // issue is that we don't have a good way to say "do this only 8990 // once". 8991 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8992 pkg.applicationInfo.uid, pkg.packageName, 8993 ArtManager.getProfileName(null))) { 8994 Log.e(TAG, "Failed to copy system profile for stub package!"); 8995 } else { 8996 useProfileForDexopt = true; 8997 } 8998 } catch (Exception e) { 8999 Log.e(TAG, "Failed to copy profile " + 9000 profileFile.getAbsolutePath() + " ", e); 9001 } 9002 } 9003 } 9004 } 9005 } 9006 9007 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 9008 if (DEBUG_DEXOPT) { 9009 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 9010 } 9011 numberOfPackagesSkipped++; 9012 continue; 9013 } 9014 9015 if (DEBUG_DEXOPT) { 9016 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 9017 numberOfPackagesToDexopt + ": " + pkg.packageName); 9018 } 9019 9020 if (showDialog) { 9021 try { 9022 ActivityManager.getService().showBootMessage( 9023 mContext.getResources().getString(R.string.android_upgrading_apk, 9024 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 9025 } catch (RemoteException e) { 9026 } 9027 synchronized (mPackages) { 9028 mDexOptDialogShown = true; 9029 } 9030 } 9031 9032 int pkgCompilationReason = compilationReason; 9033 if (useProfileForDexopt) { 9034 // Use background dexopt mode to try and use the profile. Note that this does not 9035 // guarantee usage of the profile. 9036 pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT; 9037 } 9038 9039 // checkProfiles is false to avoid merging profiles during boot which 9040 // might interfere with background compilation (b/28612421). 9041 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 9042 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 9043 // trade-off worth doing to save boot time work. 9044 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0; 9045 if (compilationReason == REASON_FIRST_BOOT) { 9046 // TODO: This doesn't cover the upgrade case, we should check for this too. 9047 dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE; 9048 } 9049 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions( 9050 pkg.packageName, 9051 pkgCompilationReason, 9052 dexoptFlags)); 9053 9054 switch (primaryDexOptStaus) { 9055 case PackageDexOptimizer.DEX_OPT_PERFORMED: 9056 numberOfPackagesOptimized++; 9057 break; 9058 case PackageDexOptimizer.DEX_OPT_SKIPPED: 9059 numberOfPackagesSkipped++; 9060 break; 9061 case PackageDexOptimizer.DEX_OPT_FAILED: 9062 numberOfPackagesFailed++; 9063 break; 9064 default: 9065 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus); 9066 break; 9067 } 9068 } 9069 9070 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 9071 numberOfPackagesFailed }; 9072 } 9073 9074 @Override 9075 public void notifyPackageUse(String packageName, int reason) { 9076 synchronized (mPackages) { 9077 final int callingUid = Binder.getCallingUid(); 9078 final int callingUserId = UserHandle.getUserId(callingUid); 9079 if (getInstantAppPackageName(callingUid) != null) { 9080 if (!isCallerSameApp(packageName, callingUid)) { 9081 return; 9082 } 9083 } else { 9084 if (isInstantApp(packageName, callingUserId)) { 9085 return; 9086 } 9087 } 9088 notifyPackageUseLocked(packageName, reason); 9089 } 9090 } 9091 9092 @GuardedBy("mPackages") 9093 private void notifyPackageUseLocked(String packageName, int reason) { 9094 final PackageParser.Package p = mPackages.get(packageName); 9095 if (p == null) { 9096 return; 9097 } 9098 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 9099 } 9100 9101 @Override 9102 public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames, 9103 List<String> classPaths, String loaderIsa) { 9104 int userId = UserHandle.getCallingUserId(); 9105 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 9106 if (ai == null) { 9107 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 9108 + loadingPackageName + ", user=" + userId); 9109 return; 9110 } 9111 mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId); 9112 } 9113 9114 @Override 9115 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule, 9116 IDexModuleRegisterCallback callback) { 9117 int userId = UserHandle.getCallingUserId(); 9118 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId); 9119 DexManager.RegisterDexModuleResult result; 9120 if (ai == null) { 9121 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" + 9122 " calling user. package=" + packageName + ", user=" + userId); 9123 result = new DexManager.RegisterDexModuleResult(false, "Package not installed"); 9124 } else { 9125 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId); 9126 } 9127 9128 if (callback != null) { 9129 mHandler.post(() -> { 9130 try { 9131 callback.onDexModuleRegistered(dexModulePath, result.success, result.message); 9132 } catch (RemoteException e) { 9133 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e); 9134 } 9135 }); 9136 } 9137 } 9138 9139 /** 9140 * Ask the package manager to perform a dex-opt with the given compiler filter. 9141 * 9142 * Note: exposed only for the shell command to allow moving packages explicitly to a 9143 * definite state. 9144 */ 9145 @Override 9146 public boolean performDexOptMode(String packageName, 9147 boolean checkProfiles, String targetCompilerFilter, boolean force, 9148 boolean bootComplete, String splitName) { 9149 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) | 9150 (force ? DexoptOptions.DEXOPT_FORCE : 0) | 9151 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0); 9152 return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN, 9153 targetCompilerFilter, splitName, flags)); 9154 } 9155 9156 /** 9157 * Ask the package manager to perform a dex-opt with the given compiler filter on the 9158 * secondary dex files belonging to the given package. 9159 * 9160 * Note: exposed only for the shell command to allow moving packages explicitly to a 9161 * definite state. 9162 */ 9163 @Override 9164 public boolean performDexOptSecondary(String packageName, String compilerFilter, 9165 boolean force) { 9166 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX | 9167 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES | 9168 DexoptOptions.DEXOPT_BOOT_COMPLETE | 9169 (force ? DexoptOptions.DEXOPT_FORCE : 0); 9170 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags)); 9171 } 9172 9173 /*package*/ boolean performDexOpt(DexoptOptions options) { 9174 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9175 return false; 9176 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) { 9177 return false; 9178 } 9179 9180 if (options.isDexoptOnlySecondaryDex()) { 9181 return mDexManager.dexoptSecondaryDex(options); 9182 } else { 9183 int dexoptStatus = performDexOptWithStatus(options); 9184 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9185 } 9186 } 9187 9188 /** 9189 * Perform dexopt on the given package and return one of following result: 9190 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9191 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9192 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9193 */ 9194 /* package */ int performDexOptWithStatus(DexoptOptions options) { 9195 return performDexOptTraced(options); 9196 } 9197 9198 private int performDexOptTraced(DexoptOptions options) { 9199 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9200 try { 9201 return performDexOptInternal(options); 9202 } finally { 9203 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9204 } 9205 } 9206 9207 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9208 // if the package can now be considered up to date for the given filter. 9209 private int performDexOptInternal(DexoptOptions options) { 9210 PackageParser.Package p; 9211 synchronized (mPackages) { 9212 p = mPackages.get(options.getPackageName()); 9213 if (p == null) { 9214 // Package could not be found. Report failure. 9215 return PackageDexOptimizer.DEX_OPT_FAILED; 9216 } 9217 mPackageUsage.maybeWriteAsync(mPackages); 9218 mCompilerStats.maybeWriteAsync(); 9219 } 9220 long callingId = Binder.clearCallingIdentity(); 9221 try { 9222 synchronized (mInstallLock) { 9223 return performDexOptInternalWithDependenciesLI(p, options); 9224 } 9225 } finally { 9226 Binder.restoreCallingIdentity(callingId); 9227 } 9228 } 9229 9230 public ArraySet<String> getOptimizablePackages() { 9231 ArraySet<String> pkgs = new ArraySet<String>(); 9232 synchronized (mPackages) { 9233 for (PackageParser.Package p : mPackages.values()) { 9234 if (PackageDexOptimizer.canOptimizePackage(p)) { 9235 pkgs.add(p.packageName); 9236 } 9237 } 9238 } 9239 return pkgs; 9240 } 9241 9242 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9243 DexoptOptions options) { 9244 // Select the dex optimizer based on the force parameter. 9245 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9246 // allocate an object here. 9247 PackageDexOptimizer pdo = options.isForce() 9248 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9249 : mPackageDexOptimizer; 9250 9251 // Dexopt all dependencies first. Note: we ignore the return value and march on 9252 // on errors. 9253 // Note that we are going to call performDexOpt on those libraries as many times as 9254 // they are referenced in packages. When we do a batch of performDexOpt (for example 9255 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9256 // and the first package that uses the library will dexopt it. The 9257 // others will see that the compiled code for the library is up to date. 9258 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 9259 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9260 if (!deps.isEmpty()) { 9261 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(), 9262 options.getCompilationReason(), options.getCompilerFilter(), 9263 options.getSplitName(), 9264 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY); 9265 for (PackageParser.Package depPackage : deps) { 9266 // TODO: Analyze and investigate if we (should) profile libraries. 9267 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 9268 getOrCreateCompilerPackageStats(depPackage), 9269 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions); 9270 } 9271 } 9272 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, 9273 getOrCreateCompilerPackageStats(p), 9274 mDexManager.getPackageUseInfoOrDefault(p.packageName), options); 9275 } 9276 9277 /** 9278 * Reconcile the information we have about the secondary dex files belonging to 9279 * {@code packagName} and the actual dex files. For all dex files that were 9280 * deleted, update the internal records and delete the generated oat files. 9281 */ 9282 @Override 9283 public void reconcileSecondaryDexFiles(String packageName) { 9284 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9285 return; 9286 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9287 return; 9288 } 9289 mDexManager.reconcileSecondaryDexFiles(packageName); 9290 } 9291 9292 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 9293 // a reference there. 9294 /*package*/ DexManager getDexManager() { 9295 return mDexManager; 9296 } 9297 9298 /** 9299 * Execute the background dexopt job immediately. 9300 */ 9301 @Override 9302 public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) { 9303 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9304 return false; 9305 } 9306 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames); 9307 } 9308 9309 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 9310 if (p.usesLibraries != null || p.usesOptionalLibraries != null 9311 || p.usesStaticLibraries != null) { 9312 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 9313 Set<String> collectedNames = new HashSet<>(); 9314 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 9315 9316 retValue.remove(p); 9317 9318 return retValue; 9319 } else { 9320 return Collections.emptyList(); 9321 } 9322 } 9323 9324 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 9325 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9326 if (!collectedNames.contains(p.packageName)) { 9327 collectedNames.add(p.packageName); 9328 collected.add(p); 9329 9330 if (p.usesLibraries != null) { 9331 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 9332 null, collected, collectedNames); 9333 } 9334 if (p.usesOptionalLibraries != null) { 9335 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 9336 null, collected, collectedNames); 9337 } 9338 if (p.usesStaticLibraries != null) { 9339 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 9340 p.usesStaticLibrariesVersions, collected, collectedNames); 9341 } 9342 } 9343 } 9344 9345 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions, 9346 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9347 final int libNameCount = libs.size(); 9348 for (int i = 0; i < libNameCount; i++) { 9349 String libName = libs.get(i); 9350 long version = (versions != null && versions.length == libNameCount) 9351 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 9352 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 9353 if (libPkg != null) { 9354 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 9355 } 9356 } 9357 } 9358 9359 private PackageParser.Package findSharedNonSystemLibrary(String name, long version) { 9360 synchronized (mPackages) { 9361 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 9362 if (libEntry != null) { 9363 return mPackages.get(libEntry.apk); 9364 } 9365 return null; 9366 } 9367 } 9368 9369 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) { 9370 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9371 if (versionedLib == null) { 9372 return null; 9373 } 9374 return versionedLib.get(version); 9375 } 9376 9377 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9378 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9379 pkg.staticSharedLibName); 9380 if (versionedLib == null) { 9381 return null; 9382 } 9383 long previousLibVersion = -1; 9384 final int versionCount = versionedLib.size(); 9385 for (int i = 0; i < versionCount; i++) { 9386 final long libVersion = versionedLib.keyAt(i); 9387 if (libVersion < pkg.staticSharedLibVersion) { 9388 previousLibVersion = Math.max(previousLibVersion, libVersion); 9389 } 9390 } 9391 if (previousLibVersion >= 0) { 9392 return versionedLib.get(previousLibVersion); 9393 } 9394 return null; 9395 } 9396 9397 public void shutdown() { 9398 mPackageUsage.writeNow(mPackages); 9399 mCompilerStats.writeNow(); 9400 mDexManager.writePackageDexUsageNow(); 9401 } 9402 9403 @Override 9404 public void dumpProfiles(String packageName) { 9405 PackageParser.Package pkg; 9406 synchronized (mPackages) { 9407 pkg = mPackages.get(packageName); 9408 if (pkg == null) { 9409 throw new IllegalArgumentException("Unknown package: " + packageName); 9410 } 9411 } 9412 /* Only the shell, root, or the app user should be able to dump profiles. */ 9413 int callingUid = Binder.getCallingUid(); 9414 if (callingUid != Process.SHELL_UID && 9415 callingUid != Process.ROOT_UID && 9416 callingUid != pkg.applicationInfo.uid) { 9417 throw new SecurityException("dumpProfiles"); 9418 } 9419 9420 synchronized (mInstallLock) { 9421 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9422 mArtManagerService.dumpProfiles(pkg); 9423 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9424 } 9425 } 9426 9427 @Override 9428 public void forceDexOpt(String packageName) { 9429 enforceSystemOrRoot("forceDexOpt"); 9430 9431 PackageParser.Package pkg; 9432 synchronized (mPackages) { 9433 pkg = mPackages.get(packageName); 9434 if (pkg == null) { 9435 throw new IllegalArgumentException("Unknown package: " + packageName); 9436 } 9437 } 9438 9439 synchronized (mInstallLock) { 9440 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9441 9442 // Whoever is calling forceDexOpt wants a compiled package. 9443 // Don't use profiles since that may cause compilation to be skipped. 9444 final int res = performDexOptInternalWithDependenciesLI( 9445 pkg, 9446 new DexoptOptions(packageName, 9447 getDefaultCompilerFilter(), 9448 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE)); 9449 9450 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9451 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9452 throw new IllegalStateException("Failed to dexopt: " + res); 9453 } 9454 } 9455 } 9456 9457 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9458 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9459 Slog.w(TAG, "Unable to update from " + oldPkg.name 9460 + " to " + newPkg.packageName 9461 + ": old package not in system partition"); 9462 return false; 9463 } else if (mPackages.get(oldPkg.name) != null) { 9464 Slog.w(TAG, "Unable to update from " + oldPkg.name 9465 + " to " + newPkg.packageName 9466 + ": old package still exists"); 9467 return false; 9468 } 9469 return true; 9470 } 9471 9472 void removeCodePathLI(File codePath) { 9473 if (codePath.isDirectory()) { 9474 try { 9475 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9476 } catch (InstallerException e) { 9477 Slog.w(TAG, "Failed to remove code path", e); 9478 } 9479 } else { 9480 codePath.delete(); 9481 } 9482 } 9483 9484 private int[] resolveUserIds(int userId) { 9485 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9486 } 9487 9488 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9489 if (pkg == null) { 9490 Slog.wtf(TAG, "Package was null!", new Throwable()); 9491 return; 9492 } 9493 clearAppDataLeafLIF(pkg, userId, flags); 9494 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9495 for (int i = 0; i < childCount; i++) { 9496 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9497 } 9498 9499 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 9500 } 9501 9502 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9503 final PackageSetting ps; 9504 synchronized (mPackages) { 9505 ps = mSettings.mPackages.get(pkg.packageName); 9506 } 9507 for (int realUserId : resolveUserIds(userId)) { 9508 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9509 try { 9510 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9511 ceDataInode); 9512 } catch (InstallerException e) { 9513 Slog.w(TAG, String.valueOf(e)); 9514 } 9515 } 9516 } 9517 9518 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9519 if (pkg == null) { 9520 Slog.wtf(TAG, "Package was null!", new Throwable()); 9521 return; 9522 } 9523 destroyAppDataLeafLIF(pkg, userId, flags); 9524 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9525 for (int i = 0; i < childCount; i++) { 9526 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9527 } 9528 } 9529 9530 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9531 final PackageSetting ps; 9532 synchronized (mPackages) { 9533 ps = mSettings.mPackages.get(pkg.packageName); 9534 } 9535 for (int realUserId : resolveUserIds(userId)) { 9536 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9537 try { 9538 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9539 ceDataInode); 9540 } catch (InstallerException e) { 9541 Slog.w(TAG, String.valueOf(e)); 9542 } 9543 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9544 } 9545 } 9546 9547 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9548 if (pkg == null) { 9549 Slog.wtf(TAG, "Package was null!", new Throwable()); 9550 return; 9551 } 9552 destroyAppProfilesLeafLIF(pkg); 9553 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9554 for (int i = 0; i < childCount; i++) { 9555 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9556 } 9557 } 9558 9559 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9560 try { 9561 mInstaller.destroyAppProfiles(pkg.packageName); 9562 } catch (InstallerException e) { 9563 Slog.w(TAG, String.valueOf(e)); 9564 } 9565 } 9566 9567 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9568 if (pkg == null) { 9569 Slog.wtf(TAG, "Package was null!", new Throwable()); 9570 return; 9571 } 9572 mArtManagerService.clearAppProfiles(pkg); 9573 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9574 for (int i = 0; i < childCount; i++) { 9575 mArtManagerService.clearAppProfiles(pkg.childPackages.get(i)); 9576 } 9577 } 9578 9579 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9580 long lastUpdateTime) { 9581 // Set parent install/update time 9582 PackageSetting ps = (PackageSetting) pkg.mExtras; 9583 if (ps != null) { 9584 ps.firstInstallTime = firstInstallTime; 9585 ps.lastUpdateTime = lastUpdateTime; 9586 } 9587 // Set children install/update time 9588 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9589 for (int i = 0; i < childCount; i++) { 9590 PackageParser.Package childPkg = pkg.childPackages.get(i); 9591 ps = (PackageSetting) childPkg.mExtras; 9592 if (ps != null) { 9593 ps.firstInstallTime = firstInstallTime; 9594 ps.lastUpdateTime = lastUpdateTime; 9595 } 9596 } 9597 } 9598 9599 private void addSharedLibraryLPr(Set<String> usesLibraryFiles, 9600 SharedLibraryEntry file, 9601 PackageParser.Package changingLib) { 9602 if (file.path != null) { 9603 usesLibraryFiles.add(file.path); 9604 return; 9605 } 9606 PackageParser.Package p = mPackages.get(file.apk); 9607 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9608 // If we are doing this while in the middle of updating a library apk, 9609 // then we need to make sure to use that new apk for determining the 9610 // dependencies here. (We haven't yet finished committing the new apk 9611 // to the package manager state.) 9612 if (p == null || p.packageName.equals(changingLib.packageName)) { 9613 p = changingLib; 9614 } 9615 } 9616 if (p != null) { 9617 usesLibraryFiles.addAll(p.getAllCodePaths()); 9618 if (p.usesLibraryFiles != null) { 9619 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 9620 } 9621 } 9622 } 9623 9624 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9625 PackageParser.Package changingLib) throws PackageManagerException { 9626 if (pkg == null) { 9627 return; 9628 } 9629 // The collection used here must maintain the order of addition (so 9630 // that libraries are searched in the correct order) and must have no 9631 // duplicates. 9632 Set<String> usesLibraryFiles = null; 9633 if (pkg.usesLibraries != null) { 9634 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9635 null, null, pkg.packageName, changingLib, true, 9636 pkg.applicationInfo.targetSdkVersion, null); 9637 } 9638 if (pkg.usesStaticLibraries != null) { 9639 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9640 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9641 pkg.packageName, changingLib, true, 9642 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9643 } 9644 if (pkg.usesOptionalLibraries != null) { 9645 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9646 null, null, pkg.packageName, changingLib, false, 9647 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9648 } 9649 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9650 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9651 } else { 9652 pkg.usesLibraryFiles = null; 9653 } 9654 } 9655 9656 private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9657 @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests, 9658 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9659 boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries) 9660 throws PackageManagerException { 9661 final int libCount = requestedLibraries.size(); 9662 for (int i = 0; i < libCount; i++) { 9663 final String libName = requestedLibraries.get(i); 9664 final long libVersion = requiredVersions != null ? requiredVersions[i] 9665 : SharedLibraryInfo.VERSION_UNDEFINED; 9666 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9667 if (libEntry == null) { 9668 if (required) { 9669 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9670 "Package " + packageName + " requires unavailable shared library " 9671 + libName + "; failing!"); 9672 } else if (DEBUG_SHARED_LIBRARIES) { 9673 Slog.i(TAG, "Package " + packageName 9674 + " desires unavailable shared library " 9675 + libName + "; ignoring!"); 9676 } 9677 } else { 9678 if (requiredVersions != null && requiredCertDigests != null) { 9679 if (libEntry.info.getLongVersion() != requiredVersions[i]) { 9680 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9681 "Package " + packageName + " requires unavailable static shared" 9682 + " library " + libName + " version " 9683 + libEntry.info.getLongVersion() + "; failing!"); 9684 } 9685 9686 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9687 if (libPkg == null) { 9688 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9689 "Package " + packageName + " requires unavailable static shared" 9690 + " library; failing!"); 9691 } 9692 9693 final String[] expectedCertDigests = requiredCertDigests[i]; 9694 9695 9696 if (expectedCertDigests.length > 1) { 9697 9698 // For apps targeting O MR1 we require explicit enumeration of all certs. 9699 final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O) 9700 ? PackageUtils.computeSignaturesSha256Digests( 9701 libPkg.mSigningDetails.signatures) 9702 : PackageUtils.computeSignaturesSha256Digests( 9703 new Signature[]{libPkg.mSigningDetails.signatures[0]}); 9704 9705 // Take a shortcut if sizes don't match. Note that if an app doesn't 9706 // target O we don't parse the "additional-certificate" tags similarly 9707 // how we only consider all certs only for apps targeting O (see above). 9708 // Therefore, the size check is safe to make. 9709 if (expectedCertDigests.length != libCertDigests.length) { 9710 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9711 "Package " + packageName + " requires differently signed" + 9712 " static shared library; failing!"); 9713 } 9714 9715 // Use a predictable order as signature order may vary 9716 Arrays.sort(libCertDigests); 9717 Arrays.sort(expectedCertDigests); 9718 9719 final int certCount = libCertDigests.length; 9720 for (int j = 0; j < certCount; j++) { 9721 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) { 9722 throw new PackageManagerException( 9723 INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9724 "Package " + packageName + " requires differently signed" + 9725 " static shared library; failing!"); 9726 } 9727 } 9728 } else { 9729 9730 // lib signing cert could have rotated beyond the one expected, check to see 9731 // if the new one has been blessed by the old 9732 if (!libPkg.mSigningDetails.hasSha256Certificate( 9733 ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) { 9734 throw new PackageManagerException( 9735 INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9736 "Package " + packageName + " requires differently signed" + 9737 " static shared library; failing!"); 9738 } 9739 } 9740 } 9741 9742 if (outUsedLibraries == null) { 9743 // Use LinkedHashSet to preserve the order of files added to 9744 // usesLibraryFiles while eliminating duplicates. 9745 outUsedLibraries = new LinkedHashSet<>(); 9746 } 9747 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9748 } 9749 } 9750 return outUsedLibraries; 9751 } 9752 9753 private static boolean hasString(List<String> list, List<String> which) { 9754 if (list == null) { 9755 return false; 9756 } 9757 for (int i=list.size()-1; i>=0; i--) { 9758 for (int j=which.size()-1; j>=0; j--) { 9759 if (which.get(j).equals(list.get(i))) { 9760 return true; 9761 } 9762 } 9763 } 9764 return false; 9765 } 9766 9767 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9768 PackageParser.Package changingPkg) { 9769 ArrayList<PackageParser.Package> res = null; 9770 for (PackageParser.Package pkg : mPackages.values()) { 9771 if (changingPkg != null 9772 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9773 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9774 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9775 changingPkg.staticSharedLibName)) { 9776 return null; 9777 } 9778 if (res == null) { 9779 res = new ArrayList<>(); 9780 } 9781 res.add(pkg); 9782 try { 9783 updateSharedLibrariesLPr(pkg, changingPkg); 9784 } catch (PackageManagerException e) { 9785 // If a system app update or an app and a required lib missing we 9786 // delete the package and for updated system apps keep the data as 9787 // it is better for the user to reinstall than to be in an limbo 9788 // state. Also libs disappearing under an app should never happen 9789 // - just in case. 9790 if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) { 9791 final int flags = pkg.isUpdatedSystemApp() 9792 ? PackageManager.DELETE_KEEP_DATA : 0; 9793 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9794 flags , null, true, null); 9795 } 9796 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9797 } 9798 } 9799 return res; 9800 } 9801 9802 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9803 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9804 @Nullable UserHandle user) throws PackageManagerException { 9805 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9806 // If the package has children and this is the first dive in the function 9807 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9808 // whether all packages (parent and children) would be successfully scanned 9809 // before the actual scan since scanning mutates internal state and we want 9810 // to atomically install the package and its children. 9811 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9812 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9813 scanFlags |= SCAN_CHECK_ONLY; 9814 } 9815 } else { 9816 scanFlags &= ~SCAN_CHECK_ONLY; 9817 } 9818 9819 final PackageParser.Package scannedPkg; 9820 try { 9821 // Scan the parent 9822 scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user); 9823 // Scan the children 9824 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9825 for (int i = 0; i < childCount; i++) { 9826 PackageParser.Package childPkg = pkg.childPackages.get(i); 9827 scanPackageNewLI(childPkg, parseFlags, 9828 scanFlags, currentTime, user); 9829 } 9830 } finally { 9831 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9832 } 9833 9834 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9835 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 9836 } 9837 9838 return scannedPkg; 9839 } 9840 9841 /** The result of a package scan. */ 9842 private static class ScanResult { 9843 /** Whether or not the package scan was successful */ 9844 public final boolean success; 9845 /** 9846 * The final package settings. This may be the same object passed in 9847 * the {@link ScanRequest}, but, with modified values. 9848 */ 9849 @Nullable public final PackageSetting pkgSetting; 9850 /** ABI code paths that have changed in the package scan */ 9851 @Nullable public final List<String> changedAbiCodePath; 9852 public ScanResult( 9853 boolean success, 9854 @Nullable PackageSetting pkgSetting, 9855 @Nullable List<String> changedAbiCodePath) { 9856 this.success = success; 9857 this.pkgSetting = pkgSetting; 9858 this.changedAbiCodePath = changedAbiCodePath; 9859 } 9860 } 9861 9862 /** A package to be scanned */ 9863 private static class ScanRequest { 9864 /** The parsed package */ 9865 @NonNull public final PackageParser.Package pkg; 9866 /** Shared user settings, if the package has a shared user */ 9867 @Nullable public final SharedUserSetting sharedUserSetting; 9868 /** 9869 * Package settings of the currently installed version. 9870 * <p><em>IMPORTANT:</em> The contents of this object may be modified 9871 * during scan. 9872 */ 9873 @Nullable public final PackageSetting pkgSetting; 9874 /** A copy of the settings for the currently installed version */ 9875 @Nullable public final PackageSetting oldPkgSetting; 9876 /** Package settings for the disabled version on the /system partition */ 9877 @Nullable public final PackageSetting disabledPkgSetting; 9878 /** Package settings for the installed version under its original package name */ 9879 @Nullable public final PackageSetting originalPkgSetting; 9880 /** The real package name of a renamed application */ 9881 @Nullable public final String realPkgName; 9882 public final @ParseFlags int parseFlags; 9883 public final @ScanFlags int scanFlags; 9884 /** The user for which the package is being scanned */ 9885 @Nullable public final UserHandle user; 9886 /** Whether or not the platform package is being scanned */ 9887 public final boolean isPlatformPackage; 9888 public ScanRequest( 9889 @NonNull PackageParser.Package pkg, 9890 @Nullable SharedUserSetting sharedUserSetting, 9891 @Nullable PackageSetting pkgSetting, 9892 @Nullable PackageSetting disabledPkgSetting, 9893 @Nullable PackageSetting originalPkgSetting, 9894 @Nullable String realPkgName, 9895 @ParseFlags int parseFlags, 9896 @ScanFlags int scanFlags, 9897 boolean isPlatformPackage, 9898 @Nullable UserHandle user) { 9899 this.pkg = pkg; 9900 this.pkgSetting = pkgSetting; 9901 this.sharedUserSetting = sharedUserSetting; 9902 this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting); 9903 this.disabledPkgSetting = disabledPkgSetting; 9904 this.originalPkgSetting = originalPkgSetting; 9905 this.realPkgName = realPkgName; 9906 this.parseFlags = parseFlags; 9907 this.scanFlags = scanFlags; 9908 this.isPlatformPackage = isPlatformPackage; 9909 this.user = user; 9910 } 9911 } 9912 9913 /** 9914 * Returns the actual scan flags depending upon the state of the other settings. 9915 * <p>Updated system applications will not have the following flags set 9916 * by default and need to be adjusted after the fact: 9917 * <ul> 9918 * <li>{@link #SCAN_AS_SYSTEM}</li> 9919 * <li>{@link #SCAN_AS_PRIVILEGED}</li> 9920 * <li>{@link #SCAN_AS_OEM}</li> 9921 * <li>{@link #SCAN_AS_VENDOR}</li> 9922 * <li>{@link #SCAN_AS_PRODUCT}</li> 9923 * <li>{@link #SCAN_AS_INSTANT_APP}</li> 9924 * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li> 9925 * </ul> 9926 */ 9927 private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags, 9928 PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user, 9929 PackageParser.Package pkg) { 9930 if (disabledPkgSetting != null) { 9931 // updated system application, must at least have SCAN_AS_SYSTEM 9932 scanFlags |= SCAN_AS_SYSTEM; 9933 if ((disabledPkgSetting.pkgPrivateFlags 9934 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 9935 scanFlags |= SCAN_AS_PRIVILEGED; 9936 } 9937 if ((disabledPkgSetting.pkgPrivateFlags 9938 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) { 9939 scanFlags |= SCAN_AS_OEM; 9940 } 9941 if ((disabledPkgSetting.pkgPrivateFlags 9942 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) { 9943 scanFlags |= SCAN_AS_VENDOR; 9944 } 9945 if ((disabledPkgSetting.pkgPrivateFlags 9946 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) { 9947 scanFlags |= SCAN_AS_PRODUCT; 9948 } 9949 } 9950 if (pkgSetting != null) { 9951 final int userId = ((user == null) ? 0 : user.getIdentifier()); 9952 if (pkgSetting.getInstantApp(userId)) { 9953 scanFlags |= SCAN_AS_INSTANT_APP; 9954 } 9955 if (pkgSetting.getVirtulalPreload(userId)) { 9956 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 9957 } 9958 } 9959 9960 // Scan as privileged apps that share a user with a priv-app. 9961 if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged() 9962 && (pkg.mSharedUserId != null)) { 9963 SharedUserSetting sharedUserSetting = null; 9964 try { 9965 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 9966 } catch (PackageManagerException ignore) {} 9967 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 9968 // Exempt SharedUsers signed with the platform key. 9969 // TODO(b/72378145) Fix this exemption. Force signature apps 9970 // to whitelist their privileged permissions just like other 9971 // priv-apps. 9972 synchronized (mPackages) { 9973 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 9974 if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures, 9975 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) { 9976 scanFlags |= SCAN_AS_PRIVILEGED; 9977 } 9978 } 9979 } 9980 } 9981 9982 return scanFlags; 9983 } 9984 9985 // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting 9986 // the results / removing app data needs to be moved up a level to the callers of this 9987 // method. Also, we need to solve the problem of potentially creating a new shared user 9988 // setting. That can probably be done later and patch things up after the fact. 9989 @GuardedBy("mInstallLock") 9990 private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg, 9991 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9992 @Nullable UserHandle user) throws PackageManagerException { 9993 9994 final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9995 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 9996 if (realPkgName != null) { 9997 ensurePackageRenamed(pkg, renamedPkgName); 9998 } 9999 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 10000 final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName); 10001 final PackageSetting disabledPkgSetting = 10002 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 10003 10004 if (mTransferedPackages.contains(pkg.packageName)) { 10005 Slog.w(TAG, "Package " + pkg.packageName 10006 + " was transferred to another, but its .apk remains"); 10007 } 10008 10009 scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg); 10010 synchronized (mPackages) { 10011 applyPolicy(pkg, parseFlags, scanFlags); 10012 assertPackageIsValid(pkg, parseFlags, scanFlags); 10013 10014 SharedUserSetting sharedUserSetting = null; 10015 if (pkg.mSharedUserId != null) { 10016 // SIDE EFFECTS; may potentially allocate a new shared user 10017 sharedUserSetting = mSettings.getSharedUserLPw( 10018 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 10019 if (DEBUG_PACKAGE_SCANNING) { 10020 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10021 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 10022 + " (uid=" + sharedUserSetting.userId + "):" 10023 + " packages=" + sharedUserSetting.packages); 10024 } 10025 } 10026 10027 boolean scanSucceeded = false; 10028 try { 10029 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting, 10030 disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags, 10031 (pkg == mPlatformPackage), user); 10032 final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime); 10033 if (result.success) { 10034 commitScanResultsLocked(request, result); 10035 } 10036 scanSucceeded = true; 10037 } finally { 10038 if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 10039 // DELETE_DATA_ON_FAILURES is only used by frozen paths 10040 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 10041 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 10042 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 10043 } 10044 } 10045 } 10046 return pkg; 10047 } 10048 10049 /** 10050 * Commits the package scan and modifies system state. 10051 * <p><em>WARNING:</em> The method may throw an excpetion in the middle 10052 * of committing the package, leaving the system in an inconsistent state. 10053 * This needs to be fixed so, once we get to this point, no errors are 10054 * possible and the system is not left in an inconsistent state. 10055 */ 10056 @GuardedBy("mPackages") 10057 private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result) 10058 throws PackageManagerException { 10059 final PackageParser.Package pkg = request.pkg; 10060 final @ParseFlags int parseFlags = request.parseFlags; 10061 final @ScanFlags int scanFlags = request.scanFlags; 10062 final PackageSetting oldPkgSetting = request.oldPkgSetting; 10063 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10064 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10065 final UserHandle user = request.user; 10066 final String realPkgName = request.realPkgName; 10067 final PackageSetting pkgSetting = result.pkgSetting; 10068 final List<String> changedAbiCodePath = result.changedAbiCodePath; 10069 final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting); 10070 10071 if (newPkgSettingCreated) { 10072 if (originalPkgSetting != null) { 10073 mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name); 10074 } 10075 // THROWS: when we can't allocate a user id. add call to check if there's 10076 // enough space to ensure we won't throw; otherwise, don't modify state 10077 mSettings.addUserToSettingLPw(pkgSetting); 10078 10079 if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) { 10080 mTransferedPackages.add(originalPkgSetting.name); 10081 } 10082 } 10083 // TODO(toddke): Consider a method specifically for modifying the Package object 10084 // post scan; or, moving this stuff out of the Package object since it has nothing 10085 // to do with the package on disk. 10086 // We need to have this here because addUserToSettingLPw() is sometimes responsible 10087 // for creating the application ID. If we did this earlier, we would be saving the 10088 // correct ID. 10089 pkg.applicationInfo.uid = pkgSetting.appId; 10090 10091 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 10092 10093 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) { 10094 mTransferedPackages.add(pkg.packageName); 10095 } 10096 10097 // THROWS: when requested libraries that can't be found. it only changes 10098 // the state of the passed in pkg object, so, move to the top of the method 10099 // and allow it to abort 10100 if ((scanFlags & SCAN_BOOTING) == 0 10101 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10102 // Check all shared libraries and map to their actual file path. 10103 // We only do this here for apps not on a system dir, because those 10104 // are the only ones that can fail an install due to this. We 10105 // will take care of the system apps by updating all of their 10106 // library paths after the scan is done. Also during the initial 10107 // scan don't update any libs as we do this wholesale after all 10108 // apps are scanned to avoid dependency based scanning. 10109 updateSharedLibrariesLPr(pkg, null); 10110 } 10111 10112 // All versions of a static shared library are referenced with the same 10113 // package name. Internally, we use a synthetic package name to allow 10114 // multiple versions of the same shared library to be installed. So, 10115 // we need to generate the synthetic package name of the latest shared 10116 // library in order to compare signatures. 10117 PackageSetting signatureCheckPs = pkgSetting; 10118 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10119 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 10120 if (libraryEntry != null) { 10121 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 10122 } 10123 } 10124 10125 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10126 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 10127 if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 10128 // We just determined the app is signed correctly, so bring 10129 // over the latest parsed certs. 10130 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10131 } else { 10132 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10133 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10134 "Package " + pkg.packageName + " upgrade keys do not match the " 10135 + "previously installed version"); 10136 } else { 10137 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10138 String msg = "System package " + pkg.packageName 10139 + " signature changed; retaining data."; 10140 reportSettingsProblem(Log.WARN, msg); 10141 } 10142 } 10143 } else { 10144 try { 10145 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 10146 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 10147 final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting, 10148 pkg.mSigningDetails, compareCompat, compareRecover); 10149 // The new KeySets will be re-added later in the scanning process. 10150 if (compatMatch) { 10151 synchronized (mPackages) { 10152 ksms.removeAppKeySetDataLPw(pkg.packageName); 10153 } 10154 } 10155 // We just determined the app is signed correctly, so bring 10156 // over the latest parsed certs. 10157 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10158 10159 10160 // if this is is a sharedUser, check to see if the new package is signed by a newer 10161 // signing certificate than the existing one, and if so, copy over the new details 10162 if (signatureCheckPs.sharedUser != null 10163 && pkg.mSigningDetails.hasAncestor( 10164 signatureCheckPs.sharedUser.signatures.mSigningDetails)) { 10165 signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails; 10166 } 10167 } catch (PackageManagerException e) { 10168 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10169 throw e; 10170 } 10171 // The signature has changed, but this package is in the system 10172 // image... let's recover! 10173 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10174 // However... if this package is part of a shared user, but it 10175 // doesn't match the signature of the shared user, let's fail. 10176 // What this means is that you can't change the signatures 10177 // associated with an overall shared user, which doesn't seem all 10178 // that unreasonable. 10179 if (signatureCheckPs.sharedUser != null) { 10180 if (compareSignatures( 10181 signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures, 10182 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) { 10183 throw new PackageManagerException( 10184 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10185 "Signature mismatch for shared user: " 10186 + pkgSetting.sharedUser); 10187 } 10188 } 10189 // File a report about this. 10190 String msg = "System package " + pkg.packageName 10191 + " signature changed; retaining data."; 10192 reportSettingsProblem(Log.WARN, msg); 10193 } catch (IllegalArgumentException e) { 10194 10195 // should never happen: certs matched when checking, but not when comparing 10196 // old to new for sharedUser 10197 throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10198 "Signing certificates comparison made on incomparable signing details" 10199 + " but somehow passed verifySignatures!"); 10200 } 10201 } 10202 10203 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 10204 // This package wants to adopt ownership of permissions from 10205 // another package. 10206 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 10207 final String origName = pkg.mAdoptPermissions.get(i); 10208 final PackageSetting orig = mSettings.getPackageLPr(origName); 10209 if (orig != null) { 10210 if (verifyPackageUpdateLPr(orig, pkg)) { 10211 Slog.i(TAG, "Adopting permissions from " + origName + " to " 10212 + pkg.packageName); 10213 mSettings.mPermissions.transferPermissions(origName, pkg.packageName); 10214 } 10215 } 10216 } 10217 } 10218 10219 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 10220 for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) { 10221 final String codePathString = changedAbiCodePath.get(i); 10222 try { 10223 mInstaller.rmdex(codePathString, 10224 getDexCodeInstructionSet(getPreferredInstructionSet())); 10225 } catch (InstallerException ignored) { 10226 } 10227 } 10228 } 10229 10230 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10231 if (oldPkgSetting != null) { 10232 synchronized (mPackages) { 10233 mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting); 10234 } 10235 } 10236 } else { 10237 final int userId = user == null ? 0 : user.getIdentifier(); 10238 // Modify state for the given package setting 10239 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 10240 (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 10241 if (pkgSetting.getInstantApp(userId)) { 10242 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 10243 } 10244 } 10245 } 10246 10247 /** 10248 * Returns the "real" name of the package. 10249 * <p>This may differ from the package's actual name if the application has already 10250 * been installed under one of this package's original names. 10251 */ 10252 private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg, 10253 @Nullable String renamedPkgName) { 10254 if (isPackageRenamed(pkg, renamedPkgName)) { 10255 return pkg.mRealPackage; 10256 } 10257 return null; 10258 } 10259 10260 /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */ 10261 private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg, 10262 @Nullable String renamedPkgName) { 10263 return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName); 10264 } 10265 10266 /** 10267 * Returns the original package setting. 10268 * <p>A package can migrate its name during an update. In this scenario, a package 10269 * designates a set of names that it considers as one of its original names. 10270 * <p>An original package must be signed identically and it must have the same 10271 * shared user [if any]. 10272 */ 10273 @GuardedBy("mPackages") 10274 private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg, 10275 @Nullable String renamedPkgName) { 10276 if (!isPackageRenamed(pkg, renamedPkgName)) { 10277 return null; 10278 } 10279 for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) { 10280 final PackageSetting originalPs = 10281 mSettings.getPackageLPr(pkg.mOriginalPackages.get(i)); 10282 if (originalPs != null) { 10283 // the package is already installed under its original name... 10284 // but, should we use it? 10285 if (!verifyPackageUpdateLPr(originalPs, pkg)) { 10286 // the new package is incompatible with the original 10287 continue; 10288 } else if (originalPs.sharedUser != null) { 10289 if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) { 10290 // the shared user id is incompatible with the original 10291 Slog.w(TAG, "Unable to migrate data from " + originalPs.name 10292 + " to " + pkg.packageName + ": old uid " 10293 + originalPs.sharedUser.name 10294 + " differs from " + pkg.mSharedUserId); 10295 continue; 10296 } 10297 // TODO: Add case when shared user id is added [b/28144775] 10298 } else { 10299 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 10300 + pkg.packageName + " to old name " + originalPs.name); 10301 } 10302 return originalPs; 10303 } 10304 } 10305 return null; 10306 } 10307 10308 /** 10309 * Renames the package if it was installed under a different name. 10310 * <p>When we've already installed the package under an original name, update 10311 * the new package so we can continue to have the old name. 10312 */ 10313 private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg, 10314 @NonNull String renamedPackageName) { 10315 if (pkg.mOriginalPackages == null 10316 || !pkg.mOriginalPackages.contains(renamedPackageName) 10317 || pkg.packageName.equals(renamedPackageName)) { 10318 return; 10319 } 10320 pkg.setPackageName(renamedPackageName); 10321 } 10322 10323 /** 10324 * Just scans the package without any side effects. 10325 * <p>Not entirely true at the moment. There is still one side effect -- this 10326 * method potentially modifies a live {@link PackageSetting} object representing 10327 * the package being scanned. This will be resolved in the future. 10328 * 10329 * @param request Information about the package to be scanned 10330 * @param isUnderFactoryTest Whether or not the device is under factory test 10331 * @param currentTime The current time, in millis 10332 * @return The results of the scan 10333 */ 10334 @GuardedBy("mInstallLock") 10335 private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request, 10336 boolean isUnderFactoryTest, long currentTime) 10337 throws PackageManagerException { 10338 final PackageParser.Package pkg = request.pkg; 10339 PackageSetting pkgSetting = request.pkgSetting; 10340 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10341 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10342 final @ParseFlags int parseFlags = request.parseFlags; 10343 final @ScanFlags int scanFlags = request.scanFlags; 10344 final String realPkgName = request.realPkgName; 10345 final SharedUserSetting sharedUserSetting = request.sharedUserSetting; 10346 final UserHandle user = request.user; 10347 final boolean isPlatformPackage = request.isPlatformPackage; 10348 10349 List<String> changedAbiCodePath = null; 10350 10351 if (DEBUG_PACKAGE_SCANNING) { 10352 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10353 Log.d(TAG, "Scanning package " + pkg.packageName); 10354 } 10355 10356 if (Build.IS_DEBUGGABLE && 10357 pkg.isPrivileged() && 10358 SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) { 10359 PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg); 10360 } 10361 10362 // Initialize package source and resource directories 10363 final File scanFile = new File(pkg.codePath); 10364 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 10365 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 10366 10367 // We keep references to the derived CPU Abis from settings in oder to reuse 10368 // them in the case where we're not upgrading or booting for the first time. 10369 String primaryCpuAbiFromSettings = null; 10370 String secondaryCpuAbiFromSettings = null; 10371 boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0; 10372 10373 if (!needToDeriveAbi) { 10374 if (pkgSetting != null) { 10375 primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString; 10376 secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString; 10377 } else { 10378 // Re-scanning a system package after uninstalling updates; need to derive ABI 10379 needToDeriveAbi = true; 10380 } 10381 } 10382 10383 if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) { 10384 PackageManagerService.reportSettingsProblem(Log.WARN, 10385 "Package " + pkg.packageName + " shared user changed from " 10386 + (pkgSetting.sharedUser != null 10387 ? pkgSetting.sharedUser.name : "<nothing>") 10388 + " to " 10389 + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>") 10390 + "; replacing with new"); 10391 pkgSetting = null; 10392 } 10393 10394 String[] usesStaticLibraries = null; 10395 if (pkg.usesStaticLibraries != null) { 10396 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 10397 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 10398 } 10399 final boolean createNewPackage = (pkgSetting == null); 10400 if (createNewPackage) { 10401 final String parentPackageName = (pkg.parentPackage != null) 10402 ? pkg.parentPackage.packageName : null; 10403 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10404 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0; 10405 // REMOVE SharedUserSetting from method; update in a separate call 10406 pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting, 10407 disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile, 10408 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 10409 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10410 pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10411 user, true /*allowInstall*/, instantApp, virtualPreload, 10412 parentPackageName, pkg.getChildPackageNames(), 10413 UserManagerService.getInstance(), usesStaticLibraries, 10414 pkg.usesStaticLibrariesVersions); 10415 } else { 10416 // REMOVE SharedUserSetting from method; update in a separate call. 10417 // 10418 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 10419 // secondaryCpuAbi are not known at this point so we always update them 10420 // to null here, only to reset them at a later point. 10421 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting, 10422 destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir, 10423 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10424 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10425 pkg.getChildPackageNames(), UserManagerService.getInstance(), 10426 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 10427 } 10428 if (createNewPackage && originalPkgSetting != null) { 10429 // This is the initial transition from the original package, so, 10430 // fix up the new package's name now. We must do this after looking 10431 // up the package under its new name, so getPackageLP takes care of 10432 // fiddling things correctly. 10433 pkg.setPackageName(originalPkgSetting.name); 10434 10435 // File a report about this. 10436 String msg = "New package " + pkgSetting.realName 10437 + " renamed to replace old package " + pkgSetting.name; 10438 reportSettingsProblem(Log.WARN, msg); 10439 } 10440 10441 if (disabledPkgSetting != null) { 10442 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10443 } 10444 10445 // Apps which share a sharedUserId must be placed in the same selinux domain. If this 10446 // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its 10447 // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be 10448 // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the 10449 // least restrictive selinux domain. 10450 // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion 10451 // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This 10452 // ensures that all packages continue to run in the same selinux domain. 10453 final int targetSdkVersion = 10454 ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ? 10455 sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion; 10456 // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync. 10457 // They currently can be if the sharedUser apps are signed with the platform key. 10458 final boolean isPrivileged = (sharedUserSetting != null) ? 10459 sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged(); 10460 10461 pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged, 10462 pkg.applicationInfo.targetSandboxVersion, targetSdkVersion); 10463 10464 pkg.mExtras = pkgSetting; 10465 pkg.applicationInfo.processName = fixProcessName( 10466 pkg.applicationInfo.packageName, 10467 pkg.applicationInfo.processName); 10468 10469 if (!isPlatformPackage) { 10470 // Get all of our default paths setup 10471 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 10472 } 10473 10474 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 10475 10476 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 10477 if (needToDeriveAbi) { 10478 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 10479 final boolean extractNativeLibs = !pkg.isLibrary(); 10480 derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs); 10481 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10482 10483 // Some system apps still use directory structure for native libraries 10484 // in which case we might end up not detecting abi solely based on apk 10485 // structure. Try to detect abi based on directory structure. 10486 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 10487 pkg.applicationInfo.primaryCpuAbi == null) { 10488 setBundledAppAbisAndRoots(pkg, pkgSetting); 10489 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10490 } 10491 } else { 10492 // This is not a first boot or an upgrade, don't bother deriving the 10493 // ABI during the scan. Instead, trust the value that was stored in the 10494 // package setting. 10495 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 10496 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 10497 10498 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10499 10500 if (DEBUG_ABI_SELECTION) { 10501 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 10502 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 10503 pkg.applicationInfo.secondaryCpuAbi); 10504 } 10505 } 10506 } else { 10507 if ((scanFlags & SCAN_MOVE) != 0) { 10508 // We haven't run dex-opt for this move (since we've moved the compiled output too) 10509 // but we already have this packages package info in the PackageSetting. We just 10510 // use that and derive the native library path based on the new codepath. 10511 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 10512 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 10513 } 10514 10515 // Set native library paths again. For moves, the path will be updated based on the 10516 // ABIs we've determined above. For non-moves, the path will be updated based on the 10517 // ABIs we determined during compilation, but the path will depend on the final 10518 // package path (after the rename away from the stage path). 10519 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10520 } 10521 10522 // This is a special case for the "system" package, where the ABI is 10523 // dictated by the zygote configuration (and init.rc). We should keep track 10524 // of this ABI so that we can deal with "normal" applications that run under 10525 // the same UID correctly. 10526 if (isPlatformPackage) { 10527 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 10528 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 10529 } 10530 10531 // If there's a mismatch between the abi-override in the package setting 10532 // and the abiOverride specified for the install. Warn about this because we 10533 // would've already compiled the app without taking the package setting into 10534 // account. 10535 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 10536 if (cpuAbiOverride == null && pkg.packageName != null) { 10537 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 10538 " for package " + pkg.packageName); 10539 } 10540 } 10541 10542 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10543 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10544 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 10545 10546 // Copy the derived override back to the parsed package, so that we can 10547 // update the package settings accordingly. 10548 pkg.cpuAbiOverride = cpuAbiOverride; 10549 10550 if (DEBUG_ABI_SELECTION) { 10551 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName 10552 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 10553 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 10554 } 10555 10556 // Push the derived path down into PackageSettings so we know what to 10557 // clean up at uninstall time. 10558 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 10559 10560 if (DEBUG_ABI_SELECTION) { 10561 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 10562 " primary=" + pkg.applicationInfo.primaryCpuAbi + 10563 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 10564 } 10565 10566 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 10567 // We don't do this here during boot because we can do it all 10568 // at once after scanning all existing packages. 10569 // 10570 // We also do this *before* we perform dexopt on this package, so that 10571 // we can avoid redundant dexopts, and also to make sure we've got the 10572 // code and package path correct. 10573 changedAbiCodePath = 10574 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 10575 } 10576 10577 if (isUnderFactoryTest && pkg.requestedPermissions.contains( 10578 android.Manifest.permission.FACTORY_TEST)) { 10579 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 10580 } 10581 10582 if (isSystemApp(pkg)) { 10583 pkgSetting.isOrphaned = true; 10584 } 10585 10586 // Take care of first install / last update times. 10587 final long scanFileTime = getLastModifiedTime(pkg); 10588 if (currentTime != 0) { 10589 if (pkgSetting.firstInstallTime == 0) { 10590 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 10591 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 10592 pkgSetting.lastUpdateTime = currentTime; 10593 } 10594 } else if (pkgSetting.firstInstallTime == 0) { 10595 // We need *something*. Take time time stamp of the file. 10596 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 10597 } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 10598 if (scanFileTime != pkgSetting.timeStamp) { 10599 // A package on the system image has changed; consider this 10600 // to be an update. 10601 pkgSetting.lastUpdateTime = scanFileTime; 10602 } 10603 } 10604 pkgSetting.setTimeStamp(scanFileTime); 10605 10606 pkgSetting.pkg = pkg; 10607 pkgSetting.pkgFlags = pkg.applicationInfo.flags; 10608 if (pkg.getLongVersionCode() != pkgSetting.versionCode) { 10609 pkgSetting.versionCode = pkg.getLongVersionCode(); 10610 } 10611 // Update volume if needed 10612 final String volumeUuid = pkg.applicationInfo.volumeUuid; 10613 if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) { 10614 Slog.i(PackageManagerService.TAG, 10615 "Update" + (pkgSetting.isSystem() ? " system" : "") 10616 + " package " + pkg.packageName 10617 + " volume from " + pkgSetting.volumeUuid 10618 + " to " + volumeUuid); 10619 pkgSetting.volumeUuid = volumeUuid; 10620 } 10621 10622 return new ScanResult(true, pkgSetting, changedAbiCodePath); 10623 } 10624 10625 /** 10626 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 10627 */ 10628 private static boolean apkHasCode(String fileName) { 10629 StrictJarFile jarFile = null; 10630 try { 10631 jarFile = new StrictJarFile(fileName, 10632 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 10633 return jarFile.findEntry("classes.dex") != null; 10634 } catch (IOException ignore) { 10635 } finally { 10636 try { 10637 if (jarFile != null) { 10638 jarFile.close(); 10639 } 10640 } catch (IOException ignore) {} 10641 } 10642 return false; 10643 } 10644 10645 /** 10646 * Enforces code policy for the package. This ensures that if an APK has 10647 * declared hasCode="true" in its manifest that the APK actually contains 10648 * code. 10649 * 10650 * @throws PackageManagerException If bytecode could not be found when it should exist 10651 */ 10652 private static void assertCodePolicy(PackageParser.Package pkg) 10653 throws PackageManagerException { 10654 final boolean shouldHaveCode = 10655 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 10656 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 10657 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10658 "Package " + pkg.baseCodePath + " code is missing"); 10659 } 10660 10661 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 10662 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 10663 final boolean splitShouldHaveCode = 10664 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 10665 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 10666 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10667 "Package " + pkg.splitCodePaths[i] + " code is missing"); 10668 } 10669 } 10670 } 10671 } 10672 10673 /** 10674 * Applies policy to the parsed package based upon the given policy flags. 10675 * Ensures the package is in a good state. 10676 * <p> 10677 * Implementation detail: This method must NOT have any side effect. It would 10678 * ideally be static, but, it requires locks to read system state. 10679 */ 10680 private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10681 final @ScanFlags int scanFlags) { 10682 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 10683 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 10684 if (pkg.applicationInfo.isDirectBootAware()) { 10685 // we're direct boot aware; set for all components 10686 for (PackageParser.Service s : pkg.services) { 10687 s.info.encryptionAware = s.info.directBootAware = true; 10688 } 10689 for (PackageParser.Provider p : pkg.providers) { 10690 p.info.encryptionAware = p.info.directBootAware = true; 10691 } 10692 for (PackageParser.Activity a : pkg.activities) { 10693 a.info.encryptionAware = a.info.directBootAware = true; 10694 } 10695 for (PackageParser.Activity r : pkg.receivers) { 10696 r.info.encryptionAware = r.info.directBootAware = true; 10697 } 10698 } 10699 if (compressedFileExists(pkg.codePath)) { 10700 pkg.isStub = true; 10701 } 10702 } else { 10703 // non system apps can't be flagged as core 10704 pkg.coreApp = false; 10705 // clear flags not applicable to regular apps 10706 pkg.applicationInfo.flags &= 10707 ~ApplicationInfo.FLAG_PERSISTENT; 10708 pkg.applicationInfo.privateFlags &= 10709 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10710 pkg.applicationInfo.privateFlags &= 10711 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10712 // cap permission priorities 10713 if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) { 10714 for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) { 10715 pkg.permissionGroups.get(i).info.priority = 0; 10716 } 10717 } 10718 } 10719 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10720 // clear protected broadcasts 10721 pkg.protectedBroadcasts = null; 10722 // ignore export request for single user receivers 10723 if (pkg.receivers != null) { 10724 for (int i = pkg.receivers.size() - 1; i >= 0; --i) { 10725 final PackageParser.Activity receiver = pkg.receivers.get(i); 10726 if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 10727 receiver.info.exported = false; 10728 } 10729 } 10730 } 10731 // ignore export request for single user services 10732 if (pkg.services != null) { 10733 for (int i = pkg.services.size() - 1; i >= 0; --i) { 10734 final PackageParser.Service service = pkg.services.get(i); 10735 if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 10736 service.info.exported = false; 10737 } 10738 } 10739 } 10740 // ignore export request for single user providers 10741 if (pkg.providers != null) { 10742 for (int i = pkg.providers.size() - 1; i >= 0; --i) { 10743 final PackageParser.Provider provider = pkg.providers.get(i); 10744 if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) { 10745 provider.info.exported = false; 10746 } 10747 } 10748 } 10749 } 10750 10751 if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) { 10752 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10753 } 10754 10755 if ((scanFlags & SCAN_AS_OEM) != 0) { 10756 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 10757 } 10758 10759 if ((scanFlags & SCAN_AS_VENDOR) != 0) { 10760 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR; 10761 } 10762 10763 if ((scanFlags & SCAN_AS_PRODUCT) != 0) { 10764 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT; 10765 } 10766 10767 if (!isSystemApp(pkg)) { 10768 // Only system apps can use these features. 10769 pkg.mOriginalPackages = null; 10770 pkg.mRealPackage = null; 10771 pkg.mAdoptPermissions = null; 10772 } 10773 } 10774 10775 private static @NonNull <T> T assertNotNull(@Nullable T object, String message) 10776 throws PackageManagerException { 10777 if (object == null) { 10778 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message); 10779 } 10780 return object; 10781 } 10782 10783 /** 10784 * Asserts the parsed package is valid according to the given policy. If the 10785 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10786 * <p> 10787 * Implementation detail: This method must NOT have any side effects. It would 10788 * ideally be static, but, it requires locks to read system state. 10789 * 10790 * @throws PackageManagerException If the package fails any of the validation checks 10791 */ 10792 private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10793 final @ScanFlags int scanFlags) 10794 throws PackageManagerException { 10795 if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10796 assertCodePolicy(pkg); 10797 } 10798 10799 if (pkg.applicationInfo.getCodePath() == null || 10800 pkg.applicationInfo.getResourcePath() == null) { 10801 // Bail out. The resource and code paths haven't been set. 10802 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10803 "Code and resource paths haven't been set correctly"); 10804 } 10805 10806 // Make sure we're not adding any bogus keyset info 10807 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10808 ksms.assertScannedPackageValid(pkg); 10809 10810 synchronized (mPackages) { 10811 // The special "android" package can only be defined once 10812 if (pkg.packageName.equals("android")) { 10813 if (mAndroidApplication != null) { 10814 Slog.w(TAG, "*************************************************"); 10815 Slog.w(TAG, "Core android package being redefined. Skipping."); 10816 Slog.w(TAG, " codePath=" + pkg.codePath); 10817 Slog.w(TAG, "*************************************************"); 10818 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10819 "Core android package being redefined. Skipping."); 10820 } 10821 } 10822 10823 // A package name must be unique; don't allow duplicates 10824 if (mPackages.containsKey(pkg.packageName)) { 10825 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10826 "Application package " + pkg.packageName 10827 + " already installed. Skipping duplicate."); 10828 } 10829 10830 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10831 // Static libs have a synthetic package name containing the version 10832 // but we still want the base name to be unique. 10833 if (mPackages.containsKey(pkg.manifestPackageName)) { 10834 throw new PackageManagerException( 10835 "Duplicate static shared lib provider package"); 10836 } 10837 10838 // Static shared libraries should have at least O target SDK 10839 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10840 throw new PackageManagerException( 10841 "Packages declaring static-shared libs must target O SDK or higher"); 10842 } 10843 10844 // Package declaring static a shared lib cannot be instant apps 10845 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10846 throw new PackageManagerException( 10847 "Packages declaring static-shared libs cannot be instant apps"); 10848 } 10849 10850 // Package declaring static a shared lib cannot be renamed since the package 10851 // name is synthetic and apps can't code around package manager internals. 10852 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10853 throw new PackageManagerException( 10854 "Packages declaring static-shared libs cannot be renamed"); 10855 } 10856 10857 // Package declaring static a shared lib cannot declare child packages 10858 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10859 throw new PackageManagerException( 10860 "Packages declaring static-shared libs cannot have child packages"); 10861 } 10862 10863 // Package declaring static a shared lib cannot declare dynamic libs 10864 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10865 throw new PackageManagerException( 10866 "Packages declaring static-shared libs cannot declare dynamic libs"); 10867 } 10868 10869 // Package declaring static a shared lib cannot declare shared users 10870 if (pkg.mSharedUserId != null) { 10871 throw new PackageManagerException( 10872 "Packages declaring static-shared libs cannot declare shared users"); 10873 } 10874 10875 // Static shared libs cannot declare activities 10876 if (!pkg.activities.isEmpty()) { 10877 throw new PackageManagerException( 10878 "Static shared libs cannot declare activities"); 10879 } 10880 10881 // Static shared libs cannot declare services 10882 if (!pkg.services.isEmpty()) { 10883 throw new PackageManagerException( 10884 "Static shared libs cannot declare services"); 10885 } 10886 10887 // Static shared libs cannot declare providers 10888 if (!pkg.providers.isEmpty()) { 10889 throw new PackageManagerException( 10890 "Static shared libs cannot declare content providers"); 10891 } 10892 10893 // Static shared libs cannot declare receivers 10894 if (!pkg.receivers.isEmpty()) { 10895 throw new PackageManagerException( 10896 "Static shared libs cannot declare broadcast receivers"); 10897 } 10898 10899 // Static shared libs cannot declare permission groups 10900 if (!pkg.permissionGroups.isEmpty()) { 10901 throw new PackageManagerException( 10902 "Static shared libs cannot declare permission groups"); 10903 } 10904 10905 // Static shared libs cannot declare permissions 10906 if (!pkg.permissions.isEmpty()) { 10907 throw new PackageManagerException( 10908 "Static shared libs cannot declare permissions"); 10909 } 10910 10911 // Static shared libs cannot declare protected broadcasts 10912 if (pkg.protectedBroadcasts != null) { 10913 throw new PackageManagerException( 10914 "Static shared libs cannot declare protected broadcasts"); 10915 } 10916 10917 // Static shared libs cannot be overlay targets 10918 if (pkg.mOverlayTarget != null) { 10919 throw new PackageManagerException( 10920 "Static shared libs cannot be overlay targets"); 10921 } 10922 10923 // The version codes must be ordered as lib versions 10924 long minVersionCode = Long.MIN_VALUE; 10925 long maxVersionCode = Long.MAX_VALUE; 10926 10927 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10928 pkg.staticSharedLibName); 10929 if (versionedLib != null) { 10930 final int versionCount = versionedLib.size(); 10931 for (int i = 0; i < versionCount; i++) { 10932 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10933 final long libVersionCode = libInfo.getDeclaringPackage() 10934 .getLongVersionCode(); 10935 if (libInfo.getLongVersion() < pkg.staticSharedLibVersion) { 10936 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10937 } else if (libInfo.getLongVersion() > pkg.staticSharedLibVersion) { 10938 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10939 } else { 10940 minVersionCode = maxVersionCode = libVersionCode; 10941 break; 10942 } 10943 } 10944 } 10945 if (pkg.getLongVersionCode() < minVersionCode 10946 || pkg.getLongVersionCode() > maxVersionCode) { 10947 throw new PackageManagerException("Static shared" 10948 + " lib version codes must be ordered as lib versions"); 10949 } 10950 } 10951 10952 // Only privileged apps and updated privileged apps can add child packages. 10953 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10954 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10955 throw new PackageManagerException("Only privileged apps can add child " 10956 + "packages. Ignoring package " + pkg.packageName); 10957 } 10958 final int childCount = pkg.childPackages.size(); 10959 for (int i = 0; i < childCount; i++) { 10960 PackageParser.Package childPkg = pkg.childPackages.get(i); 10961 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10962 childPkg.packageName)) { 10963 throw new PackageManagerException("Can't override child of " 10964 + "another disabled app. Ignoring package " + pkg.packageName); 10965 } 10966 } 10967 } 10968 10969 // If we're only installing presumed-existing packages, require that the 10970 // scanned APK is both already known and at the path previously established 10971 // for it. Previously unknown packages we pick up normally, but if we have an 10972 // a priori expectation about this package's install presence, enforce it. 10973 // With a singular exception for new system packages. When an OTA contains 10974 // a new system package, we allow the codepath to change from a system location 10975 // to the user-installed location. If we don't allow this change, any newer, 10976 // user-installed version of the application will be ignored. 10977 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10978 if (mExpectingBetter.containsKey(pkg.packageName)) { 10979 logCriticalInfo(Log.WARN, 10980 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10981 } else { 10982 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10983 if (known != null) { 10984 if (DEBUG_PACKAGE_SCANNING) { 10985 Log.d(TAG, "Examining " + pkg.codePath 10986 + " and requiring known paths " + known.codePathString 10987 + " & " + known.resourcePathString); 10988 } 10989 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10990 || !pkg.applicationInfo.getResourcePath().equals( 10991 known.resourcePathString)) { 10992 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10993 "Application package " + pkg.packageName 10994 + " found at " + pkg.applicationInfo.getCodePath() 10995 + " but expected at " + known.codePathString 10996 + "; ignoring."); 10997 } 10998 } else { 10999 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11000 "Application package " + pkg.packageName 11001 + " not found; ignoring."); 11002 } 11003 } 11004 } 11005 11006 // Verify that this new package doesn't have any content providers 11007 // that conflict with existing packages. Only do this if the 11008 // package isn't already installed, since we don't want to break 11009 // things that are installed. 11010 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 11011 final int N = pkg.providers.size(); 11012 int i; 11013 for (i=0; i<N; i++) { 11014 PackageParser.Provider p = pkg.providers.get(i); 11015 if (p.info.authority != null) { 11016 String names[] = p.info.authority.split(";"); 11017 for (int j = 0; j < names.length; j++) { 11018 if (mProvidersByAuthority.containsKey(names[j])) { 11019 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11020 final String otherPackageName = 11021 ((other != null && other.getComponentName() != null) ? 11022 other.getComponentName().getPackageName() : "?"); 11023 throw new PackageManagerException( 11024 INSTALL_FAILED_CONFLICTING_PROVIDER, 11025 "Can't install because provider name " + names[j] 11026 + " (in package " + pkg.applicationInfo.packageName 11027 + ") is already used by " + otherPackageName); 11028 } 11029 } 11030 } 11031 } 11032 } 11033 11034 // Verify that packages sharing a user with a privileged app are marked as privileged. 11035 if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) { 11036 SharedUserSetting sharedUserSetting = null; 11037 try { 11038 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 11039 } catch (PackageManagerException ignore) {} 11040 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 11041 // Exempt SharedUsers signed with the platform key. 11042 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 11043 if ((platformPkgSetting.signatures.mSigningDetails 11044 != PackageParser.SigningDetails.UNKNOWN) 11045 && (compareSignatures( 11046 platformPkgSetting.signatures.mSigningDetails.signatures, 11047 pkg.mSigningDetails.signatures) 11048 != PackageManager.SIGNATURE_MATCH)) { 11049 throw new PackageManagerException("Apps that share a user with a " + 11050 "privileged app must themselves be marked as privileged. " + 11051 pkg.packageName + " shares privileged user " + 11052 pkg.mSharedUserId + "."); 11053 } 11054 } 11055 } 11056 11057 // Apply policies specific for runtime resource overlays (RROs). 11058 if (pkg.mOverlayTarget != null) { 11059 // System overlays have some restrictions on their use of the 'static' state. 11060 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 11061 // We are scanning a system overlay. This can be the first scan of the 11062 // system/vendor/oem partition, or an update to the system overlay. 11063 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 11064 // This must be an update to a system overlay. 11065 final PackageSetting previousPkg = assertNotNull( 11066 mSettings.getPackageLPr(pkg.packageName), 11067 "previous package state not present"); 11068 11069 // Static overlays cannot be updated. 11070 if (previousPkg.pkg.mOverlayIsStatic) { 11071 throw new PackageManagerException("Overlay " + pkg.packageName + 11072 " is static and cannot be upgraded."); 11073 // Non-static overlays cannot be converted to static overlays. 11074 } else if (pkg.mOverlayIsStatic) { 11075 throw new PackageManagerException("Overlay " + pkg.packageName + 11076 " cannot be upgraded into a static overlay."); 11077 } 11078 } 11079 } else { 11080 // The overlay is a non-system overlay. Non-system overlays cannot be static. 11081 if (pkg.mOverlayIsStatic) { 11082 throw new PackageManagerException("Overlay " + pkg.packageName + 11083 " is static but not pre-installed."); 11084 } 11085 11086 // The only case where we allow installation of a non-system overlay is when 11087 // its signature is signed with the platform certificate. 11088 PackageSetting platformPkgSetting = mSettings.getPackageLPr("android"); 11089 if ((platformPkgSetting.signatures.mSigningDetails 11090 != PackageParser.SigningDetails.UNKNOWN) 11091 && (compareSignatures( 11092 platformPkgSetting.signatures.mSigningDetails.signatures, 11093 pkg.mSigningDetails.signatures) 11094 != PackageManager.SIGNATURE_MATCH)) { 11095 throw new PackageManagerException("Overlay " + pkg.packageName + 11096 " must be signed with the platform certificate."); 11097 } 11098 } 11099 } 11100 } 11101 } 11102 11103 private boolean addSharedLibraryLPw(String path, String apk, String name, long version, 11104 int type, String declaringPackageName, long declaringVersionCode) { 11105 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11106 if (versionedLib == null) { 11107 versionedLib = new LongSparseArray<>(); 11108 mSharedLibraries.put(name, versionedLib); 11109 if (type == SharedLibraryInfo.TYPE_STATIC) { 11110 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 11111 } 11112 } else if (versionedLib.indexOfKey(version) >= 0) { 11113 return false; 11114 } 11115 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 11116 version, type, declaringPackageName, declaringVersionCode); 11117 versionedLib.put(version, libEntry); 11118 return true; 11119 } 11120 11121 private boolean removeSharedLibraryLPw(String name, long version) { 11122 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11123 if (versionedLib == null) { 11124 return false; 11125 } 11126 final int libIdx = versionedLib.indexOfKey(version); 11127 if (libIdx < 0) { 11128 return false; 11129 } 11130 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 11131 versionedLib.remove(version); 11132 if (versionedLib.size() <= 0) { 11133 mSharedLibraries.remove(name); 11134 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 11135 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 11136 .getPackageName()); 11137 } 11138 } 11139 return true; 11140 } 11141 11142 /** 11143 * Adds a scanned package to the system. When this method is finished, the package will 11144 * be available for query, resolution, etc... 11145 */ 11146 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 11147 UserHandle user, final @ScanFlags int scanFlags, boolean chatty) { 11148 final String pkgName = pkg.packageName; 11149 if (mCustomResolverComponentName != null && 11150 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 11151 setUpCustomResolverActivity(pkg); 11152 } 11153 11154 if (pkg.packageName.equals("android")) { 11155 synchronized (mPackages) { 11156 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 11157 // Set up information for our fall-back user intent resolution activity. 11158 mPlatformPackage = pkg; 11159 pkg.mVersionCode = mSdkVersion; 11160 pkg.mVersionCodeMajor = 0; 11161 mAndroidApplication = pkg.applicationInfo; 11162 if (!mResolverReplaced) { 11163 mResolveActivity.applicationInfo = mAndroidApplication; 11164 mResolveActivity.name = ResolverActivity.class.getName(); 11165 mResolveActivity.packageName = mAndroidApplication.packageName; 11166 mResolveActivity.processName = "system:ui"; 11167 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11168 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 11169 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 11170 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 11171 mResolveActivity.exported = true; 11172 mResolveActivity.enabled = true; 11173 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 11174 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 11175 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 11176 | ActivityInfo.CONFIG_SCREEN_LAYOUT 11177 | ActivityInfo.CONFIG_ORIENTATION 11178 | ActivityInfo.CONFIG_KEYBOARD 11179 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 11180 mResolveInfo.activityInfo = mResolveActivity; 11181 mResolveInfo.priority = 0; 11182 mResolveInfo.preferredOrder = 0; 11183 mResolveInfo.match = 0; 11184 mResolveComponentName = new ComponentName( 11185 mAndroidApplication.packageName, mResolveActivity.name); 11186 } 11187 } 11188 } 11189 } 11190 11191 ArrayList<PackageParser.Package> clientLibPkgs = null; 11192 // writer 11193 synchronized (mPackages) { 11194 boolean hasStaticSharedLibs = false; 11195 11196 // Any app can add new static shared libraries 11197 if (pkg.staticSharedLibName != null) { 11198 // Static shared libs don't allow renaming as they have synthetic package 11199 // names to allow install of multiple versions, so use name from manifest. 11200 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 11201 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 11202 pkg.manifestPackageName, pkg.getLongVersionCode())) { 11203 hasStaticSharedLibs = true; 11204 } else { 11205 Slog.w(TAG, "Package " + pkg.packageName + " library " 11206 + pkg.staticSharedLibName + " already exists; skipping"); 11207 } 11208 // Static shared libs cannot be updated once installed since they 11209 // use synthetic package name which includes the version code, so 11210 // not need to update other packages's shared lib dependencies. 11211 } 11212 11213 if (!hasStaticSharedLibs 11214 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11215 // Only system apps can add new dynamic shared libraries. 11216 if (pkg.libraryNames != null) { 11217 for (int i = 0; i < pkg.libraryNames.size(); i++) { 11218 String name = pkg.libraryNames.get(i); 11219 boolean allowed = false; 11220 if (pkg.isUpdatedSystemApp()) { 11221 // New library entries can only be added through the 11222 // system image. This is important to get rid of a lot 11223 // of nasty edge cases: for example if we allowed a non- 11224 // system update of the app to add a library, then uninstalling 11225 // the update would make the library go away, and assumptions 11226 // we made such as through app install filtering would now 11227 // have allowed apps on the device which aren't compatible 11228 // with it. Better to just have the restriction here, be 11229 // conservative, and create many fewer cases that can negatively 11230 // impact the user experience. 11231 final PackageSetting sysPs = mSettings 11232 .getDisabledSystemPkgLPr(pkg.packageName); 11233 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 11234 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 11235 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 11236 allowed = true; 11237 break; 11238 } 11239 } 11240 } 11241 } else { 11242 allowed = true; 11243 } 11244 if (allowed) { 11245 if (!addSharedLibraryLPw(null, pkg.packageName, name, 11246 SharedLibraryInfo.VERSION_UNDEFINED, 11247 SharedLibraryInfo.TYPE_DYNAMIC, 11248 pkg.packageName, pkg.getLongVersionCode())) { 11249 Slog.w(TAG, "Package " + pkg.packageName + " library " 11250 + name + " already exists; skipping"); 11251 } 11252 } else { 11253 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 11254 + name + " that is not declared on system image; skipping"); 11255 } 11256 } 11257 11258 if ((scanFlags & SCAN_BOOTING) == 0) { 11259 // If we are not booting, we need to update any applications 11260 // that are clients of our shared library. If we are booting, 11261 // this will all be done once the scan is complete. 11262 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 11263 } 11264 } 11265 } 11266 } 11267 11268 if ((scanFlags & SCAN_BOOTING) != 0) { 11269 // No apps can run during boot scan, so they don't need to be frozen 11270 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 11271 // Caller asked to not kill app, so it's probably not frozen 11272 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 11273 // Caller asked us to ignore frozen check for some reason; they 11274 // probably didn't know the package name 11275 } else { 11276 // We're doing major surgery on this package, so it better be frozen 11277 // right now to keep it from launching 11278 checkPackageFrozen(pkgName); 11279 } 11280 11281 // Also need to kill any apps that are dependent on the library. 11282 if (clientLibPkgs != null) { 11283 for (int i=0; i<clientLibPkgs.size(); i++) { 11284 PackageParser.Package clientPkg = clientLibPkgs.get(i); 11285 killApplication(clientPkg.applicationInfo.packageName, 11286 clientPkg.applicationInfo.uid, "update lib"); 11287 } 11288 } 11289 11290 // writer 11291 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 11292 11293 synchronized (mPackages) { 11294 // We don't expect installation to fail beyond this point 11295 11296 // Add the new setting to mSettings 11297 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 11298 // Add the new setting to mPackages 11299 mPackages.put(pkg.applicationInfo.packageName, pkg); 11300 // Make sure we don't accidentally delete its data. 11301 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 11302 while (iter.hasNext()) { 11303 PackageCleanItem item = iter.next(); 11304 if (pkgName.equals(item.packageName)) { 11305 iter.remove(); 11306 } 11307 } 11308 11309 // Add the package's KeySets to the global KeySetManagerService 11310 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11311 ksms.addScannedPackageLPw(pkg); 11312 11313 int N = pkg.providers.size(); 11314 StringBuilder r = null; 11315 int i; 11316 for (i=0; i<N; i++) { 11317 PackageParser.Provider p = pkg.providers.get(i); 11318 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 11319 p.info.processName); 11320 mProviders.addProvider(p); 11321 p.syncable = p.info.isSyncable; 11322 if (p.info.authority != null) { 11323 String names[] = p.info.authority.split(";"); 11324 p.info.authority = null; 11325 for (int j = 0; j < names.length; j++) { 11326 if (j == 1 && p.syncable) { 11327 // We only want the first authority for a provider to possibly be 11328 // syncable, so if we already added this provider using a different 11329 // authority clear the syncable flag. We copy the provider before 11330 // changing it because the mProviders object contains a reference 11331 // to a provider that we don't want to change. 11332 // Only do this for the second authority since the resulting provider 11333 // object can be the same for all future authorities for this provider. 11334 p = new PackageParser.Provider(p); 11335 p.syncable = false; 11336 } 11337 if (!mProvidersByAuthority.containsKey(names[j])) { 11338 mProvidersByAuthority.put(names[j], p); 11339 if (p.info.authority == null) { 11340 p.info.authority = names[j]; 11341 } else { 11342 p.info.authority = p.info.authority + ";" + names[j]; 11343 } 11344 if (DEBUG_PACKAGE_SCANNING) { 11345 if (chatty) 11346 Log.d(TAG, "Registered content provider: " + names[j] 11347 + ", className = " + p.info.name + ", isSyncable = " 11348 + p.info.isSyncable); 11349 } 11350 } else { 11351 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11352 Slog.w(TAG, "Skipping provider name " + names[j] + 11353 " (in package " + pkg.applicationInfo.packageName + 11354 "): name already used by " 11355 + ((other != null && other.getComponentName() != null) 11356 ? other.getComponentName().getPackageName() : "?")); 11357 } 11358 } 11359 } 11360 if (chatty) { 11361 if (r == null) { 11362 r = new StringBuilder(256); 11363 } else { 11364 r.append(' '); 11365 } 11366 r.append(p.info.name); 11367 } 11368 } 11369 if (r != null) { 11370 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 11371 } 11372 11373 N = pkg.services.size(); 11374 r = null; 11375 for (i=0; i<N; i++) { 11376 PackageParser.Service s = pkg.services.get(i); 11377 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 11378 s.info.processName); 11379 mServices.addService(s); 11380 if (chatty) { 11381 if (r == null) { 11382 r = new StringBuilder(256); 11383 } else { 11384 r.append(' '); 11385 } 11386 r.append(s.info.name); 11387 } 11388 } 11389 if (r != null) { 11390 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 11391 } 11392 11393 N = pkg.receivers.size(); 11394 r = null; 11395 for (i=0; i<N; i++) { 11396 PackageParser.Activity a = pkg.receivers.get(i); 11397 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11398 a.info.processName); 11399 mReceivers.addActivity(a, "receiver"); 11400 if (chatty) { 11401 if (r == null) { 11402 r = new StringBuilder(256); 11403 } else { 11404 r.append(' '); 11405 } 11406 r.append(a.info.name); 11407 } 11408 } 11409 if (r != null) { 11410 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 11411 } 11412 11413 N = pkg.activities.size(); 11414 r = null; 11415 for (i=0; i<N; i++) { 11416 PackageParser.Activity a = pkg.activities.get(i); 11417 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11418 a.info.processName); 11419 mActivities.addActivity(a, "activity"); 11420 if (chatty) { 11421 if (r == null) { 11422 r = new StringBuilder(256); 11423 } else { 11424 r.append(' '); 11425 } 11426 r.append(a.info.name); 11427 } 11428 } 11429 if (r != null) { 11430 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11431 } 11432 11433 // Don't allow ephemeral applications to define new permissions groups. 11434 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11435 Slog.w(TAG, "Permission groups from package " + pkg.packageName 11436 + " ignored: instant apps cannot define new permission groups."); 11437 } else { 11438 mPermissionManager.addAllPermissionGroups(pkg, chatty); 11439 } 11440 11441 // Don't allow ephemeral applications to define new permissions. 11442 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11443 Slog.w(TAG, "Permissions from package " + pkg.packageName 11444 + " ignored: instant apps cannot define new permissions."); 11445 } else { 11446 mPermissionManager.addAllPermissions(pkg, chatty); 11447 } 11448 11449 N = pkg.instrumentation.size(); 11450 r = null; 11451 for (i=0; i<N; i++) { 11452 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11453 a.info.packageName = pkg.applicationInfo.packageName; 11454 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11455 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11456 a.info.splitNames = pkg.splitNames; 11457 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11458 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11459 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11460 a.info.dataDir = pkg.applicationInfo.dataDir; 11461 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11462 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11463 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11464 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11465 mInstrumentation.put(a.getComponentName(), a); 11466 if (chatty) { 11467 if (r == null) { 11468 r = new StringBuilder(256); 11469 } else { 11470 r.append(' '); 11471 } 11472 r.append(a.info.name); 11473 } 11474 } 11475 if (r != null) { 11476 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11477 } 11478 11479 if (pkg.protectedBroadcasts != null) { 11480 N = pkg.protectedBroadcasts.size(); 11481 synchronized (mProtectedBroadcasts) { 11482 for (i = 0; i < N; i++) { 11483 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 11484 } 11485 } 11486 } 11487 } 11488 11489 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11490 } 11491 11492 /** 11493 * Derive the ABI of a non-system package located at {@code scanFile}. This information 11494 * is derived purely on the basis of the contents of {@code scanFile} and 11495 * {@code cpuAbiOverride}. 11496 * 11497 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 11498 */ 11499 private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride, 11500 boolean extractLibs) 11501 throws PackageManagerException { 11502 // Give ourselves some initial paths; we'll come back for another 11503 // pass once we've determined ABI below. 11504 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11505 11506 // We would never need to extract libs for forward-locked and external packages, 11507 // since the container service will do it for us. We shouldn't attempt to 11508 // extract libs from system app when it was not updated. 11509 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 11510 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 11511 extractLibs = false; 11512 } 11513 11514 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 11515 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 11516 11517 NativeLibraryHelper.Handle handle = null; 11518 try { 11519 handle = NativeLibraryHelper.Handle.create(pkg); 11520 // TODO(multiArch): This can be null for apps that didn't go through the 11521 // usual installation process. We can calculate it again, like we 11522 // do during install time. 11523 // 11524 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 11525 // unnecessary. 11526 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 11527 11528 // Null out the abis so that they can be recalculated. 11529 pkg.applicationInfo.primaryCpuAbi = null; 11530 pkg.applicationInfo.secondaryCpuAbi = null; 11531 if (isMultiArch(pkg.applicationInfo)) { 11532 // Warn if we've set an abiOverride for multi-lib packages.. 11533 // By definition, we need to copy both 32 and 64 bit libraries for 11534 // such packages. 11535 if (pkg.cpuAbiOverride != null 11536 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 11537 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 11538 } 11539 11540 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 11541 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 11542 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 11543 if (extractLibs) { 11544 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11545 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11546 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 11547 useIsaSpecificSubdirs); 11548 } else { 11549 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11550 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 11551 } 11552 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11553 } 11554 11555 // Shared library native code should be in the APK zip aligned 11556 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 11557 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11558 "Shared library native lib extraction not supported"); 11559 } 11560 11561 maybeThrowExceptionForMultiArchCopy( 11562 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 11563 11564 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 11565 if (extractLibs) { 11566 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11567 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11568 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 11569 useIsaSpecificSubdirs); 11570 } else { 11571 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11572 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 11573 } 11574 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11575 } 11576 11577 maybeThrowExceptionForMultiArchCopy( 11578 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 11579 11580 if (abi64 >= 0) { 11581 // Shared library native libs should be in the APK zip aligned 11582 if (extractLibs && pkg.isLibrary()) { 11583 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11584 "Shared library native lib extraction not supported"); 11585 } 11586 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11587 } 11588 11589 if (abi32 >= 0) { 11590 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11591 if (abi64 >= 0) { 11592 if (pkg.use32bitAbi) { 11593 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11594 pkg.applicationInfo.primaryCpuAbi = abi; 11595 } else { 11596 pkg.applicationInfo.secondaryCpuAbi = abi; 11597 } 11598 } else { 11599 pkg.applicationInfo.primaryCpuAbi = abi; 11600 } 11601 } 11602 } else { 11603 String[] abiList = (cpuAbiOverride != null) ? 11604 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11605 11606 // Enable gross and lame hacks for apps that are built with old 11607 // SDK tools. We must scan their APKs for renderscript bitcode and 11608 // not launch them if it's present. Don't bother checking on devices 11609 // that don't have 64 bit support. 11610 boolean needsRenderScriptOverride = false; 11611 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11612 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11613 abiList = Build.SUPPORTED_32_BIT_ABIS; 11614 needsRenderScriptOverride = true; 11615 } 11616 11617 final int copyRet; 11618 if (extractLibs) { 11619 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11620 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11621 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11622 } else { 11623 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11624 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11625 } 11626 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11627 11628 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11629 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11630 "Error unpackaging native libs for app, errorCode=" + copyRet); 11631 } 11632 11633 if (copyRet >= 0) { 11634 // Shared libraries that have native libs must be multi-architecture 11635 if (pkg.isLibrary()) { 11636 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11637 "Shared library with native libs must be multiarch"); 11638 } 11639 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11640 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11641 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11642 } else if (needsRenderScriptOverride) { 11643 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11644 } 11645 } 11646 } catch (IOException ioe) { 11647 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11648 } finally { 11649 IoUtils.closeQuietly(handle); 11650 } 11651 11652 // Now that we've calculated the ABIs and determined if it's an internal app, 11653 // we will go ahead and populate the nativeLibraryPath. 11654 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11655 } 11656 11657 /** 11658 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11659 * i.e, so that all packages can be run inside a single process if required. 11660 * 11661 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11662 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11663 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11664 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11665 * updating a package that belongs to a shared user. 11666 * 11667 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11668 * adds unnecessary complexity. 11669 */ 11670 private static @Nullable List<String> adjustCpuAbisForSharedUserLPw( 11671 Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) { 11672 List<String> changedAbiCodePath = null; 11673 String requiredInstructionSet = null; 11674 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11675 requiredInstructionSet = VMRuntime.getInstructionSet( 11676 scannedPackage.applicationInfo.primaryCpuAbi); 11677 } 11678 11679 PackageSetting requirer = null; 11680 for (PackageSetting ps : packagesForUser) { 11681 // If packagesForUser contains scannedPackage, we skip it. This will happen 11682 // when scannedPackage is an update of an existing package. Without this check, 11683 // we will never be able to change the ABI of any package belonging to a shared 11684 // user, even if it's compatible with other packages. 11685 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11686 if (ps.primaryCpuAbiString == null) { 11687 continue; 11688 } 11689 11690 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11691 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11692 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11693 // this but there's not much we can do. 11694 String errorMessage = "Instruction set mismatch, " 11695 + ((requirer == null) ? "[caller]" : requirer) 11696 + " requires " + requiredInstructionSet + " whereas " + ps 11697 + " requires " + instructionSet; 11698 Slog.w(TAG, errorMessage); 11699 } 11700 11701 if (requiredInstructionSet == null) { 11702 requiredInstructionSet = instructionSet; 11703 requirer = ps; 11704 } 11705 } 11706 } 11707 11708 if (requiredInstructionSet != null) { 11709 String adjustedAbi; 11710 if (requirer != null) { 11711 // requirer != null implies that either scannedPackage was null or that scannedPackage 11712 // did not require an ABI, in which case we have to adjust scannedPackage to match 11713 // the ABI of the set (which is the same as requirer's ABI) 11714 adjustedAbi = requirer.primaryCpuAbiString; 11715 if (scannedPackage != null) { 11716 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11717 } 11718 } else { 11719 // requirer == null implies that we're updating all ABIs in the set to 11720 // match scannedPackage. 11721 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11722 } 11723 11724 for (PackageSetting ps : packagesForUser) { 11725 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11726 if (ps.primaryCpuAbiString != null) { 11727 continue; 11728 } 11729 11730 ps.primaryCpuAbiString = adjustedAbi; 11731 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11732 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11733 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11734 if (DEBUG_ABI_SELECTION) { 11735 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11736 + " (requirer=" 11737 + (requirer != null ? requirer.pkg : "null") 11738 + ", scannedPackage=" 11739 + (scannedPackage != null ? scannedPackage : "null") 11740 + ")"); 11741 } 11742 if (changedAbiCodePath == null) { 11743 changedAbiCodePath = new ArrayList<>(); 11744 } 11745 changedAbiCodePath.add(ps.codePathString); 11746 } 11747 } 11748 } 11749 } 11750 return changedAbiCodePath; 11751 } 11752 11753 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11754 synchronized (mPackages) { 11755 mResolverReplaced = true; 11756 // Set up information for custom user intent resolution activity. 11757 mResolveActivity.applicationInfo = pkg.applicationInfo; 11758 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11759 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11760 mResolveActivity.processName = pkg.applicationInfo.packageName; 11761 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11762 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11763 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11764 mResolveActivity.theme = 0; 11765 mResolveActivity.exported = true; 11766 mResolveActivity.enabled = true; 11767 mResolveInfo.activityInfo = mResolveActivity; 11768 mResolveInfo.priority = 0; 11769 mResolveInfo.preferredOrder = 0; 11770 mResolveInfo.match = 0; 11771 mResolveComponentName = mCustomResolverComponentName; 11772 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11773 mResolveComponentName); 11774 } 11775 } 11776 11777 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11778 if (installerActivity == null) { 11779 if (DEBUG_INSTANT) { 11780 Slog.d(TAG, "Clear ephemeral installer activity"); 11781 } 11782 mInstantAppInstallerActivity = null; 11783 return; 11784 } 11785 11786 if (DEBUG_INSTANT) { 11787 Slog.d(TAG, "Set ephemeral installer activity: " 11788 + installerActivity.getComponentName()); 11789 } 11790 // Set up information for ephemeral installer activity 11791 mInstantAppInstallerActivity = installerActivity; 11792 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11793 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11794 mInstantAppInstallerActivity.exported = true; 11795 mInstantAppInstallerActivity.enabled = true; 11796 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11797 mInstantAppInstallerInfo.priority = 1; 11798 mInstantAppInstallerInfo.preferredOrder = 1; 11799 mInstantAppInstallerInfo.isDefault = true; 11800 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11801 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11802 } 11803 11804 private static String calculateBundledApkRoot(final String codePathString) { 11805 final File codePath = new File(codePathString); 11806 final File codeRoot; 11807 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11808 codeRoot = Environment.getRootDirectory(); 11809 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11810 codeRoot = Environment.getOemDirectory(); 11811 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11812 codeRoot = Environment.getVendorDirectory(); 11813 } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) { 11814 codeRoot = Environment.getOdmDirectory(); 11815 } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) { 11816 codeRoot = Environment.getProductDirectory(); 11817 } else { 11818 // Unrecognized code path; take its top real segment as the apk root: 11819 // e.g. /something/app/blah.apk => /something 11820 try { 11821 File f = codePath.getCanonicalFile(); 11822 File parent = f.getParentFile(); // non-null because codePath is a file 11823 File tmp; 11824 while ((tmp = parent.getParentFile()) != null) { 11825 f = parent; 11826 parent = tmp; 11827 } 11828 codeRoot = f; 11829 Slog.w(TAG, "Unrecognized code path " 11830 + codePath + " - using " + codeRoot); 11831 } catch (IOException e) { 11832 // Can't canonicalize the code path -- shenanigans? 11833 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11834 return Environment.getRootDirectory().getPath(); 11835 } 11836 } 11837 return codeRoot.getPath(); 11838 } 11839 11840 /** 11841 * Derive and set the location of native libraries for the given package, 11842 * which varies depending on where and how the package was installed. 11843 */ 11844 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11845 final ApplicationInfo info = pkg.applicationInfo; 11846 final String codePath = pkg.codePath; 11847 final File codeFile = new File(codePath); 11848 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11849 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11850 11851 info.nativeLibraryRootDir = null; 11852 info.nativeLibraryRootRequiresIsa = false; 11853 info.nativeLibraryDir = null; 11854 info.secondaryNativeLibraryDir = null; 11855 11856 if (isApkFile(codeFile)) { 11857 // Monolithic install 11858 if (bundledApp) { 11859 // If "/system/lib64/apkname" exists, assume that is the per-package 11860 // native library directory to use; otherwise use "/system/lib/apkname". 11861 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11862 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11863 getPrimaryInstructionSet(info)); 11864 11865 // This is a bundled system app so choose the path based on the ABI. 11866 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11867 // is just the default path. 11868 final String apkName = deriveCodePathName(codePath); 11869 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11870 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11871 apkName).getAbsolutePath(); 11872 11873 if (info.secondaryCpuAbi != null) { 11874 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11875 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11876 secondaryLibDir, apkName).getAbsolutePath(); 11877 } 11878 } else if (asecApp) { 11879 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11880 .getAbsolutePath(); 11881 } else { 11882 final String apkName = deriveCodePathName(codePath); 11883 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11884 .getAbsolutePath(); 11885 } 11886 11887 info.nativeLibraryRootRequiresIsa = false; 11888 info.nativeLibraryDir = info.nativeLibraryRootDir; 11889 } else { 11890 // Cluster install 11891 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11892 info.nativeLibraryRootRequiresIsa = true; 11893 11894 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11895 getPrimaryInstructionSet(info)).getAbsolutePath(); 11896 11897 if (info.secondaryCpuAbi != null) { 11898 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11899 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11900 } 11901 } 11902 } 11903 11904 /** 11905 * Calculate the abis and roots for a bundled app. These can uniquely 11906 * be determined from the contents of the system partition, i.e whether 11907 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11908 * of this information, and instead assume that the system was built 11909 * sensibly. 11910 */ 11911 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11912 PackageSetting pkgSetting) { 11913 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11914 11915 // If "/system/lib64/apkname" exists, assume that is the per-package 11916 // native library directory to use; otherwise use "/system/lib/apkname". 11917 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11918 setBundledAppAbi(pkg, apkRoot, apkName); 11919 // pkgSetting might be null during rescan following uninstall of updates 11920 // to a bundled app, so accommodate that possibility. The settings in 11921 // that case will be established later from the parsed package. 11922 // 11923 // If the settings aren't null, sync them up with what we've just derived. 11924 // note that apkRoot isn't stored in the package settings. 11925 if (pkgSetting != null) { 11926 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11927 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11928 } 11929 } 11930 11931 /** 11932 * Deduces the ABI of a bundled app and sets the relevant fields on the 11933 * parsed pkg object. 11934 * 11935 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11936 * under which system libraries are installed. 11937 * @param apkName the name of the installed package. 11938 */ 11939 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11940 final File codeFile = new File(pkg.codePath); 11941 11942 final boolean has64BitLibs; 11943 final boolean has32BitLibs; 11944 if (isApkFile(codeFile)) { 11945 // Monolithic install 11946 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11947 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11948 } else { 11949 // Cluster install 11950 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11951 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11952 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11953 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11954 has64BitLibs = (new File(rootDir, isa)).exists(); 11955 } else { 11956 has64BitLibs = false; 11957 } 11958 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11959 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11960 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11961 has32BitLibs = (new File(rootDir, isa)).exists(); 11962 } else { 11963 has32BitLibs = false; 11964 } 11965 } 11966 11967 if (has64BitLibs && !has32BitLibs) { 11968 // The package has 64 bit libs, but not 32 bit libs. Its primary 11969 // ABI should be 64 bit. We can safely assume here that the bundled 11970 // native libraries correspond to the most preferred ABI in the list. 11971 11972 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11973 pkg.applicationInfo.secondaryCpuAbi = null; 11974 } else if (has32BitLibs && !has64BitLibs) { 11975 // The package has 32 bit libs but not 64 bit libs. Its primary 11976 // ABI should be 32 bit. 11977 11978 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11979 pkg.applicationInfo.secondaryCpuAbi = null; 11980 } else if (has32BitLibs && has64BitLibs) { 11981 // The application has both 64 and 32 bit bundled libraries. We check 11982 // here that the app declares multiArch support, and warn if it doesn't. 11983 // 11984 // We will be lenient here and record both ABIs. The primary will be the 11985 // ABI that's higher on the list, i.e, a device that's configured to prefer 11986 // 64 bit apps will see a 64 bit primary ABI, 11987 11988 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11989 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11990 } 11991 11992 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11993 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11994 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11995 } else { 11996 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11997 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11998 } 11999 } else { 12000 pkg.applicationInfo.primaryCpuAbi = null; 12001 pkg.applicationInfo.secondaryCpuAbi = null; 12002 } 12003 } 12004 12005 private void killApplication(String pkgName, int appId, String reason) { 12006 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 12007 } 12008 12009 private void killApplication(String pkgName, int appId, int userId, String reason) { 12010 // Request the ActivityManager to kill the process(only for existing packages) 12011 // so that we do not end up in a confused state while the user is still using the older 12012 // version of the application while the new one gets installed. 12013 final long token = Binder.clearCallingIdentity(); 12014 try { 12015 IActivityManager am = ActivityManager.getService(); 12016 if (am != null) { 12017 try { 12018 am.killApplication(pkgName, appId, userId, reason); 12019 } catch (RemoteException e) { 12020 } 12021 } 12022 } finally { 12023 Binder.restoreCallingIdentity(token); 12024 } 12025 } 12026 12027 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 12028 // Remove the parent package setting 12029 PackageSetting ps = (PackageSetting) pkg.mExtras; 12030 if (ps != null) { 12031 removePackageLI(ps, chatty); 12032 } 12033 // Remove the child package setting 12034 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12035 for (int i = 0; i < childCount; i++) { 12036 PackageParser.Package childPkg = pkg.childPackages.get(i); 12037 ps = (PackageSetting) childPkg.mExtras; 12038 if (ps != null) { 12039 removePackageLI(ps, chatty); 12040 } 12041 } 12042 } 12043 12044 void removePackageLI(PackageSetting ps, boolean chatty) { 12045 if (DEBUG_INSTALL) { 12046 if (chatty) 12047 Log.d(TAG, "Removing package " + ps.name); 12048 } 12049 12050 // writer 12051 synchronized (mPackages) { 12052 mPackages.remove(ps.name); 12053 final PackageParser.Package pkg = ps.pkg; 12054 if (pkg != null) { 12055 cleanPackageDataStructuresLILPw(pkg, chatty); 12056 } 12057 } 12058 } 12059 12060 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 12061 if (DEBUG_INSTALL) { 12062 if (chatty) 12063 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 12064 } 12065 12066 // writer 12067 synchronized (mPackages) { 12068 // Remove the parent package 12069 mPackages.remove(pkg.applicationInfo.packageName); 12070 cleanPackageDataStructuresLILPw(pkg, chatty); 12071 12072 // Remove the child packages 12073 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12074 for (int i = 0; i < childCount; i++) { 12075 PackageParser.Package childPkg = pkg.childPackages.get(i); 12076 mPackages.remove(childPkg.applicationInfo.packageName); 12077 cleanPackageDataStructuresLILPw(childPkg, chatty); 12078 } 12079 } 12080 } 12081 12082 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 12083 int N = pkg.providers.size(); 12084 StringBuilder r = null; 12085 int i; 12086 for (i=0; i<N; i++) { 12087 PackageParser.Provider p = pkg.providers.get(i); 12088 mProviders.removeProvider(p); 12089 if (p.info.authority == null) { 12090 12091 /* There was another ContentProvider with this authority when 12092 * this app was installed so this authority is null, 12093 * Ignore it as we don't have to unregister the provider. 12094 */ 12095 continue; 12096 } 12097 String names[] = p.info.authority.split(";"); 12098 for (int j = 0; j < names.length; j++) { 12099 if (mProvidersByAuthority.get(names[j]) == p) { 12100 mProvidersByAuthority.remove(names[j]); 12101 if (DEBUG_REMOVE) { 12102 if (chatty) 12103 Log.d(TAG, "Unregistered content provider: " + names[j] 12104 + ", className = " + p.info.name + ", isSyncable = " 12105 + p.info.isSyncable); 12106 } 12107 } 12108 } 12109 if (DEBUG_REMOVE && chatty) { 12110 if (r == null) { 12111 r = new StringBuilder(256); 12112 } else { 12113 r.append(' '); 12114 } 12115 r.append(p.info.name); 12116 } 12117 } 12118 if (r != null) { 12119 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 12120 } 12121 12122 N = pkg.services.size(); 12123 r = null; 12124 for (i=0; i<N; i++) { 12125 PackageParser.Service s = pkg.services.get(i); 12126 mServices.removeService(s); 12127 if (chatty) { 12128 if (r == null) { 12129 r = new StringBuilder(256); 12130 } else { 12131 r.append(' '); 12132 } 12133 r.append(s.info.name); 12134 } 12135 } 12136 if (r != null) { 12137 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 12138 } 12139 12140 N = pkg.receivers.size(); 12141 r = null; 12142 for (i=0; i<N; i++) { 12143 PackageParser.Activity a = pkg.receivers.get(i); 12144 mReceivers.removeActivity(a, "receiver"); 12145 if (DEBUG_REMOVE && chatty) { 12146 if (r == null) { 12147 r = new StringBuilder(256); 12148 } else { 12149 r.append(' '); 12150 } 12151 r.append(a.info.name); 12152 } 12153 } 12154 if (r != null) { 12155 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 12156 } 12157 12158 N = pkg.activities.size(); 12159 r = null; 12160 for (i=0; i<N; i++) { 12161 PackageParser.Activity a = pkg.activities.get(i); 12162 mActivities.removeActivity(a, "activity"); 12163 if (DEBUG_REMOVE && chatty) { 12164 if (r == null) { 12165 r = new StringBuilder(256); 12166 } else { 12167 r.append(' '); 12168 } 12169 r.append(a.info.name); 12170 } 12171 } 12172 if (r != null) { 12173 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 12174 } 12175 12176 mPermissionManager.removeAllPermissions(pkg, chatty); 12177 12178 N = pkg.instrumentation.size(); 12179 r = null; 12180 for (i=0; i<N; i++) { 12181 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 12182 mInstrumentation.remove(a.getComponentName()); 12183 if (DEBUG_REMOVE && chatty) { 12184 if (r == null) { 12185 r = new StringBuilder(256); 12186 } else { 12187 r.append(' '); 12188 } 12189 r.append(a.info.name); 12190 } 12191 } 12192 if (r != null) { 12193 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 12194 } 12195 12196 r = null; 12197 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 12198 // Only system apps can hold shared libraries. 12199 if (pkg.libraryNames != null) { 12200 for (i = 0; i < pkg.libraryNames.size(); i++) { 12201 String name = pkg.libraryNames.get(i); 12202 if (removeSharedLibraryLPw(name, 0)) { 12203 if (DEBUG_REMOVE && chatty) { 12204 if (r == null) { 12205 r = new StringBuilder(256); 12206 } else { 12207 r.append(' '); 12208 } 12209 r.append(name); 12210 } 12211 } 12212 } 12213 } 12214 } 12215 12216 r = null; 12217 12218 // Any package can hold static shared libraries. 12219 if (pkg.staticSharedLibName != null) { 12220 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 12221 if (DEBUG_REMOVE && chatty) { 12222 if (r == null) { 12223 r = new StringBuilder(256); 12224 } else { 12225 r.append(' '); 12226 } 12227 r.append(pkg.staticSharedLibName); 12228 } 12229 } 12230 } 12231 12232 if (r != null) { 12233 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 12234 } 12235 } 12236 12237 12238 final class ActivityIntentResolver 12239 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 12240 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12241 boolean defaultOnly, int userId) { 12242 if (!sUserManager.exists(userId)) return null; 12243 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 12244 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12245 } 12246 12247 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12248 int userId) { 12249 if (!sUserManager.exists(userId)) return null; 12250 mFlags = flags; 12251 return super.queryIntent(intent, resolvedType, 12252 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12253 userId); 12254 } 12255 12256 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12257 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 12258 if (!sUserManager.exists(userId)) return null; 12259 if (packageActivities == null) { 12260 return null; 12261 } 12262 mFlags = flags; 12263 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12264 final int N = packageActivities.size(); 12265 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 12266 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 12267 12268 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 12269 for (int i = 0; i < N; ++i) { 12270 intentFilters = packageActivities.get(i).intents; 12271 if (intentFilters != null && intentFilters.size() > 0) { 12272 PackageParser.ActivityIntentInfo[] array = 12273 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 12274 intentFilters.toArray(array); 12275 listCut.add(array); 12276 } 12277 } 12278 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12279 } 12280 12281 /** 12282 * Finds a privileged activity that matches the specified activity names. 12283 */ 12284 private PackageParser.Activity findMatchingActivity( 12285 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 12286 for (PackageParser.Activity sysActivity : activityList) { 12287 if (sysActivity.info.name.equals(activityInfo.name)) { 12288 return sysActivity; 12289 } 12290 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 12291 return sysActivity; 12292 } 12293 if (sysActivity.info.targetActivity != null) { 12294 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 12295 return sysActivity; 12296 } 12297 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 12298 return sysActivity; 12299 } 12300 } 12301 } 12302 return null; 12303 } 12304 12305 public class IterGenerator<E> { 12306 public Iterator<E> generate(ActivityIntentInfo info) { 12307 return null; 12308 } 12309 } 12310 12311 public class ActionIterGenerator extends IterGenerator<String> { 12312 @Override 12313 public Iterator<String> generate(ActivityIntentInfo info) { 12314 return info.actionsIterator(); 12315 } 12316 } 12317 12318 public class CategoriesIterGenerator extends IterGenerator<String> { 12319 @Override 12320 public Iterator<String> generate(ActivityIntentInfo info) { 12321 return info.categoriesIterator(); 12322 } 12323 } 12324 12325 public class SchemesIterGenerator extends IterGenerator<String> { 12326 @Override 12327 public Iterator<String> generate(ActivityIntentInfo info) { 12328 return info.schemesIterator(); 12329 } 12330 } 12331 12332 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 12333 @Override 12334 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 12335 return info.authoritiesIterator(); 12336 } 12337 } 12338 12339 /** 12340 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12341 * MODIFIED. Do not pass in a list that should not be changed. 12342 */ 12343 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12344 IterGenerator<T> generator, Iterator<T> searchIterator) { 12345 // loop through the set of actions; every one must be found in the intent filter 12346 while (searchIterator.hasNext()) { 12347 // we must have at least one filter in the list to consider a match 12348 if (intentList.size() == 0) { 12349 break; 12350 } 12351 12352 final T searchAction = searchIterator.next(); 12353 12354 // loop through the set of intent filters 12355 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12356 while (intentIter.hasNext()) { 12357 final ActivityIntentInfo intentInfo = intentIter.next(); 12358 boolean selectionFound = false; 12359 12360 // loop through the intent filter's selection criteria; at least one 12361 // of them must match the searched criteria 12362 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12363 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12364 final T intentSelection = intentSelectionIter.next(); 12365 if (intentSelection != null && intentSelection.equals(searchAction)) { 12366 selectionFound = true; 12367 break; 12368 } 12369 } 12370 12371 // the selection criteria wasn't found in this filter's set; this filter 12372 // is not a potential match 12373 if (!selectionFound) { 12374 intentIter.remove(); 12375 } 12376 } 12377 } 12378 } 12379 12380 private boolean isProtectedAction(ActivityIntentInfo filter) { 12381 final Iterator<String> actionsIter = filter.actionsIterator(); 12382 while (actionsIter != null && actionsIter.hasNext()) { 12383 final String filterAction = actionsIter.next(); 12384 if (PROTECTED_ACTIONS.contains(filterAction)) { 12385 return true; 12386 } 12387 } 12388 return false; 12389 } 12390 12391 /** 12392 * Adjusts the priority of the given intent filter according to policy. 12393 * <p> 12394 * <ul> 12395 * <li>The priority for non privileged applications is capped to '0'</li> 12396 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12397 * <li>The priority for unbundled updates to privileged applications is capped to the 12398 * priority defined on the system partition</li> 12399 * </ul> 12400 * <p> 12401 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12402 * allowed to obtain any priority on any action. 12403 */ 12404 private void adjustPriority( 12405 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12406 // nothing to do; priority is fine as-is 12407 if (intent.getPriority() <= 0) { 12408 return; 12409 } 12410 12411 final ActivityInfo activityInfo = intent.activity.info; 12412 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12413 12414 final boolean privilegedApp = 12415 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12416 if (!privilegedApp) { 12417 // non-privileged applications can never define a priority >0 12418 if (DEBUG_FILTERS) { 12419 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 12420 + " package: " + applicationInfo.packageName 12421 + " activity: " + intent.activity.className 12422 + " origPrio: " + intent.getPriority()); 12423 } 12424 intent.setPriority(0); 12425 return; 12426 } 12427 12428 if (systemActivities == null) { 12429 // the system package is not disabled; we're parsing the system partition 12430 if (isProtectedAction(intent)) { 12431 if (mDeferProtectedFilters) { 12432 // We can't deal with these just yet. No component should ever obtain a 12433 // >0 priority for a protected actions, with ONE exception -- the setup 12434 // wizard. The setup wizard, however, cannot be known until we're able to 12435 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12436 // until all intent filters have been processed. Chicken, meet egg. 12437 // Let the filter temporarily have a high priority and rectify the 12438 // priorities after all system packages have been scanned. 12439 mProtectedFilters.add(intent); 12440 if (DEBUG_FILTERS) { 12441 Slog.i(TAG, "Protected action; save for later;" 12442 + " package: " + applicationInfo.packageName 12443 + " activity: " + intent.activity.className 12444 + " origPrio: " + intent.getPriority()); 12445 } 12446 return; 12447 } else { 12448 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12449 Slog.i(TAG, "No setup wizard;" 12450 + " All protected intents capped to priority 0"); 12451 } 12452 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12453 if (DEBUG_FILTERS) { 12454 Slog.i(TAG, "Found setup wizard;" 12455 + " allow priority " + intent.getPriority() + ";" 12456 + " package: " + intent.activity.info.packageName 12457 + " activity: " + intent.activity.className 12458 + " priority: " + intent.getPriority()); 12459 } 12460 // setup wizard gets whatever it wants 12461 return; 12462 } 12463 if (DEBUG_FILTERS) { 12464 Slog.i(TAG, "Protected action; cap priority to 0;" 12465 + " package: " + intent.activity.info.packageName 12466 + " activity: " + intent.activity.className 12467 + " origPrio: " + intent.getPriority()); 12468 } 12469 intent.setPriority(0); 12470 return; 12471 } 12472 } 12473 // privileged apps on the system image get whatever priority they request 12474 return; 12475 } 12476 12477 // privileged app unbundled update ... try to find the same activity 12478 final PackageParser.Activity foundActivity = 12479 findMatchingActivity(systemActivities, activityInfo); 12480 if (foundActivity == null) { 12481 // this is a new activity; it cannot obtain >0 priority 12482 if (DEBUG_FILTERS) { 12483 Slog.i(TAG, "New activity; cap priority to 0;" 12484 + " package: " + applicationInfo.packageName 12485 + " activity: " + intent.activity.className 12486 + " origPrio: " + intent.getPriority()); 12487 } 12488 intent.setPriority(0); 12489 return; 12490 } 12491 12492 // found activity, now check for filter equivalence 12493 12494 // a shallow copy is enough; we modify the list, not its contents 12495 final List<ActivityIntentInfo> intentListCopy = 12496 new ArrayList<>(foundActivity.intents); 12497 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12498 12499 // find matching action subsets 12500 final Iterator<String> actionsIterator = intent.actionsIterator(); 12501 if (actionsIterator != null) { 12502 getIntentListSubset( 12503 intentListCopy, new ActionIterGenerator(), actionsIterator); 12504 if (intentListCopy.size() == 0) { 12505 // no more intents to match; we're not equivalent 12506 if (DEBUG_FILTERS) { 12507 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12508 + " package: " + applicationInfo.packageName 12509 + " activity: " + intent.activity.className 12510 + " origPrio: " + intent.getPriority()); 12511 } 12512 intent.setPriority(0); 12513 return; 12514 } 12515 } 12516 12517 // find matching category subsets 12518 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12519 if (categoriesIterator != null) { 12520 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12521 categoriesIterator); 12522 if (intentListCopy.size() == 0) { 12523 // no more intents to match; we're not equivalent 12524 if (DEBUG_FILTERS) { 12525 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12526 + " package: " + applicationInfo.packageName 12527 + " activity: " + intent.activity.className 12528 + " origPrio: " + intent.getPriority()); 12529 } 12530 intent.setPriority(0); 12531 return; 12532 } 12533 } 12534 12535 // find matching schemes subsets 12536 final Iterator<String> schemesIterator = intent.schemesIterator(); 12537 if (schemesIterator != null) { 12538 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12539 schemesIterator); 12540 if (intentListCopy.size() == 0) { 12541 // no more intents to match; we're not equivalent 12542 if (DEBUG_FILTERS) { 12543 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12544 + " package: " + applicationInfo.packageName 12545 + " activity: " + intent.activity.className 12546 + " origPrio: " + intent.getPriority()); 12547 } 12548 intent.setPriority(0); 12549 return; 12550 } 12551 } 12552 12553 // find matching authorities subsets 12554 final Iterator<IntentFilter.AuthorityEntry> 12555 authoritiesIterator = intent.authoritiesIterator(); 12556 if (authoritiesIterator != null) { 12557 getIntentListSubset(intentListCopy, 12558 new AuthoritiesIterGenerator(), 12559 authoritiesIterator); 12560 if (intentListCopy.size() == 0) { 12561 // no more intents to match; we're not equivalent 12562 if (DEBUG_FILTERS) { 12563 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12564 + " package: " + applicationInfo.packageName 12565 + " activity: " + intent.activity.className 12566 + " origPrio: " + intent.getPriority()); 12567 } 12568 intent.setPriority(0); 12569 return; 12570 } 12571 } 12572 12573 // we found matching filter(s); app gets the max priority of all intents 12574 int cappedPriority = 0; 12575 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12576 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12577 } 12578 if (intent.getPriority() > cappedPriority) { 12579 if (DEBUG_FILTERS) { 12580 Slog.i(TAG, "Found matching filter(s);" 12581 + " cap priority to " + cappedPriority + ";" 12582 + " package: " + applicationInfo.packageName 12583 + " activity: " + intent.activity.className 12584 + " origPrio: " + intent.getPriority()); 12585 } 12586 intent.setPriority(cappedPriority); 12587 return; 12588 } 12589 // all this for nothing; the requested priority was <= what was on the system 12590 } 12591 12592 public final void addActivity(PackageParser.Activity a, String type) { 12593 mActivities.put(a.getComponentName(), a); 12594 if (DEBUG_SHOW_INFO) 12595 Log.v( 12596 TAG, " " + type + " " + 12597 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12598 if (DEBUG_SHOW_INFO) 12599 Log.v(TAG, " Class=" + a.info.name); 12600 final int NI = a.intents.size(); 12601 for (int j=0; j<NI; j++) { 12602 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12603 if ("activity".equals(type)) { 12604 final PackageSetting ps = 12605 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12606 final List<PackageParser.Activity> systemActivities = 12607 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12608 adjustPriority(systemActivities, intent); 12609 } 12610 if (DEBUG_SHOW_INFO) { 12611 Log.v(TAG, " IntentFilter:"); 12612 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12613 } 12614 if (!intent.debugCheck()) { 12615 Log.w(TAG, "==> For Activity " + a.info.name); 12616 } 12617 addFilter(intent); 12618 } 12619 } 12620 12621 public final void removeActivity(PackageParser.Activity a, String type) { 12622 mActivities.remove(a.getComponentName()); 12623 if (DEBUG_SHOW_INFO) { 12624 Log.v(TAG, " " + type + " " 12625 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12626 : a.info.name) + ":"); 12627 Log.v(TAG, " Class=" + a.info.name); 12628 } 12629 final int NI = a.intents.size(); 12630 for (int j=0; j<NI; j++) { 12631 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12632 if (DEBUG_SHOW_INFO) { 12633 Log.v(TAG, " IntentFilter:"); 12634 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12635 } 12636 removeFilter(intent); 12637 } 12638 } 12639 12640 @Override 12641 protected boolean allowFilterResult( 12642 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12643 ActivityInfo filterAi = filter.activity.info; 12644 for (int i=dest.size()-1; i>=0; i--) { 12645 ActivityInfo destAi = dest.get(i).activityInfo; 12646 if (destAi.name == filterAi.name 12647 && destAi.packageName == filterAi.packageName) { 12648 return false; 12649 } 12650 } 12651 return true; 12652 } 12653 12654 @Override 12655 protected ActivityIntentInfo[] newArray(int size) { 12656 return new ActivityIntentInfo[size]; 12657 } 12658 12659 @Override 12660 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12661 if (!sUserManager.exists(userId)) return true; 12662 PackageParser.Package p = filter.activity.owner; 12663 if (p != null) { 12664 PackageSetting ps = (PackageSetting)p.mExtras; 12665 if (ps != null) { 12666 // System apps are never considered stopped for purposes of 12667 // filtering, because there may be no way for the user to 12668 // actually re-launch them. 12669 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12670 && ps.getStopped(userId); 12671 } 12672 } 12673 return false; 12674 } 12675 12676 @Override 12677 protected boolean isPackageForFilter(String packageName, 12678 PackageParser.ActivityIntentInfo info) { 12679 return packageName.equals(info.activity.owner.packageName); 12680 } 12681 12682 @Override 12683 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12684 int match, int userId) { 12685 if (!sUserManager.exists(userId)) return null; 12686 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12687 return null; 12688 } 12689 final PackageParser.Activity activity = info.activity; 12690 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12691 if (ps == null) { 12692 return null; 12693 } 12694 final PackageUserState userState = ps.readUserState(userId); 12695 ActivityInfo ai = 12696 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 12697 if (ai == null) { 12698 return null; 12699 } 12700 final boolean matchExplicitlyVisibleOnly = 12701 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12702 final boolean matchVisibleToInstantApp = 12703 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12704 final boolean componentVisible = 12705 matchVisibleToInstantApp 12706 && info.isVisibleToInstantApp() 12707 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12708 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12709 // throw out filters that aren't visible to ephemeral apps 12710 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12711 return null; 12712 } 12713 // throw out instant app filters if we're not explicitly requesting them 12714 if (!matchInstantApp && userState.instantApp) { 12715 return null; 12716 } 12717 // throw out instant app filters if updates are available; will trigger 12718 // instant app resolution 12719 if (userState.instantApp && ps.isUpdateAvailable()) { 12720 return null; 12721 } 12722 final ResolveInfo res = new ResolveInfo(); 12723 res.activityInfo = ai; 12724 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12725 res.filter = info; 12726 } 12727 if (info != null) { 12728 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12729 } 12730 res.priority = info.getPriority(); 12731 res.preferredOrder = activity.owner.mPreferredOrder; 12732 //System.out.println("Result: " + res.activityInfo.className + 12733 // " = " + res.priority); 12734 res.match = match; 12735 res.isDefault = info.hasDefault; 12736 res.labelRes = info.labelRes; 12737 res.nonLocalizedLabel = info.nonLocalizedLabel; 12738 if (userNeedsBadging(userId)) { 12739 res.noResourceId = true; 12740 } else { 12741 res.icon = info.icon; 12742 } 12743 res.iconResourceId = info.icon; 12744 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12745 res.isInstantAppAvailable = userState.instantApp; 12746 return res; 12747 } 12748 12749 @Override 12750 protected void sortResults(List<ResolveInfo> results) { 12751 Collections.sort(results, mResolvePrioritySorter); 12752 } 12753 12754 @Override 12755 protected void dumpFilter(PrintWriter out, String prefix, 12756 PackageParser.ActivityIntentInfo filter) { 12757 out.print(prefix); out.print( 12758 Integer.toHexString(System.identityHashCode(filter.activity))); 12759 out.print(' '); 12760 filter.activity.printComponentShortName(out); 12761 out.print(" filter "); 12762 out.println(Integer.toHexString(System.identityHashCode(filter))); 12763 } 12764 12765 @Override 12766 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12767 return filter.activity; 12768 } 12769 12770 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12771 PackageParser.Activity activity = (PackageParser.Activity)label; 12772 out.print(prefix); out.print( 12773 Integer.toHexString(System.identityHashCode(activity))); 12774 out.print(' '); 12775 activity.printComponentShortName(out); 12776 if (count > 1) { 12777 out.print(" ("); out.print(count); out.print(" filters)"); 12778 } 12779 out.println(); 12780 } 12781 12782 // Keys are String (activity class name), values are Activity. 12783 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12784 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12785 private int mFlags; 12786 } 12787 12788 private final class ServiceIntentResolver 12789 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12790 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12791 boolean defaultOnly, int userId) { 12792 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12793 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12794 } 12795 12796 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12797 int userId) { 12798 if (!sUserManager.exists(userId)) return null; 12799 mFlags = flags; 12800 return super.queryIntent(intent, resolvedType, 12801 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12802 userId); 12803 } 12804 12805 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12806 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12807 if (!sUserManager.exists(userId)) return null; 12808 if (packageServices == null) { 12809 return null; 12810 } 12811 mFlags = flags; 12812 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12813 final int N = packageServices.size(); 12814 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12815 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12816 12817 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12818 for (int i = 0; i < N; ++i) { 12819 intentFilters = packageServices.get(i).intents; 12820 if (intentFilters != null && intentFilters.size() > 0) { 12821 PackageParser.ServiceIntentInfo[] array = 12822 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12823 intentFilters.toArray(array); 12824 listCut.add(array); 12825 } 12826 } 12827 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12828 } 12829 12830 public final void addService(PackageParser.Service s) { 12831 mServices.put(s.getComponentName(), s); 12832 if (DEBUG_SHOW_INFO) { 12833 Log.v(TAG, " " 12834 + (s.info.nonLocalizedLabel != null 12835 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12836 Log.v(TAG, " Class=" + s.info.name); 12837 } 12838 final int NI = s.intents.size(); 12839 int j; 12840 for (j=0; j<NI; j++) { 12841 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12842 if (DEBUG_SHOW_INFO) { 12843 Log.v(TAG, " IntentFilter:"); 12844 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12845 } 12846 if (!intent.debugCheck()) { 12847 Log.w(TAG, "==> For Service " + s.info.name); 12848 } 12849 addFilter(intent); 12850 } 12851 } 12852 12853 public final void removeService(PackageParser.Service s) { 12854 mServices.remove(s.getComponentName()); 12855 if (DEBUG_SHOW_INFO) { 12856 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12857 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12858 Log.v(TAG, " Class=" + s.info.name); 12859 } 12860 final int NI = s.intents.size(); 12861 int j; 12862 for (j=0; j<NI; j++) { 12863 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12864 if (DEBUG_SHOW_INFO) { 12865 Log.v(TAG, " IntentFilter:"); 12866 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12867 } 12868 removeFilter(intent); 12869 } 12870 } 12871 12872 @Override 12873 protected boolean allowFilterResult( 12874 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12875 ServiceInfo filterSi = filter.service.info; 12876 for (int i=dest.size()-1; i>=0; i--) { 12877 ServiceInfo destAi = dest.get(i).serviceInfo; 12878 if (destAi.name == filterSi.name 12879 && destAi.packageName == filterSi.packageName) { 12880 return false; 12881 } 12882 } 12883 return true; 12884 } 12885 12886 @Override 12887 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12888 return new PackageParser.ServiceIntentInfo[size]; 12889 } 12890 12891 @Override 12892 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12893 if (!sUserManager.exists(userId)) return true; 12894 PackageParser.Package p = filter.service.owner; 12895 if (p != null) { 12896 PackageSetting ps = (PackageSetting)p.mExtras; 12897 if (ps != null) { 12898 // System apps are never considered stopped for purposes of 12899 // filtering, because there may be no way for the user to 12900 // actually re-launch them. 12901 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12902 && ps.getStopped(userId); 12903 } 12904 } 12905 return false; 12906 } 12907 12908 @Override 12909 protected boolean isPackageForFilter(String packageName, 12910 PackageParser.ServiceIntentInfo info) { 12911 return packageName.equals(info.service.owner.packageName); 12912 } 12913 12914 @Override 12915 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12916 int match, int userId) { 12917 if (!sUserManager.exists(userId)) return null; 12918 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12919 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12920 return null; 12921 } 12922 final PackageParser.Service service = info.service; 12923 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12924 if (ps == null) { 12925 return null; 12926 } 12927 final PackageUserState userState = ps.readUserState(userId); 12928 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12929 userState, userId); 12930 if (si == null) { 12931 return null; 12932 } 12933 final boolean matchVisibleToInstantApp = 12934 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12935 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12936 // throw out filters that aren't visible to ephemeral apps 12937 if (matchVisibleToInstantApp 12938 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12939 return null; 12940 } 12941 // throw out ephemeral filters if we're not explicitly requesting them 12942 if (!isInstantApp && userState.instantApp) { 12943 return null; 12944 } 12945 // throw out instant app filters if updates are available; will trigger 12946 // instant app resolution 12947 if (userState.instantApp && ps.isUpdateAvailable()) { 12948 return null; 12949 } 12950 final ResolveInfo res = new ResolveInfo(); 12951 res.serviceInfo = si; 12952 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12953 res.filter = filter; 12954 } 12955 res.priority = info.getPriority(); 12956 res.preferredOrder = service.owner.mPreferredOrder; 12957 res.match = match; 12958 res.isDefault = info.hasDefault; 12959 res.labelRes = info.labelRes; 12960 res.nonLocalizedLabel = info.nonLocalizedLabel; 12961 res.icon = info.icon; 12962 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12963 return res; 12964 } 12965 12966 @Override 12967 protected void sortResults(List<ResolveInfo> results) { 12968 Collections.sort(results, mResolvePrioritySorter); 12969 } 12970 12971 @Override 12972 protected void dumpFilter(PrintWriter out, String prefix, 12973 PackageParser.ServiceIntentInfo filter) { 12974 out.print(prefix); out.print( 12975 Integer.toHexString(System.identityHashCode(filter.service))); 12976 out.print(' '); 12977 filter.service.printComponentShortName(out); 12978 out.print(" filter "); 12979 out.print(Integer.toHexString(System.identityHashCode(filter))); 12980 if (filter.service.info.permission != null) { 12981 out.print(" permission "); out.println(filter.service.info.permission); 12982 } else { 12983 out.println(); 12984 } 12985 } 12986 12987 @Override 12988 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12989 return filter.service; 12990 } 12991 12992 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12993 PackageParser.Service service = (PackageParser.Service)label; 12994 out.print(prefix); out.print( 12995 Integer.toHexString(System.identityHashCode(service))); 12996 out.print(' '); 12997 service.printComponentShortName(out); 12998 if (count > 1) { 12999 out.print(" ("); out.print(count); out.print(" filters)"); 13000 } 13001 out.println(); 13002 } 13003 13004// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 13005// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 13006// final List<ResolveInfo> retList = Lists.newArrayList(); 13007// while (i.hasNext()) { 13008// final ResolveInfo resolveInfo = (ResolveInfo) i; 13009// if (isEnabledLP(resolveInfo.serviceInfo)) { 13010// retList.add(resolveInfo); 13011// } 13012// } 13013// return retList; 13014// } 13015 13016 // Keys are String (activity class name), values are Activity. 13017 private final ArrayMap<ComponentName, PackageParser.Service> mServices 13018 = new ArrayMap<ComponentName, PackageParser.Service>(); 13019 private int mFlags; 13020 } 13021 13022 private final class ProviderIntentResolver 13023 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 13024 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 13025 boolean defaultOnly, int userId) { 13026 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 13027 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 13028 } 13029 13030 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 13031 int userId) { 13032 if (!sUserManager.exists(userId)) 13033 return null; 13034 mFlags = flags; 13035 return super.queryIntent(intent, resolvedType, 13036 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 13037 userId); 13038 } 13039 13040 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 13041 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 13042 if (!sUserManager.exists(userId)) 13043 return null; 13044 if (packageProviders == null) { 13045 return null; 13046 } 13047 mFlags = flags; 13048 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 13049 final int N = packageProviders.size(); 13050 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 13051 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 13052 13053 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 13054 for (int i = 0; i < N; ++i) { 13055 intentFilters = packageProviders.get(i).intents; 13056 if (intentFilters != null && intentFilters.size() > 0) { 13057 PackageParser.ProviderIntentInfo[] array = 13058 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 13059 intentFilters.toArray(array); 13060 listCut.add(array); 13061 } 13062 } 13063 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 13064 } 13065 13066 public final void addProvider(PackageParser.Provider p) { 13067 if (mProviders.containsKey(p.getComponentName())) { 13068 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 13069 return; 13070 } 13071 13072 mProviders.put(p.getComponentName(), p); 13073 if (DEBUG_SHOW_INFO) { 13074 Log.v(TAG, " " 13075 + (p.info.nonLocalizedLabel != null 13076 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13077 Log.v(TAG, " Class=" + p.info.name); 13078 } 13079 final int NI = p.intents.size(); 13080 int j; 13081 for (j = 0; j < NI; j++) { 13082 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13083 if (DEBUG_SHOW_INFO) { 13084 Log.v(TAG, " IntentFilter:"); 13085 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13086 } 13087 if (!intent.debugCheck()) { 13088 Log.w(TAG, "==> For Provider " + p.info.name); 13089 } 13090 addFilter(intent); 13091 } 13092 } 13093 13094 public final void removeProvider(PackageParser.Provider p) { 13095 mProviders.remove(p.getComponentName()); 13096 if (DEBUG_SHOW_INFO) { 13097 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 13098 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13099 Log.v(TAG, " Class=" + p.info.name); 13100 } 13101 final int NI = p.intents.size(); 13102 int j; 13103 for (j = 0; j < NI; j++) { 13104 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13105 if (DEBUG_SHOW_INFO) { 13106 Log.v(TAG, " IntentFilter:"); 13107 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13108 } 13109 removeFilter(intent); 13110 } 13111 } 13112 13113 @Override 13114 protected boolean allowFilterResult( 13115 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 13116 ProviderInfo filterPi = filter.provider.info; 13117 for (int i = dest.size() - 1; i >= 0; i--) { 13118 ProviderInfo destPi = dest.get(i).providerInfo; 13119 if (destPi.name == filterPi.name 13120 && destPi.packageName == filterPi.packageName) { 13121 return false; 13122 } 13123 } 13124 return true; 13125 } 13126 13127 @Override 13128 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 13129 return new PackageParser.ProviderIntentInfo[size]; 13130 } 13131 13132 @Override 13133 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 13134 if (!sUserManager.exists(userId)) 13135 return true; 13136 PackageParser.Package p = filter.provider.owner; 13137 if (p != null) { 13138 PackageSetting ps = (PackageSetting) p.mExtras; 13139 if (ps != null) { 13140 // System apps are never considered stopped for purposes of 13141 // filtering, because there may be no way for the user to 13142 // actually re-launch them. 13143 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 13144 && ps.getStopped(userId); 13145 } 13146 } 13147 return false; 13148 } 13149 13150 @Override 13151 protected boolean isPackageForFilter(String packageName, 13152 PackageParser.ProviderIntentInfo info) { 13153 return packageName.equals(info.provider.owner.packageName); 13154 } 13155 13156 @Override 13157 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 13158 int match, int userId) { 13159 if (!sUserManager.exists(userId)) 13160 return null; 13161 final PackageParser.ProviderIntentInfo info = filter; 13162 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 13163 return null; 13164 } 13165 final PackageParser.Provider provider = info.provider; 13166 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 13167 if (ps == null) { 13168 return null; 13169 } 13170 final PackageUserState userState = ps.readUserState(userId); 13171 final boolean matchVisibleToInstantApp = 13172 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13173 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13174 // throw out filters that aren't visible to instant applications 13175 if (matchVisibleToInstantApp 13176 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 13177 return null; 13178 } 13179 // throw out instant application filters if we're not explicitly requesting them 13180 if (!isInstantApp && userState.instantApp) { 13181 return null; 13182 } 13183 // throw out instant application filters if updates are available; will trigger 13184 // instant application resolution 13185 if (userState.instantApp && ps.isUpdateAvailable()) { 13186 return null; 13187 } 13188 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 13189 userState, userId); 13190 if (pi == null) { 13191 return null; 13192 } 13193 final ResolveInfo res = new ResolveInfo(); 13194 res.providerInfo = pi; 13195 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 13196 res.filter = filter; 13197 } 13198 res.priority = info.getPriority(); 13199 res.preferredOrder = provider.owner.mPreferredOrder; 13200 res.match = match; 13201 res.isDefault = info.hasDefault; 13202 res.labelRes = info.labelRes; 13203 res.nonLocalizedLabel = info.nonLocalizedLabel; 13204 res.icon = info.icon; 13205 res.system = res.providerInfo.applicationInfo.isSystemApp(); 13206 return res; 13207 } 13208 13209 @Override 13210 protected void sortResults(List<ResolveInfo> results) { 13211 Collections.sort(results, mResolvePrioritySorter); 13212 } 13213 13214 @Override 13215 protected void dumpFilter(PrintWriter out, String prefix, 13216 PackageParser.ProviderIntentInfo filter) { 13217 out.print(prefix); 13218 out.print( 13219 Integer.toHexString(System.identityHashCode(filter.provider))); 13220 out.print(' '); 13221 filter.provider.printComponentShortName(out); 13222 out.print(" filter "); 13223 out.println(Integer.toHexString(System.identityHashCode(filter))); 13224 } 13225 13226 @Override 13227 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 13228 return filter.provider; 13229 } 13230 13231 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13232 PackageParser.Provider provider = (PackageParser.Provider)label; 13233 out.print(prefix); out.print( 13234 Integer.toHexString(System.identityHashCode(provider))); 13235 out.print(' '); 13236 provider.printComponentShortName(out); 13237 if (count > 1) { 13238 out.print(" ("); out.print(count); out.print(" filters)"); 13239 } 13240 out.println(); 13241 } 13242 13243 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 13244 = new ArrayMap<ComponentName, PackageParser.Provider>(); 13245 private int mFlags; 13246 } 13247 13248 static final class InstantAppIntentResolver 13249 extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter, 13250 AuxiliaryResolveInfo.AuxiliaryFilter> { 13251 /** 13252 * The result that has the highest defined order. Ordering applies on a 13253 * per-package basis. Mapping is from package name to Pair of order and 13254 * EphemeralResolveInfo. 13255 * <p> 13256 * NOTE: This is implemented as a field variable for convenience and efficiency. 13257 * By having a field variable, we're able to track filter ordering as soon as 13258 * a non-zero order is defined. Otherwise, multiple loops across the result set 13259 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 13260 * this needs to be contained entirely within {@link #filterResults}. 13261 */ 13262 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 13263 13264 @Override 13265 protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) { 13266 return new AuxiliaryResolveInfo.AuxiliaryFilter[size]; 13267 } 13268 13269 @Override 13270 protected boolean isPackageForFilter(String packageName, 13271 AuxiliaryResolveInfo.AuxiliaryFilter responseObj) { 13272 return true; 13273 } 13274 13275 @Override 13276 protected AuxiliaryResolveInfo.AuxiliaryFilter newResult( 13277 AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) { 13278 if (!sUserManager.exists(userId)) { 13279 return null; 13280 } 13281 final String packageName = responseObj.resolveInfo.getPackageName(); 13282 final Integer order = responseObj.getOrder(); 13283 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 13284 mOrderResult.get(packageName); 13285 // ordering is enabled and this item's order isn't high enough 13286 if (lastOrderResult != null && lastOrderResult.first >= order) { 13287 return null; 13288 } 13289 final InstantAppResolveInfo res = responseObj.resolveInfo; 13290 if (order > 0) { 13291 // non-zero order, enable ordering 13292 mOrderResult.put(packageName, new Pair<>(order, res)); 13293 } 13294 return responseObj; 13295 } 13296 13297 @Override 13298 protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) { 13299 // only do work if ordering is enabled [most of the time it won't be] 13300 if (mOrderResult.size() == 0) { 13301 return; 13302 } 13303 int resultSize = results.size(); 13304 for (int i = 0; i < resultSize; i++) { 13305 final InstantAppResolveInfo info = results.get(i).resolveInfo; 13306 final String packageName = info.getPackageName(); 13307 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 13308 if (savedInfo == null) { 13309 // package doesn't having ordering 13310 continue; 13311 } 13312 if (savedInfo.second == info) { 13313 // circled back to the highest ordered item; remove from order list 13314 mOrderResult.remove(packageName); 13315 if (mOrderResult.size() == 0) { 13316 // no more ordered items 13317 break; 13318 } 13319 continue; 13320 } 13321 // item has a worse order, remove it from the result list 13322 results.remove(i); 13323 resultSize--; 13324 i--; 13325 } 13326 } 13327 } 13328 13329 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 13330 new Comparator<ResolveInfo>() { 13331 public int compare(ResolveInfo r1, ResolveInfo r2) { 13332 int v1 = r1.priority; 13333 int v2 = r2.priority; 13334 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 13335 if (v1 != v2) { 13336 return (v1 > v2) ? -1 : 1; 13337 } 13338 v1 = r1.preferredOrder; 13339 v2 = r2.preferredOrder; 13340 if (v1 != v2) { 13341 return (v1 > v2) ? -1 : 1; 13342 } 13343 if (r1.isDefault != r2.isDefault) { 13344 return r1.isDefault ? -1 : 1; 13345 } 13346 v1 = r1.match; 13347 v2 = r2.match; 13348 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13349 if (v1 != v2) { 13350 return (v1 > v2) ? -1 : 1; 13351 } 13352 if (r1.system != r2.system) { 13353 return r1.system ? -1 : 1; 13354 } 13355 if (r1.activityInfo != null) { 13356 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13357 } 13358 if (r1.serviceInfo != null) { 13359 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13360 } 13361 if (r1.providerInfo != null) { 13362 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13363 } 13364 return 0; 13365 } 13366 }; 13367 13368 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13369 new Comparator<ProviderInfo>() { 13370 public int compare(ProviderInfo p1, ProviderInfo p2) { 13371 final int v1 = p1.initOrder; 13372 final int v2 = p2.initOrder; 13373 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13374 } 13375 }; 13376 13377 @Override 13378 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13379 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13380 final int[] userIds, int[] instantUserIds) { 13381 mHandler.post(new Runnable() { 13382 @Override 13383 public void run() { 13384 try { 13385 final IActivityManager am = ActivityManager.getService(); 13386 if (am == null) return; 13387 final int[] resolvedUserIds; 13388 if (userIds == null) { 13389 resolvedUserIds = am.getRunningUserIds(); 13390 } else { 13391 resolvedUserIds = userIds; 13392 } 13393 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13394 resolvedUserIds, false); 13395 if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) { 13396 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13397 instantUserIds, true); 13398 } 13399 } catch (RemoteException ex) { 13400 } 13401 } 13402 }); 13403 } 13404 13405 @Override 13406 public void notifyPackageAdded(String packageName) { 13407 final PackageListObserver[] observers; 13408 synchronized (mPackages) { 13409 if (mPackageListObservers.size() == 0) { 13410 return; 13411 } 13412 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13413 } 13414 for (int i = observers.length - 1; i >= 0; --i) { 13415 observers[i].onPackageAdded(packageName); 13416 } 13417 } 13418 13419 @Override 13420 public void notifyPackageRemoved(String packageName) { 13421 final PackageListObserver[] observers; 13422 synchronized (mPackages) { 13423 if (mPackageListObservers.size() == 0) { 13424 return; 13425 } 13426 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13427 } 13428 for (int i = observers.length - 1; i >= 0; --i) { 13429 observers[i].onPackageRemoved(packageName); 13430 } 13431 } 13432 13433 /** 13434 * Sends a broadcast for the given action. 13435 * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with 13436 * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows 13437 * the system and applications allowed to see instant applications to receive package 13438 * lifecycle events for instant applications. 13439 */ 13440 private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras, 13441 int flags, String targetPkg, IIntentReceiver finishedReceiver, 13442 int[] userIds, boolean isInstantApp) 13443 throws RemoteException { 13444 for (int id : userIds) { 13445 final Intent intent = new Intent(action, 13446 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13447 final String[] requiredPermissions = 13448 isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null; 13449 if (extras != null) { 13450 intent.putExtras(extras); 13451 } 13452 if (targetPkg != null) { 13453 intent.setPackage(targetPkg); 13454 } 13455 // Modify the UID when posting to other users 13456 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13457 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13458 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13459 intent.putExtra(Intent.EXTRA_UID, uid); 13460 } 13461 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13462 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13463 if (DEBUG_BROADCASTS) { 13464 RuntimeException here = new RuntimeException("here"); 13465 here.fillInStackTrace(); 13466 Slog.d(TAG, "Sending to user " + id + ": " 13467 + intent.toShortString(false, true, false, false) 13468 + " " + intent.getExtras(), here); 13469 } 13470 am.broadcastIntent(null, intent, null, finishedReceiver, 13471 0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE, 13472 null, finishedReceiver != null, false, id); 13473 } 13474 } 13475 13476 /** 13477 * Check if the external storage media is available. This is true if there 13478 * is a mounted external storage medium or if the external storage is 13479 * emulated. 13480 */ 13481 private boolean isExternalMediaAvailable() { 13482 return mMediaMounted || Environment.isExternalStorageEmulated(); 13483 } 13484 13485 @Override 13486 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13487 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 13488 return null; 13489 } 13490 if (!isExternalMediaAvailable()) { 13491 // If the external storage is no longer mounted at this point, 13492 // the caller may not have been able to delete all of this 13493 // packages files and can not delete any more. Bail. 13494 return null; 13495 } 13496 synchronized (mPackages) { 13497 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13498 if (lastPackage != null) { 13499 pkgs.remove(lastPackage); 13500 } 13501 if (pkgs.size() > 0) { 13502 return pkgs.get(0); 13503 } 13504 } 13505 return null; 13506 } 13507 13508 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13509 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13510 userId, andCode ? 1 : 0, packageName); 13511 if (mSystemReady) { 13512 msg.sendToTarget(); 13513 } else { 13514 if (mPostSystemReadyMessages == null) { 13515 mPostSystemReadyMessages = new ArrayList<>(); 13516 } 13517 mPostSystemReadyMessages.add(msg); 13518 } 13519 } 13520 13521 void startCleaningPackages() { 13522 // reader 13523 if (!isExternalMediaAvailable()) { 13524 return; 13525 } 13526 synchronized (mPackages) { 13527 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13528 return; 13529 } 13530 } 13531 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13532 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13533 IActivityManager am = ActivityManager.getService(); 13534 if (am != null) { 13535 int dcsUid = -1; 13536 synchronized (mPackages) { 13537 if (!mDefaultContainerWhitelisted) { 13538 mDefaultContainerWhitelisted = true; 13539 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13540 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13541 } 13542 } 13543 try { 13544 if (dcsUid > 0) { 13545 am.backgroundWhitelistUid(dcsUid); 13546 } 13547 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13548 UserHandle.USER_SYSTEM); 13549 } catch (RemoteException e) { 13550 } 13551 } 13552 } 13553 13554 /** 13555 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13556 * it is acting on behalf on an enterprise or the user). 13557 * 13558 * Note that the ordering of the conditionals in this method is important. The checks we perform 13559 * are as follows, in this order: 13560 * 13561 * 1) If the install is being performed by a system app, we can trust the app to have set the 13562 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13563 * what it is. 13564 * 2) If the install is being performed by a device or profile owner app, the install reason 13565 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13566 * set the install reason correctly. If the app targets an older SDK version where install 13567 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13568 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13569 * 3) In all other cases, the install is being performed by a regular app that is neither part 13570 * of the system nor a device or profile owner. We have no reason to believe that this app is 13571 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13572 * set to enterprise policy and if so, change it to unknown instead. 13573 */ 13574 private int fixUpInstallReason(String installerPackageName, int installerUid, 13575 int installReason) { 13576 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13577 == PERMISSION_GRANTED) { 13578 // If the install is being performed by a system app, we trust that app to have set the 13579 // install reason correctly. 13580 return installReason; 13581 } 13582 13583 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13584 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13585 if (dpm != null) { 13586 ComponentName owner = null; 13587 try { 13588 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13589 if (owner == null) { 13590 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13591 } 13592 } catch (RemoteException e) { 13593 } 13594 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13595 // If the install is being performed by a device or profile owner, the install 13596 // reason should be enterprise policy. 13597 return PackageManager.INSTALL_REASON_POLICY; 13598 } 13599 } 13600 13601 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13602 // If the install is being performed by a regular app (i.e. neither system app nor 13603 // device or profile owner), we have no reason to believe that the app is acting on 13604 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13605 // change it to unknown instead. 13606 return PackageManager.INSTALL_REASON_UNKNOWN; 13607 } 13608 13609 // If the install is being performed by a regular app and the install reason was set to any 13610 // value but enterprise policy, leave the install reason unchanged. 13611 return installReason; 13612 } 13613 13614 void installStage(String packageName, File stagedDir, 13615 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13616 String installerPackageName, int installerUid, UserHandle user, 13617 PackageParser.SigningDetails signingDetails) { 13618 if (DEBUG_INSTANT) { 13619 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13620 Slog.d(TAG, "Ephemeral install of " + packageName); 13621 } 13622 } 13623 final VerificationInfo verificationInfo = new VerificationInfo( 13624 sessionParams.originatingUri, sessionParams.referrerUri, 13625 sessionParams.originatingUid, installerUid); 13626 13627 final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir); 13628 13629 final Message msg = mHandler.obtainMessage(INIT_COPY); 13630 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13631 sessionParams.installReason); 13632 final InstallParams params = new InstallParams(origin, null, observer, 13633 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13634 verificationInfo, user, sessionParams.abiOverride, 13635 sessionParams.grantedRuntimePermissions, signingDetails, installReason); 13636 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13637 msg.obj = params; 13638 13639 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13640 System.identityHashCode(msg.obj)); 13641 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13642 System.identityHashCode(msg.obj)); 13643 13644 mHandler.sendMessage(msg); 13645 } 13646 13647 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13648 int userId) { 13649 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13650 final boolean isInstantApp = pkgSetting.getInstantApp(userId); 13651 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 13652 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 13653 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 13654 false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds); 13655 13656 // Send a session commit broadcast 13657 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 13658 info.installReason = pkgSetting.getInstallReason(userId); 13659 info.appPackageName = packageName; 13660 sendSessionCommitBroadcast(info, userId); 13661 } 13662 13663 @Override 13664 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 13665 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) { 13666 if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) { 13667 return; 13668 } 13669 Bundle extras = new Bundle(1); 13670 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13671 final int uid = UserHandle.getUid( 13672 (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId); 13673 extras.putInt(Intent.EXTRA_UID, uid); 13674 13675 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13676 packageName, extras, 0, null, null, userIds, instantUserIds); 13677 if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) { 13678 mHandler.post(() -> { 13679 for (int userId : userIds) { 13680 sendBootCompletedBroadcastToSystemApp( 13681 packageName, includeStopped, userId); 13682 } 13683 } 13684 ); 13685 } 13686 } 13687 13688 /** 13689 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13690 * automatically without needing an explicit launch. 13691 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13692 */ 13693 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 13694 int userId) { 13695 // If user is not running, the app didn't miss any broadcast 13696 if (!mUserManagerInternal.isUserRunning(userId)) { 13697 return; 13698 } 13699 final IActivityManager am = ActivityManager.getService(); 13700 try { 13701 // Deliver LOCKED_BOOT_COMPLETED first 13702 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13703 .setPackage(packageName); 13704 if (includeStopped) { 13705 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13706 } 13707 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13708 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13709 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13710 13711 // Deliver BOOT_COMPLETED only if user is unlocked 13712 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13713 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13714 if (includeStopped) { 13715 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13716 } 13717 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13718 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13719 } 13720 } catch (RemoteException e) { 13721 throw e.rethrowFromSystemServer(); 13722 } 13723 } 13724 13725 @Override 13726 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13727 int userId) { 13728 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13729 PackageSetting pkgSetting; 13730 final int callingUid = Binder.getCallingUid(); 13731 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13732 true /* requireFullPermission */, true /* checkShell */, 13733 "setApplicationHiddenSetting for user " + userId); 13734 13735 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13736 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13737 return false; 13738 } 13739 13740 long callingId = Binder.clearCallingIdentity(); 13741 try { 13742 boolean sendAdded = false; 13743 boolean sendRemoved = false; 13744 // writer 13745 synchronized (mPackages) { 13746 pkgSetting = mSettings.mPackages.get(packageName); 13747 if (pkgSetting == null) { 13748 return false; 13749 } 13750 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13751 return false; 13752 } 13753 // Do not allow "android" is being disabled 13754 if ("android".equals(packageName)) { 13755 Slog.w(TAG, "Cannot hide package: android"); 13756 return false; 13757 } 13758 // Cannot hide static shared libs as they are considered 13759 // a part of the using app (emulating static linking). Also 13760 // static libs are installed always on internal storage. 13761 PackageParser.Package pkg = mPackages.get(packageName); 13762 if (pkg != null && pkg.staticSharedLibName != null) { 13763 Slog.w(TAG, "Cannot hide package: " + packageName 13764 + " providing static shared library: " 13765 + pkg.staticSharedLibName); 13766 return false; 13767 } 13768 // Only allow protected packages to hide themselves. 13769 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 13770 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13771 Slog.w(TAG, "Not hiding protected package: " + packageName); 13772 return false; 13773 } 13774 13775 if (pkgSetting.getHidden(userId) != hidden) { 13776 pkgSetting.setHidden(hidden, userId); 13777 mSettings.writePackageRestrictionsLPr(userId); 13778 if (hidden) { 13779 sendRemoved = true; 13780 } else { 13781 sendAdded = true; 13782 } 13783 } 13784 } 13785 if (sendAdded) { 13786 sendPackageAddedForUser(packageName, pkgSetting, userId); 13787 return true; 13788 } 13789 if (sendRemoved) { 13790 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13791 "hiding pkg"); 13792 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13793 return true; 13794 } 13795 } finally { 13796 Binder.restoreCallingIdentity(callingId); 13797 } 13798 return false; 13799 } 13800 13801 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13802 int userId) { 13803 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13804 info.removedPackage = packageName; 13805 info.installerPackageName = pkgSetting.installerPackageName; 13806 info.removedUsers = new int[] {userId}; 13807 info.broadcastUsers = new int[] {userId}; 13808 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13809 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13810 } 13811 13812 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13813 if (pkgList.length > 0) { 13814 Bundle extras = new Bundle(1); 13815 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13816 13817 sendPackageBroadcast( 13818 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13819 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13820 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13821 new int[] {userId}, null); 13822 } 13823 } 13824 13825 /** 13826 * Returns true if application is not found or there was an error. Otherwise it returns 13827 * the hidden state of the package for the given user. 13828 */ 13829 @Override 13830 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13831 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13832 final int callingUid = Binder.getCallingUid(); 13833 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13834 true /* requireFullPermission */, false /* checkShell */, 13835 "getApplicationHidden for user " + userId); 13836 PackageSetting ps; 13837 long callingId = Binder.clearCallingIdentity(); 13838 try { 13839 // writer 13840 synchronized (mPackages) { 13841 ps = mSettings.mPackages.get(packageName); 13842 if (ps == null) { 13843 return true; 13844 } 13845 if (filterAppAccessLPr(ps, callingUid, userId)) { 13846 return true; 13847 } 13848 return ps.getHidden(userId); 13849 } 13850 } finally { 13851 Binder.restoreCallingIdentity(callingId); 13852 } 13853 } 13854 13855 /** 13856 * @hide 13857 */ 13858 @Override 13859 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13860 int installReason) { 13861 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13862 null); 13863 PackageSetting pkgSetting; 13864 final int callingUid = Binder.getCallingUid(); 13865 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13866 true /* requireFullPermission */, true /* checkShell */, 13867 "installExistingPackage for user " + userId); 13868 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13869 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13870 } 13871 13872 long callingId = Binder.clearCallingIdentity(); 13873 try { 13874 boolean installed = false; 13875 final boolean instantApp = 13876 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13877 final boolean fullApp = 13878 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13879 13880 // writer 13881 synchronized (mPackages) { 13882 pkgSetting = mSettings.mPackages.get(packageName); 13883 if (pkgSetting == null) { 13884 return PackageManager.INSTALL_FAILED_INVALID_URI; 13885 } 13886 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 13887 // only allow the existing package to be used if it's installed as a full 13888 // application for at least one user 13889 boolean installAllowed = false; 13890 for (int checkUserId : sUserManager.getUserIds()) { 13891 installAllowed = !pkgSetting.getInstantApp(checkUserId); 13892 if (installAllowed) { 13893 break; 13894 } 13895 } 13896 if (!installAllowed) { 13897 return PackageManager.INSTALL_FAILED_INVALID_URI; 13898 } 13899 } 13900 if (!pkgSetting.getInstalled(userId)) { 13901 pkgSetting.setInstalled(true, userId); 13902 pkgSetting.setHidden(false, userId); 13903 pkgSetting.setInstallReason(installReason, userId); 13904 mSettings.writePackageRestrictionsLPr(userId); 13905 mSettings.writeKernelMappingLPr(pkgSetting); 13906 installed = true; 13907 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13908 // upgrade app from instant to full; we don't allow app downgrade 13909 installed = true; 13910 } 13911 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13912 } 13913 13914 if (installed) { 13915 if (pkgSetting.pkg != null) { 13916 synchronized (mInstallLock) { 13917 // We don't need to freeze for a brand new install 13918 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13919 } 13920 } 13921 sendPackageAddedForUser(packageName, pkgSetting, userId); 13922 synchronized (mPackages) { 13923 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 13924 } 13925 } 13926 } finally { 13927 Binder.restoreCallingIdentity(callingId); 13928 } 13929 13930 return PackageManager.INSTALL_SUCCEEDED; 13931 } 13932 13933 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13934 boolean instantApp, boolean fullApp) { 13935 // no state specified; do nothing 13936 if (!instantApp && !fullApp) { 13937 return; 13938 } 13939 if (userId != UserHandle.USER_ALL) { 13940 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13941 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13942 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13943 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13944 } 13945 } else { 13946 for (int currentUserId : sUserManager.getUserIds()) { 13947 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13948 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13949 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13950 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13951 } 13952 } 13953 } 13954 } 13955 13956 boolean isUserRestricted(int userId, String restrictionKey) { 13957 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13958 if (restrictions.getBoolean(restrictionKey, false)) { 13959 Log.w(TAG, "User is restricted: " + restrictionKey); 13960 return true; 13961 } 13962 return false; 13963 } 13964 13965 @Override 13966 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13967 PersistableBundle appExtras, PersistableBundle launcherExtras, String callingPackage, 13968 int userId) { 13969 try { 13970 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null); 13971 } catch (SecurityException e) { 13972 mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS, 13973 "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or " 13974 + Manifest.permission.MANAGE_USERS); 13975 } 13976 final int callingUid = Binder.getCallingUid(); 13977 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13978 true /* requireFullPermission */, true /* checkShell */, 13979 "setPackagesSuspended for user " + userId); 13980 if (callingUid != Process.ROOT_UID && 13981 !UserHandle.isSameApp(getPackageUid(callingPackage, 0, userId), callingUid)) { 13982 throw new IllegalArgumentException("callingPackage " + callingPackage + " does not" 13983 + " belong to calling app id " + UserHandle.getAppId(callingUid)); 13984 } 13985 13986 if (ArrayUtils.isEmpty(packageNames)) { 13987 return packageNames; 13988 } 13989 13990 // List of package names for whom the suspended state has changed. 13991 final List<String> changedPackages = new ArrayList<>(packageNames.length); 13992 // List of package names for whom the suspended state is not set as requested in this 13993 // method. 13994 final List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13995 final long callingId = Binder.clearCallingIdentity(); 13996 try { 13997 synchronized (mPackages) { 13998 for (int i = 0; i < packageNames.length; i++) { 13999 final String packageName = packageNames[i]; 14000 if (packageName == callingPackage) { 14001 Slog.w(TAG, "Calling package: " + callingPackage + "trying to " 14002 + (suspended ? "" : "un") + "suspend itself. Ignoring"); 14003 unactionedPackages.add(packageName); 14004 continue; 14005 } 14006 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 14007 if (pkgSetting == null 14008 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 14009 Slog.w(TAG, "Could not find package setting for package \"" + packageName 14010 + "\". Skipping suspending/un-suspending."); 14011 unactionedPackages.add(packageName); 14012 continue; 14013 } 14014 if (pkgSetting.getSuspended(userId) != suspended) { 14015 if (!canSuspendPackageForUserLocked(packageName, userId)) { 14016 unactionedPackages.add(packageName); 14017 continue; 14018 } 14019 pkgSetting.setSuspended(suspended, callingPackage, appExtras, 14020 launcherExtras, userId); 14021 changedPackages.add(packageName); 14022 } 14023 } 14024 } 14025 } finally { 14026 Binder.restoreCallingIdentity(callingId); 14027 } 14028 // TODO (b/75036698): Also send each package a broadcast when suspended state changed 14029 if (!changedPackages.isEmpty()) { 14030 sendPackagesSuspendedForUser(changedPackages.toArray( 14031 new String[changedPackages.size()]), userId, suspended); 14032 synchronized (mPackages) { 14033 scheduleWritePackageRestrictionsLocked(userId); 14034 } 14035 } 14036 14037 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 14038 } 14039 14040 @Override 14041 public PersistableBundle getPackageSuspendedAppExtras(String packageName, int userId) { 14042 final int callingUid = Binder.getCallingUid(); 14043 if (getPackageUid(packageName, 0, userId) != callingUid) { 14044 mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null); 14045 } 14046 synchronized (mPackages) { 14047 final PackageSetting ps = mSettings.mPackages.get(packageName); 14048 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 14049 throw new IllegalArgumentException("Unknown target package: " + packageName); 14050 } 14051 final PackageUserState packageUserState = ps.readUserState(userId); 14052 return packageUserState.suspended ? packageUserState.suspendedAppExtras : null; 14053 } 14054 } 14055 14056 @Override 14057 public void setSuspendedPackageAppExtras(String packageName, PersistableBundle appExtras, 14058 int userId) { 14059 final int callingUid = Binder.getCallingUid(); 14060 mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null); 14061 synchronized (mPackages) { 14062 final PackageSetting ps = mSettings.mPackages.get(packageName); 14063 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 14064 throw new IllegalArgumentException("Unknown target package: " + packageName); 14065 } 14066 final PackageUserState packageUserState = ps.readUserState(userId); 14067 if (packageUserState.suspended) { 14068 // TODO (b/75036698): Also send this package a broadcast with the new app extras 14069 packageUserState.suspendedAppExtras = appExtras; 14070 } 14071 } 14072 } 14073 14074 @Override 14075 public boolean isPackageSuspendedForUser(String packageName, int userId) { 14076 final int callingUid = Binder.getCallingUid(); 14077 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 14078 true /* requireFullPermission */, false /* checkShell */, 14079 "isPackageSuspendedForUser for user " + userId); 14080 if (getPackageUid(packageName, 0, userId) != callingUid) { 14081 mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null); 14082 } 14083 synchronized (mPackages) { 14084 final PackageSetting ps = mSettings.mPackages.get(packageName); 14085 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 14086 throw new IllegalArgumentException("Unknown target package: " + packageName); 14087 } 14088 return ps.getSuspended(userId); 14089 } 14090 } 14091 14092 void onSuspendingPackageRemoved(String packageName, int userId) { 14093 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 14094 : new int[] {userId}; 14095 synchronized (mPackages) { 14096 for (PackageSetting ps : mSettings.mPackages.values()) { 14097 for (int user : userIds) { 14098 final PackageUserState pus = ps.readUserState(user); 14099 if (pus.suspended && packageName.equals(pus.suspendingPackage)) { 14100 ps.setSuspended(false, null, null, null, user); 14101 } 14102 } 14103 } 14104 } 14105 } 14106 14107 @GuardedBy("mPackages") 14108 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 14109 if (isPackageDeviceAdmin(packageName, userId)) { 14110 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14111 + "\": has an active device admin"); 14112 return false; 14113 } 14114 14115 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 14116 if (packageName.equals(activeLauncherPackageName)) { 14117 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14118 + "\": contains the active launcher"); 14119 return false; 14120 } 14121 14122 if (packageName.equals(mRequiredInstallerPackage)) { 14123 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14124 + "\": required for package installation"); 14125 return false; 14126 } 14127 14128 if (packageName.equals(mRequiredUninstallerPackage)) { 14129 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14130 + "\": required for package uninstallation"); 14131 return false; 14132 } 14133 14134 if (packageName.equals(mRequiredVerifierPackage)) { 14135 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14136 + "\": required for package verification"); 14137 return false; 14138 } 14139 14140 if (packageName.equals(getDefaultDialerPackageName(userId))) { 14141 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14142 + "\": is the default dialer"); 14143 return false; 14144 } 14145 14146 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 14147 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14148 + "\": protected package"); 14149 return false; 14150 } 14151 14152 // Cannot suspend static shared libs as they are considered 14153 // a part of the using app (emulating static linking). Also 14154 // static libs are installed always on internal storage. 14155 PackageParser.Package pkg = mPackages.get(packageName); 14156 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 14157 Slog.w(TAG, "Cannot suspend package: " + packageName 14158 + " providing static shared library: " 14159 + pkg.staticSharedLibName); 14160 return false; 14161 } 14162 14163 if (PLATFORM_PACKAGE_NAME.equals(packageName)) { 14164 Slog.w(TAG, "Cannot suspend package: " + packageName); 14165 return false; 14166 } 14167 14168 return true; 14169 } 14170 14171 private String getActiveLauncherPackageName(int userId) { 14172 Intent intent = new Intent(Intent.ACTION_MAIN); 14173 intent.addCategory(Intent.CATEGORY_HOME); 14174 ResolveInfo resolveInfo = resolveIntent( 14175 intent, 14176 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 14177 PackageManager.MATCH_DEFAULT_ONLY, 14178 userId); 14179 14180 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 14181 } 14182 14183 private String getDefaultDialerPackageName(int userId) { 14184 synchronized (mPackages) { 14185 return mSettings.getDefaultDialerPackageNameLPw(userId); 14186 } 14187 } 14188 14189 @Override 14190 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 14191 mContext.enforceCallingOrSelfPermission( 14192 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14193 "Only package verification agents can verify applications"); 14194 14195 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14196 final PackageVerificationResponse response = new PackageVerificationResponse( 14197 verificationCode, Binder.getCallingUid()); 14198 msg.arg1 = id; 14199 msg.obj = response; 14200 mHandler.sendMessage(msg); 14201 } 14202 14203 @Override 14204 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 14205 long millisecondsToDelay) { 14206 mContext.enforceCallingOrSelfPermission( 14207 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14208 "Only package verification agents can extend verification timeouts"); 14209 14210 final PackageVerificationState state = mPendingVerification.get(id); 14211 final PackageVerificationResponse response = new PackageVerificationResponse( 14212 verificationCodeAtTimeout, Binder.getCallingUid()); 14213 14214 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 14215 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 14216 } 14217 if (millisecondsToDelay < 0) { 14218 millisecondsToDelay = 0; 14219 } 14220 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 14221 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 14222 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 14223 } 14224 14225 if ((state != null) && !state.timeoutExtended()) { 14226 state.extendTimeout(); 14227 14228 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14229 msg.arg1 = id; 14230 msg.obj = response; 14231 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 14232 } 14233 } 14234 14235 private void broadcastPackageVerified(int verificationId, Uri packageUri, 14236 int verificationCode, UserHandle user) { 14237 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 14238 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 14239 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14240 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14241 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 14242 14243 mContext.sendBroadcastAsUser(intent, user, 14244 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 14245 } 14246 14247 private ComponentName matchComponentForVerifier(String packageName, 14248 List<ResolveInfo> receivers) { 14249 ActivityInfo targetReceiver = null; 14250 14251 final int NR = receivers.size(); 14252 for (int i = 0; i < NR; i++) { 14253 final ResolveInfo info = receivers.get(i); 14254 if (info.activityInfo == null) { 14255 continue; 14256 } 14257 14258 if (packageName.equals(info.activityInfo.packageName)) { 14259 targetReceiver = info.activityInfo; 14260 break; 14261 } 14262 } 14263 14264 if (targetReceiver == null) { 14265 return null; 14266 } 14267 14268 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 14269 } 14270 14271 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 14272 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 14273 if (pkgInfo.verifiers.length == 0) { 14274 return null; 14275 } 14276 14277 final int N = pkgInfo.verifiers.length; 14278 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 14279 for (int i = 0; i < N; i++) { 14280 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 14281 14282 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 14283 receivers); 14284 if (comp == null) { 14285 continue; 14286 } 14287 14288 final int verifierUid = getUidForVerifier(verifierInfo); 14289 if (verifierUid == -1) { 14290 continue; 14291 } 14292 14293 if (DEBUG_VERIFY) { 14294 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 14295 + " with the correct signature"); 14296 } 14297 sufficientVerifiers.add(comp); 14298 verificationState.addSufficientVerifier(verifierUid); 14299 } 14300 14301 return sufficientVerifiers; 14302 } 14303 14304 private int getUidForVerifier(VerifierInfo verifierInfo) { 14305 synchronized (mPackages) { 14306 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 14307 if (pkg == null) { 14308 return -1; 14309 } else if (pkg.mSigningDetails.signatures.length != 1) { 14310 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14311 + " has more than one signature; ignoring"); 14312 return -1; 14313 } 14314 14315 /* 14316 * If the public key of the package's signature does not match 14317 * our expected public key, then this is a different package and 14318 * we should skip. 14319 */ 14320 14321 final byte[] expectedPublicKey; 14322 try { 14323 final Signature verifierSig = pkg.mSigningDetails.signatures[0]; 14324 final PublicKey publicKey = verifierSig.getPublicKey(); 14325 expectedPublicKey = publicKey.getEncoded(); 14326 } catch (CertificateException e) { 14327 return -1; 14328 } 14329 14330 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 14331 14332 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 14333 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14334 + " does not have the expected public key; ignoring"); 14335 return -1; 14336 } 14337 14338 return pkg.applicationInfo.uid; 14339 } 14340 } 14341 14342 @Override 14343 public void finishPackageInstall(int token, boolean didLaunch) { 14344 enforceSystemOrRoot("Only the system is allowed to finish installs"); 14345 14346 if (DEBUG_INSTALL) { 14347 Slog.v(TAG, "BM finishing package install for " + token); 14348 } 14349 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14350 14351 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 14352 mHandler.sendMessage(msg); 14353 } 14354 14355 /** 14356 * Get the verification agent timeout. Used for both the APK verifier and the 14357 * intent filter verifier. 14358 * 14359 * @return verification timeout in milliseconds 14360 */ 14361 private long getVerificationTimeout() { 14362 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 14363 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 14364 DEFAULT_VERIFICATION_TIMEOUT); 14365 } 14366 14367 /** 14368 * Get the default verification agent response code. 14369 * 14370 * @return default verification response code 14371 */ 14372 private int getDefaultVerificationResponse(UserHandle user) { 14373 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 14374 return PackageManager.VERIFICATION_REJECT; 14375 } 14376 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14377 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 14378 DEFAULT_VERIFICATION_RESPONSE); 14379 } 14380 14381 /** 14382 * Check whether or not package verification has been enabled. 14383 * 14384 * @return true if verification should be performed 14385 */ 14386 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 14387 if (!DEFAULT_VERIFY_ENABLE) { 14388 return false; 14389 } 14390 14391 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14392 14393 // Check if installing from ADB 14394 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14395 // Do not run verification in a test harness environment 14396 if (ActivityManager.isRunningInTestHarness()) { 14397 return false; 14398 } 14399 if (ensureVerifyAppsEnabled) { 14400 return true; 14401 } 14402 // Check if the developer does not want package verification for ADB installs 14403 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14404 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14405 return false; 14406 } 14407 } else { 14408 // only when not installed from ADB, skip verification for instant apps when 14409 // the installer and verifier are the same. 14410 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14411 if (mInstantAppInstallerActivity != null 14412 && mInstantAppInstallerActivity.packageName.equals( 14413 mRequiredVerifierPackage)) { 14414 try { 14415 mContext.getSystemService(AppOpsManager.class) 14416 .checkPackage(installerUid, mRequiredVerifierPackage); 14417 if (DEBUG_VERIFY) { 14418 Slog.i(TAG, "disable verification for instant app"); 14419 } 14420 return false; 14421 } catch (SecurityException ignore) { } 14422 } 14423 } 14424 } 14425 14426 if (ensureVerifyAppsEnabled) { 14427 return true; 14428 } 14429 14430 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14431 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14432 } 14433 14434 @Override 14435 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14436 throws RemoteException { 14437 mContext.enforceCallingOrSelfPermission( 14438 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14439 "Only intentfilter verification agents can verify applications"); 14440 14441 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14442 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14443 Binder.getCallingUid(), verificationCode, failedDomains); 14444 msg.arg1 = id; 14445 msg.obj = response; 14446 mHandler.sendMessage(msg); 14447 } 14448 14449 @Override 14450 public int getIntentVerificationStatus(String packageName, int userId) { 14451 final int callingUid = Binder.getCallingUid(); 14452 if (UserHandle.getUserId(callingUid) != userId) { 14453 mContext.enforceCallingOrSelfPermission( 14454 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14455 "getIntentVerificationStatus" + userId); 14456 } 14457 if (getInstantAppPackageName(callingUid) != null) { 14458 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14459 } 14460 synchronized (mPackages) { 14461 final PackageSetting ps = mSettings.mPackages.get(packageName); 14462 if (ps == null 14463 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14464 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14465 } 14466 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14467 } 14468 } 14469 14470 @Override 14471 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14472 mContext.enforceCallingOrSelfPermission( 14473 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14474 14475 boolean result = false; 14476 synchronized (mPackages) { 14477 final PackageSetting ps = mSettings.mPackages.get(packageName); 14478 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14479 return false; 14480 } 14481 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14482 } 14483 if (result) { 14484 scheduleWritePackageRestrictionsLocked(userId); 14485 } 14486 return result; 14487 } 14488 14489 @Override 14490 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14491 String packageName) { 14492 final int callingUid = Binder.getCallingUid(); 14493 if (getInstantAppPackageName(callingUid) != null) { 14494 return ParceledListSlice.emptyList(); 14495 } 14496 synchronized (mPackages) { 14497 final PackageSetting ps = mSettings.mPackages.get(packageName); 14498 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14499 return ParceledListSlice.emptyList(); 14500 } 14501 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14502 } 14503 } 14504 14505 @Override 14506 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14507 if (TextUtils.isEmpty(packageName)) { 14508 return ParceledListSlice.emptyList(); 14509 } 14510 final int callingUid = Binder.getCallingUid(); 14511 final int callingUserId = UserHandle.getUserId(callingUid); 14512 synchronized (mPackages) { 14513 PackageParser.Package pkg = mPackages.get(packageName); 14514 if (pkg == null || pkg.activities == null) { 14515 return ParceledListSlice.emptyList(); 14516 } 14517 if (pkg.mExtras == null) { 14518 return ParceledListSlice.emptyList(); 14519 } 14520 final PackageSetting ps = (PackageSetting) pkg.mExtras; 14521 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 14522 return ParceledListSlice.emptyList(); 14523 } 14524 final int count = pkg.activities.size(); 14525 ArrayList<IntentFilter> result = new ArrayList<>(); 14526 for (int n=0; n<count; n++) { 14527 PackageParser.Activity activity = pkg.activities.get(n); 14528 if (activity.intents != null && activity.intents.size() > 0) { 14529 result.addAll(activity.intents); 14530 } 14531 } 14532 return new ParceledListSlice<>(result); 14533 } 14534 } 14535 14536 @Override 14537 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14538 mContext.enforceCallingOrSelfPermission( 14539 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14540 if (UserHandle.getCallingUserId() != userId) { 14541 mContext.enforceCallingOrSelfPermission( 14542 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14543 } 14544 14545 synchronized (mPackages) { 14546 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14547 if (packageName != null) { 14548 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser( 14549 packageName, userId); 14550 } 14551 return result; 14552 } 14553 } 14554 14555 @Override 14556 public String getDefaultBrowserPackageName(int userId) { 14557 if (UserHandle.getCallingUserId() != userId) { 14558 mContext.enforceCallingOrSelfPermission( 14559 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14560 } 14561 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14562 return null; 14563 } 14564 synchronized (mPackages) { 14565 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14566 } 14567 } 14568 14569 /** 14570 * Get the "allow unknown sources" setting. 14571 * 14572 * @return the current "allow unknown sources" setting 14573 */ 14574 private int getUnknownSourcesSettings() { 14575 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14576 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14577 -1); 14578 } 14579 14580 @Override 14581 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14582 final int callingUid = Binder.getCallingUid(); 14583 if (getInstantAppPackageName(callingUid) != null) { 14584 return; 14585 } 14586 // writer 14587 synchronized (mPackages) { 14588 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14589 if (targetPackageSetting == null 14590 || filterAppAccessLPr( 14591 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 14592 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14593 } 14594 14595 PackageSetting installerPackageSetting; 14596 if (installerPackageName != null) { 14597 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14598 if (installerPackageSetting == null) { 14599 throw new IllegalArgumentException("Unknown installer package: " 14600 + installerPackageName); 14601 } 14602 } else { 14603 installerPackageSetting = null; 14604 } 14605 14606 Signature[] callerSignature; 14607 Object obj = mSettings.getUserIdLPr(callingUid); 14608 if (obj != null) { 14609 if (obj instanceof SharedUserSetting) { 14610 callerSignature = 14611 ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 14612 } else if (obj instanceof PackageSetting) { 14613 callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures; 14614 } else { 14615 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 14616 } 14617 } else { 14618 throw new SecurityException("Unknown calling UID: " + callingUid); 14619 } 14620 14621 // Verify: can't set installerPackageName to a package that is 14622 // not signed with the same cert as the caller. 14623 if (installerPackageSetting != null) { 14624 if (compareSignatures(callerSignature, 14625 installerPackageSetting.signatures.mSigningDetails.signatures) 14626 != PackageManager.SIGNATURE_MATCH) { 14627 throw new SecurityException( 14628 "Caller does not have same cert as new installer package " 14629 + installerPackageName); 14630 } 14631 } 14632 14633 // Verify: if target already has an installer package, it must 14634 // be signed with the same cert as the caller. 14635 if (targetPackageSetting.installerPackageName != null) { 14636 PackageSetting setting = mSettings.mPackages.get( 14637 targetPackageSetting.installerPackageName); 14638 // If the currently set package isn't valid, then it's always 14639 // okay to change it. 14640 if (setting != null) { 14641 if (compareSignatures(callerSignature, 14642 setting.signatures.mSigningDetails.signatures) 14643 != PackageManager.SIGNATURE_MATCH) { 14644 throw new SecurityException( 14645 "Caller does not have same cert as old installer package " 14646 + targetPackageSetting.installerPackageName); 14647 } 14648 } 14649 } 14650 14651 // Okay! 14652 targetPackageSetting.installerPackageName = installerPackageName; 14653 if (installerPackageName != null) { 14654 mSettings.mInstallerPackages.add(installerPackageName); 14655 } 14656 scheduleWriteSettingsLocked(); 14657 } 14658 } 14659 14660 @Override 14661 public void setApplicationCategoryHint(String packageName, int categoryHint, 14662 String callerPackageName) { 14663 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14664 throw new SecurityException("Instant applications don't have access to this method"); 14665 } 14666 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14667 callerPackageName); 14668 synchronized (mPackages) { 14669 PackageSetting ps = mSettings.mPackages.get(packageName); 14670 if (ps == null) { 14671 throw new IllegalArgumentException("Unknown target package " + packageName); 14672 } 14673 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14674 throw new IllegalArgumentException("Unknown target package " + packageName); 14675 } 14676 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14677 throw new IllegalArgumentException("Calling package " + callerPackageName 14678 + " is not installer for " + packageName); 14679 } 14680 14681 if (ps.categoryHint != categoryHint) { 14682 ps.categoryHint = categoryHint; 14683 scheduleWriteSettingsLocked(); 14684 } 14685 } 14686 } 14687 14688 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14689 // Queue up an async operation since the package installation may take a little while. 14690 mHandler.post(new Runnable() { 14691 public void run() { 14692 mHandler.removeCallbacks(this); 14693 // Result object to be returned 14694 PackageInstalledInfo res = new PackageInstalledInfo(); 14695 res.setReturnCode(currentStatus); 14696 res.uid = -1; 14697 res.pkg = null; 14698 res.removedInfo = null; 14699 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14700 args.doPreInstall(res.returnCode); 14701 synchronized (mInstallLock) { 14702 installPackageTracedLI(args, res); 14703 } 14704 args.doPostInstall(res.returnCode, res.uid); 14705 } 14706 14707 // A restore should be performed at this point if (a) the install 14708 // succeeded, (b) the operation is not an update, and (c) the new 14709 // package has not opted out of backup participation. 14710 final boolean update = res.removedInfo != null 14711 && res.removedInfo.removedPackage != null; 14712 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14713 boolean doRestore = !update 14714 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14715 14716 // Set up the post-install work request bookkeeping. This will be used 14717 // and cleaned up by the post-install event handling regardless of whether 14718 // there's a restore pass performed. Token values are >= 1. 14719 int token; 14720 if (mNextInstallToken < 0) mNextInstallToken = 1; 14721 token = mNextInstallToken++; 14722 14723 PostInstallData data = new PostInstallData(args, res); 14724 mRunningInstalls.put(token, data); 14725 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14726 14727 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14728 // Pass responsibility to the Backup Manager. It will perform a 14729 // restore if appropriate, then pass responsibility back to the 14730 // Package Manager to run the post-install observer callbacks 14731 // and broadcasts. 14732 IBackupManager bm = IBackupManager.Stub.asInterface( 14733 ServiceManager.getService(Context.BACKUP_SERVICE)); 14734 if (bm != null) { 14735 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14736 + " to BM for possible restore"); 14737 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14738 try { 14739 // TODO: http://b/22388012 14740 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14741 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14742 } else { 14743 doRestore = false; 14744 } 14745 } catch (RemoteException e) { 14746 // can't happen; the backup manager is local 14747 } catch (Exception e) { 14748 Slog.e(TAG, "Exception trying to enqueue restore", e); 14749 doRestore = false; 14750 } 14751 } else { 14752 Slog.e(TAG, "Backup Manager not found!"); 14753 doRestore = false; 14754 } 14755 } 14756 14757 if (!doRestore) { 14758 // No restore possible, or the Backup Manager was mysteriously not 14759 // available -- just fire the post-install work request directly. 14760 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14761 14762 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14763 14764 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14765 mHandler.sendMessage(msg); 14766 } 14767 } 14768 }); 14769 } 14770 14771 /** 14772 * Callback from PackageSettings whenever an app is first transitioned out of the 14773 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14774 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14775 * here whether the app is the target of an ongoing install, and only send the 14776 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14777 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14778 * handling. 14779 */ 14780 void notifyFirstLaunch(final String packageName, final String installerPackage, 14781 final int userId) { 14782 // Serialize this with the rest of the install-process message chain. In the 14783 // restore-at-install case, this Runnable will necessarily run before the 14784 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14785 // are coherent. In the non-restore case, the app has already completed install 14786 // and been launched through some other means, so it is not in a problematic 14787 // state for observers to see the FIRST_LAUNCH signal. 14788 mHandler.post(new Runnable() { 14789 @Override 14790 public void run() { 14791 for (int i = 0; i < mRunningInstalls.size(); i++) { 14792 final PostInstallData data = mRunningInstalls.valueAt(i); 14793 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14794 continue; 14795 } 14796 if (packageName.equals(data.res.pkg.applicationInfo.packageName)) { 14797 // right package; but is it for the right user? 14798 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14799 if (userId == data.res.newUsers[uIndex]) { 14800 if (DEBUG_BACKUP) { 14801 Slog.i(TAG, "Package " + packageName 14802 + " being restored so deferring FIRST_LAUNCH"); 14803 } 14804 return; 14805 } 14806 } 14807 } 14808 } 14809 // didn't find it, so not being restored 14810 if (DEBUG_BACKUP) { 14811 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH"); 14812 } 14813 final boolean isInstantApp = isInstantApp(packageName, userId); 14814 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 14815 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 14816 sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds); 14817 } 14818 }); 14819 } 14820 14821 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, 14822 int[] userIds, int[] instantUserIds) { 14823 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14824 installerPkg, null, userIds, instantUserIds); 14825 } 14826 14827 private abstract class HandlerParams { 14828 private static final int MAX_RETRIES = 4; 14829 14830 /** 14831 * Number of times startCopy() has been attempted and had a non-fatal 14832 * error. 14833 */ 14834 private int mRetries = 0; 14835 14836 /** User handle for the user requesting the information or installation. */ 14837 private final UserHandle mUser; 14838 String traceMethod; 14839 int traceCookie; 14840 14841 HandlerParams(UserHandle user) { 14842 mUser = user; 14843 } 14844 14845 UserHandle getUser() { 14846 return mUser; 14847 } 14848 14849 HandlerParams setTraceMethod(String traceMethod) { 14850 this.traceMethod = traceMethod; 14851 return this; 14852 } 14853 14854 HandlerParams setTraceCookie(int traceCookie) { 14855 this.traceCookie = traceCookie; 14856 return this; 14857 } 14858 14859 final boolean startCopy() { 14860 boolean res; 14861 try { 14862 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14863 14864 if (++mRetries > MAX_RETRIES) { 14865 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14866 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14867 handleServiceError(); 14868 return false; 14869 } else { 14870 handleStartCopy(); 14871 res = true; 14872 } 14873 } catch (RemoteException e) { 14874 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14875 mHandler.sendEmptyMessage(MCS_RECONNECT); 14876 res = false; 14877 } 14878 handleReturnCode(); 14879 return res; 14880 } 14881 14882 final void serviceError() { 14883 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14884 handleServiceError(); 14885 handleReturnCode(); 14886 } 14887 14888 abstract void handleStartCopy() throws RemoteException; 14889 abstract void handleServiceError(); 14890 abstract void handleReturnCode(); 14891 } 14892 14893 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14894 for (File path : paths) { 14895 try { 14896 mcs.clearDirectory(path.getAbsolutePath()); 14897 } catch (RemoteException e) { 14898 } 14899 } 14900 } 14901 14902 static class OriginInfo { 14903 /** 14904 * Location where install is coming from, before it has been 14905 * copied/renamed into place. This could be a single monolithic APK 14906 * file, or a cluster directory. This location may be untrusted. 14907 */ 14908 final File file; 14909 14910 /** 14911 * Flag indicating that {@link #file} or {@link #cid} has already been 14912 * staged, meaning downstream users don't need to defensively copy the 14913 * contents. 14914 */ 14915 final boolean staged; 14916 14917 /** 14918 * Flag indicating that {@link #file} or {@link #cid} is an already 14919 * installed app that is being moved. 14920 */ 14921 final boolean existing; 14922 14923 final String resolvedPath; 14924 final File resolvedFile; 14925 14926 static OriginInfo fromNothing() { 14927 return new OriginInfo(null, false, false); 14928 } 14929 14930 static OriginInfo fromUntrustedFile(File file) { 14931 return new OriginInfo(file, false, false); 14932 } 14933 14934 static OriginInfo fromExistingFile(File file) { 14935 return new OriginInfo(file, false, true); 14936 } 14937 14938 static OriginInfo fromStagedFile(File file) { 14939 return new OriginInfo(file, true, false); 14940 } 14941 14942 private OriginInfo(File file, boolean staged, boolean existing) { 14943 this.file = file; 14944 this.staged = staged; 14945 this.existing = existing; 14946 14947 if (file != null) { 14948 resolvedPath = file.getAbsolutePath(); 14949 resolvedFile = file; 14950 } else { 14951 resolvedPath = null; 14952 resolvedFile = null; 14953 } 14954 } 14955 } 14956 14957 static class MoveInfo { 14958 final int moveId; 14959 final String fromUuid; 14960 final String toUuid; 14961 final String packageName; 14962 final String dataAppName; 14963 final int appId; 14964 final String seinfo; 14965 final int targetSdkVersion; 14966 14967 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14968 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14969 this.moveId = moveId; 14970 this.fromUuid = fromUuid; 14971 this.toUuid = toUuid; 14972 this.packageName = packageName; 14973 this.dataAppName = dataAppName; 14974 this.appId = appId; 14975 this.seinfo = seinfo; 14976 this.targetSdkVersion = targetSdkVersion; 14977 } 14978 } 14979 14980 static class VerificationInfo { 14981 /** A constant used to indicate that a uid value is not present. */ 14982 public static final int NO_UID = -1; 14983 14984 /** URI referencing where the package was downloaded from. */ 14985 final Uri originatingUri; 14986 14987 /** HTTP referrer URI associated with the originatingURI. */ 14988 final Uri referrer; 14989 14990 /** UID of the application that the install request originated from. */ 14991 final int originatingUid; 14992 14993 /** UID of application requesting the install */ 14994 final int installerUid; 14995 14996 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14997 this.originatingUri = originatingUri; 14998 this.referrer = referrer; 14999 this.originatingUid = originatingUid; 15000 this.installerUid = installerUid; 15001 } 15002 } 15003 15004 class InstallParams extends HandlerParams { 15005 final OriginInfo origin; 15006 final MoveInfo move; 15007 final IPackageInstallObserver2 observer; 15008 int installFlags; 15009 final String installerPackageName; 15010 final String volumeUuid; 15011 private InstallArgs mArgs; 15012 private int mRet; 15013 final String packageAbiOverride; 15014 final String[] grantedRuntimePermissions; 15015 final VerificationInfo verificationInfo; 15016 final PackageParser.SigningDetails signingDetails; 15017 final int installReason; 15018 15019 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15020 int installFlags, String installerPackageName, String volumeUuid, 15021 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 15022 String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) { 15023 super(user); 15024 this.origin = origin; 15025 this.move = move; 15026 this.observer = observer; 15027 this.installFlags = installFlags; 15028 this.installerPackageName = installerPackageName; 15029 this.volumeUuid = volumeUuid; 15030 this.verificationInfo = verificationInfo; 15031 this.packageAbiOverride = packageAbiOverride; 15032 this.grantedRuntimePermissions = grantedPermissions; 15033 this.signingDetails = signingDetails; 15034 this.installReason = installReason; 15035 } 15036 15037 @Override 15038 public String toString() { 15039 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 15040 + " file=" + origin.file + "}"; 15041 } 15042 15043 private int installLocationPolicy(PackageInfoLite pkgLite) { 15044 String packageName = pkgLite.packageName; 15045 int installLocation = pkgLite.installLocation; 15046 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15047 // reader 15048 synchronized (mPackages) { 15049 // Currently installed package which the new package is attempting to replace or 15050 // null if no such package is installed. 15051 PackageParser.Package installedPkg = mPackages.get(packageName); 15052 // Package which currently owns the data which the new package will own if installed. 15053 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 15054 // will be null whereas dataOwnerPkg will contain information about the package 15055 // which was uninstalled while keeping its data. 15056 PackageParser.Package dataOwnerPkg = installedPkg; 15057 if (dataOwnerPkg == null) { 15058 PackageSetting ps = mSettings.mPackages.get(packageName); 15059 if (ps != null) { 15060 dataOwnerPkg = ps.pkg; 15061 } 15062 } 15063 15064 if (dataOwnerPkg != null) { 15065 // If installed, the package will get access to data left on the device by its 15066 // predecessor. As a security measure, this is permited only if this is not a 15067 // version downgrade or if the predecessor package is marked as debuggable and 15068 // a downgrade is explicitly requested. 15069 // 15070 // On debuggable platform builds, downgrades are permitted even for 15071 // non-debuggable packages to make testing easier. Debuggable platform builds do 15072 // not offer security guarantees and thus it's OK to disable some security 15073 // mechanisms to make debugging/testing easier on those builds. However, even on 15074 // debuggable builds downgrades of packages are permitted only if requested via 15075 // installFlags. This is because we aim to keep the behavior of debuggable 15076 // platform builds as close as possible to the behavior of non-debuggable 15077 // platform builds. 15078 final boolean downgradeRequested = 15079 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 15080 final boolean packageDebuggable = 15081 (dataOwnerPkg.applicationInfo.flags 15082 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 15083 final boolean downgradePermitted = 15084 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 15085 if (!downgradePermitted) { 15086 try { 15087 checkDowngrade(dataOwnerPkg, pkgLite); 15088 } catch (PackageManagerException e) { 15089 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 15090 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 15091 } 15092 } 15093 } 15094 15095 if (installedPkg != null) { 15096 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15097 // Check for updated system application. 15098 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15099 if (onSd) { 15100 Slog.w(TAG, "Cannot install update to system app on sdcard"); 15101 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 15102 } 15103 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15104 } else { 15105 if (onSd) { 15106 // Install flag overrides everything. 15107 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15108 } 15109 // If current upgrade specifies particular preference 15110 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 15111 // Application explicitly specified internal. 15112 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15113 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 15114 // App explictly prefers external. Let policy decide 15115 } else { 15116 // Prefer previous location 15117 if (isExternal(installedPkg)) { 15118 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15119 } 15120 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15121 } 15122 } 15123 } else { 15124 // Invalid install. Return error code 15125 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 15126 } 15127 } 15128 } 15129 // All the special cases have been taken care of. 15130 // Return result based on recommended install location. 15131 if (onSd) { 15132 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15133 } 15134 return pkgLite.recommendedInstallLocation; 15135 } 15136 15137 /* 15138 * Invoke remote method to get package information and install 15139 * location values. Override install location based on default 15140 * policy if needed and then create install arguments based 15141 * on the install location. 15142 */ 15143 public void handleStartCopy() throws RemoteException { 15144 int ret = PackageManager.INSTALL_SUCCEEDED; 15145 15146 // If we're already staged, we've firmly committed to an install location 15147 if (origin.staged) { 15148 if (origin.file != null) { 15149 installFlags |= PackageManager.INSTALL_INTERNAL; 15150 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15151 } else { 15152 throw new IllegalStateException("Invalid stage location"); 15153 } 15154 } 15155 15156 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15157 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 15158 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15159 PackageInfoLite pkgLite = null; 15160 15161 if (onInt && onSd) { 15162 // Check if both bits are set. 15163 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 15164 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15165 } else if (onSd && ephemeral) { 15166 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 15167 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15168 } else { 15169 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 15170 packageAbiOverride); 15171 15172 if (DEBUG_INSTANT && ephemeral) { 15173 Slog.v(TAG, "pkgLite for install: " + pkgLite); 15174 } 15175 15176 /* 15177 * If we have too little free space, try to free cache 15178 * before giving up. 15179 */ 15180 if (!origin.staged && pkgLite.recommendedInstallLocation 15181 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15182 // TODO: focus freeing disk space on the target device 15183 final StorageManager storage = StorageManager.from(mContext); 15184 final long lowThreshold = storage.getStorageLowBytes( 15185 Environment.getDataDirectory()); 15186 15187 final long sizeBytes = mContainerService.calculateInstalledSize( 15188 origin.resolvedPath, packageAbiOverride); 15189 15190 try { 15191 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 15192 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 15193 installFlags, packageAbiOverride); 15194 } catch (InstallerException e) { 15195 Slog.w(TAG, "Failed to free cache", e); 15196 } 15197 15198 /* 15199 * The cache free must have deleted the file we 15200 * downloaded to install. 15201 * 15202 * TODO: fix the "freeCache" call to not delete 15203 * the file we care about. 15204 */ 15205 if (pkgLite.recommendedInstallLocation 15206 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15207 pkgLite.recommendedInstallLocation 15208 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 15209 } 15210 } 15211 } 15212 15213 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15214 int loc = pkgLite.recommendedInstallLocation; 15215 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 15216 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15217 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 15218 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 15219 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15220 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15221 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 15222 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 15223 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15224 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 15225 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 15226 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 15227 } else { 15228 // Override with defaults if needed. 15229 loc = installLocationPolicy(pkgLite); 15230 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 15231 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 15232 } else if (!onSd && !onInt) { 15233 // Override install location with flags 15234 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 15235 // Set the flag to install on external media. 15236 installFlags |= PackageManager.INSTALL_EXTERNAL; 15237 installFlags &= ~PackageManager.INSTALL_INTERNAL; 15238 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 15239 if (DEBUG_INSTANT) { 15240 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 15241 } 15242 installFlags |= PackageManager.INSTALL_INSTANT_APP; 15243 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 15244 |PackageManager.INSTALL_INTERNAL); 15245 } else { 15246 // Make sure the flag for installing on external 15247 // media is unset 15248 installFlags |= PackageManager.INSTALL_INTERNAL; 15249 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15250 } 15251 } 15252 } 15253 } 15254 15255 final InstallArgs args = createInstallArgs(this); 15256 mArgs = args; 15257 15258 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15259 // TODO: http://b/22976637 15260 // Apps installed for "all" users use the device owner to verify the app 15261 UserHandle verifierUser = getUser(); 15262 if (verifierUser == UserHandle.ALL) { 15263 verifierUser = UserHandle.SYSTEM; 15264 } 15265 15266 /* 15267 * Determine if we have any installed package verifiers. If we 15268 * do, then we'll defer to them to verify the packages. 15269 */ 15270 final int requiredUid = mRequiredVerifierPackage == null ? -1 15271 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15272 verifierUser.getIdentifier()); 15273 final int installerUid = 15274 verificationInfo == null ? -1 : verificationInfo.installerUid; 15275 if (!origin.existing && requiredUid != -1 15276 && isVerificationEnabled( 15277 verifierUser.getIdentifier(), installFlags, installerUid)) { 15278 final Intent verification = new Intent( 15279 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 15280 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 15281 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 15282 PACKAGE_MIME_TYPE); 15283 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15284 15285 // Query all live verifiers based on current user state 15286 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 15287 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 15288 false /*allowDynamicSplits*/); 15289 15290 if (DEBUG_VERIFY) { 15291 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 15292 + verification.toString() + " with " + pkgLite.verifiers.length 15293 + " optional verifiers"); 15294 } 15295 15296 final int verificationId = mPendingVerificationToken++; 15297 15298 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 15299 15300 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 15301 installerPackageName); 15302 15303 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 15304 installFlags); 15305 15306 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 15307 pkgLite.packageName); 15308 15309 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 15310 pkgLite.versionCode); 15311 15312 verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE, 15313 pkgLite.getLongVersionCode()); 15314 15315 if (verificationInfo != null) { 15316 if (verificationInfo.originatingUri != null) { 15317 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 15318 verificationInfo.originatingUri); 15319 } 15320 if (verificationInfo.referrer != null) { 15321 verification.putExtra(Intent.EXTRA_REFERRER, 15322 verificationInfo.referrer); 15323 } 15324 if (verificationInfo.originatingUid >= 0) { 15325 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 15326 verificationInfo.originatingUid); 15327 } 15328 if (verificationInfo.installerUid >= 0) { 15329 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 15330 verificationInfo.installerUid); 15331 } 15332 } 15333 15334 final PackageVerificationState verificationState = new PackageVerificationState( 15335 requiredUid, args); 15336 15337 mPendingVerification.append(verificationId, verificationState); 15338 15339 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 15340 receivers, verificationState); 15341 15342 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 15343 final long idleDuration = getVerificationTimeout(); 15344 15345 /* 15346 * If any sufficient verifiers were listed in the package 15347 * manifest, attempt to ask them. 15348 */ 15349 if (sufficientVerifiers != null) { 15350 final int N = sufficientVerifiers.size(); 15351 if (N == 0) { 15352 Slog.i(TAG, "Additional verifiers required, but none installed."); 15353 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 15354 } else { 15355 for (int i = 0; i < N; i++) { 15356 final ComponentName verifierComponent = sufficientVerifiers.get(i); 15357 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15358 verifierComponent.getPackageName(), idleDuration, 15359 verifierUser.getIdentifier(), false, "package verifier"); 15360 15361 final Intent sufficientIntent = new Intent(verification); 15362 sufficientIntent.setComponent(verifierComponent); 15363 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 15364 } 15365 } 15366 } 15367 15368 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 15369 mRequiredVerifierPackage, receivers); 15370 if (ret == PackageManager.INSTALL_SUCCEEDED 15371 && mRequiredVerifierPackage != null) { 15372 Trace.asyncTraceBegin( 15373 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 15374 /* 15375 * Send the intent to the required verification agent, 15376 * but only start the verification timeout after the 15377 * target BroadcastReceivers have run. 15378 */ 15379 verification.setComponent(requiredVerifierComponent); 15380 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15381 mRequiredVerifierPackage, idleDuration, 15382 verifierUser.getIdentifier(), false, "package verifier"); 15383 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 15384 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15385 new BroadcastReceiver() { 15386 @Override 15387 public void onReceive(Context context, Intent intent) { 15388 final Message msg = mHandler 15389 .obtainMessage(CHECK_PENDING_VERIFICATION); 15390 msg.arg1 = verificationId; 15391 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15392 } 15393 }, null, 0, null, null); 15394 15395 /* 15396 * We don't want the copy to proceed until verification 15397 * succeeds, so null out this field. 15398 */ 15399 mArgs = null; 15400 } 15401 } else { 15402 /* 15403 * No package verification is enabled, so immediately start 15404 * the remote call to initiate copy using temporary file. 15405 */ 15406 ret = args.copyApk(mContainerService, true); 15407 } 15408 } 15409 15410 mRet = ret; 15411 } 15412 15413 @Override 15414 void handleReturnCode() { 15415 // If mArgs is null, then MCS couldn't be reached. When it 15416 // reconnects, it will try again to install. At that point, this 15417 // will succeed. 15418 if (mArgs != null) { 15419 processPendingInstall(mArgs, mRet); 15420 } 15421 } 15422 15423 @Override 15424 void handleServiceError() { 15425 mArgs = createInstallArgs(this); 15426 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15427 } 15428 } 15429 15430 private InstallArgs createInstallArgs(InstallParams params) { 15431 if (params.move != null) { 15432 return new MoveInstallArgs(params); 15433 } else { 15434 return new FileInstallArgs(params); 15435 } 15436 } 15437 15438 /** 15439 * Create args that describe an existing installed package. Typically used 15440 * when cleaning up old installs, or used as a move source. 15441 */ 15442 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 15443 String resourcePath, String[] instructionSets) { 15444 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15445 } 15446 15447 static abstract class InstallArgs { 15448 /** @see InstallParams#origin */ 15449 final OriginInfo origin; 15450 /** @see InstallParams#move */ 15451 final MoveInfo move; 15452 15453 final IPackageInstallObserver2 observer; 15454 // Always refers to PackageManager flags only 15455 final int installFlags; 15456 final String installerPackageName; 15457 final String volumeUuid; 15458 final UserHandle user; 15459 final String abiOverride; 15460 final String[] installGrantPermissions; 15461 /** If non-null, drop an async trace when the install completes */ 15462 final String traceMethod; 15463 final int traceCookie; 15464 final PackageParser.SigningDetails signingDetails; 15465 final int installReason; 15466 15467 // The list of instruction sets supported by this app. This is currently 15468 // only used during the rmdex() phase to clean up resources. We can get rid of this 15469 // if we move dex files under the common app path. 15470 /* nullable */ String[] instructionSets; 15471 15472 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15473 int installFlags, String installerPackageName, String volumeUuid, 15474 UserHandle user, String[] instructionSets, 15475 String abiOverride, String[] installGrantPermissions, 15476 String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails, 15477 int installReason) { 15478 this.origin = origin; 15479 this.move = move; 15480 this.installFlags = installFlags; 15481 this.observer = observer; 15482 this.installerPackageName = installerPackageName; 15483 this.volumeUuid = volumeUuid; 15484 this.user = user; 15485 this.instructionSets = instructionSets; 15486 this.abiOverride = abiOverride; 15487 this.installGrantPermissions = installGrantPermissions; 15488 this.traceMethod = traceMethod; 15489 this.traceCookie = traceCookie; 15490 this.signingDetails = signingDetails; 15491 this.installReason = installReason; 15492 } 15493 15494 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15495 abstract int doPreInstall(int status); 15496 15497 /** 15498 * Rename package into final resting place. All paths on the given 15499 * scanned package should be updated to reflect the rename. 15500 */ 15501 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15502 abstract int doPostInstall(int status, int uid); 15503 15504 /** @see PackageSettingBase#codePathString */ 15505 abstract String getCodePath(); 15506 /** @see PackageSettingBase#resourcePathString */ 15507 abstract String getResourcePath(); 15508 15509 // Need installer lock especially for dex file removal. 15510 abstract void cleanUpResourcesLI(); 15511 abstract boolean doPostDeleteLI(boolean delete); 15512 15513 /** 15514 * Called before the source arguments are copied. This is used mostly 15515 * for MoveParams when it needs to read the source file to put it in the 15516 * destination. 15517 */ 15518 int doPreCopy() { 15519 return PackageManager.INSTALL_SUCCEEDED; 15520 } 15521 15522 /** 15523 * Called after the source arguments are copied. This is used mostly for 15524 * MoveParams when it needs to read the source file to put it in the 15525 * destination. 15526 */ 15527 int doPostCopy(int uid) { 15528 return PackageManager.INSTALL_SUCCEEDED; 15529 } 15530 15531 protected boolean isFwdLocked() { 15532 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15533 } 15534 15535 protected boolean isExternalAsec() { 15536 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15537 } 15538 15539 protected boolean isEphemeral() { 15540 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15541 } 15542 15543 UserHandle getUser() { 15544 return user; 15545 } 15546 } 15547 15548 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15549 if (!allCodePaths.isEmpty()) { 15550 if (instructionSets == null) { 15551 throw new IllegalStateException("instructionSet == null"); 15552 } 15553 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15554 for (String codePath : allCodePaths) { 15555 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15556 try { 15557 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15558 } catch (InstallerException ignored) { 15559 } 15560 } 15561 } 15562 } 15563 } 15564 15565 /** 15566 * Logic to handle installation of non-ASEC applications, including copying 15567 * and renaming logic. 15568 */ 15569 class FileInstallArgs extends InstallArgs { 15570 private File codeFile; 15571 private File resourceFile; 15572 15573 // Example topology: 15574 // /data/app/com.example/base.apk 15575 // /data/app/com.example/split_foo.apk 15576 // /data/app/com.example/lib/arm/libfoo.so 15577 // /data/app/com.example/lib/arm64/libfoo.so 15578 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15579 15580 /** New install */ 15581 FileInstallArgs(InstallParams params) { 15582 super(params.origin, params.move, params.observer, params.installFlags, 15583 params.installerPackageName, params.volumeUuid, 15584 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15585 params.grantedRuntimePermissions, 15586 params.traceMethod, params.traceCookie, params.signingDetails, 15587 params.installReason); 15588 if (isFwdLocked()) { 15589 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15590 } 15591 } 15592 15593 /** Existing install */ 15594 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15595 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15596 null, null, null, 0, PackageParser.SigningDetails.UNKNOWN, 15597 PackageManager.INSTALL_REASON_UNKNOWN); 15598 this.codeFile = (codePath != null) ? new File(codePath) : null; 15599 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15600 } 15601 15602 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15603 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15604 try { 15605 return doCopyApk(imcs, temp); 15606 } finally { 15607 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15608 } 15609 } 15610 15611 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15612 if (origin.staged) { 15613 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15614 codeFile = origin.file; 15615 resourceFile = origin.file; 15616 return PackageManager.INSTALL_SUCCEEDED; 15617 } 15618 15619 try { 15620 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15621 final File tempDir = 15622 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15623 codeFile = tempDir; 15624 resourceFile = tempDir; 15625 } catch (IOException e) { 15626 Slog.w(TAG, "Failed to create copy file: " + e); 15627 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15628 } 15629 15630 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15631 @Override 15632 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15633 if (!FileUtils.isValidExtFilename(name)) { 15634 throw new IllegalArgumentException("Invalid filename: " + name); 15635 } 15636 try { 15637 final File file = new File(codeFile, name); 15638 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15639 O_RDWR | O_CREAT, 0644); 15640 Os.chmod(file.getAbsolutePath(), 0644); 15641 return new ParcelFileDescriptor(fd); 15642 } catch (ErrnoException e) { 15643 throw new RemoteException("Failed to open: " + e.getMessage()); 15644 } 15645 } 15646 }; 15647 15648 int ret = PackageManager.INSTALL_SUCCEEDED; 15649 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15650 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15651 Slog.e(TAG, "Failed to copy package"); 15652 return ret; 15653 } 15654 15655 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15656 NativeLibraryHelper.Handle handle = null; 15657 try { 15658 handle = NativeLibraryHelper.Handle.create(codeFile); 15659 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15660 abiOverride); 15661 } catch (IOException e) { 15662 Slog.e(TAG, "Copying native libraries failed", e); 15663 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15664 } finally { 15665 IoUtils.closeQuietly(handle); 15666 } 15667 15668 return ret; 15669 } 15670 15671 int doPreInstall(int status) { 15672 if (status != PackageManager.INSTALL_SUCCEEDED) { 15673 cleanUp(); 15674 } 15675 return status; 15676 } 15677 15678 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15679 if (status != PackageManager.INSTALL_SUCCEEDED) { 15680 cleanUp(); 15681 return false; 15682 } 15683 15684 final File targetDir = codeFile.getParentFile(); 15685 final File beforeCodeFile = codeFile; 15686 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15687 15688 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15689 try { 15690 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15691 } catch (ErrnoException e) { 15692 Slog.w(TAG, "Failed to rename", e); 15693 return false; 15694 } 15695 15696 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15697 Slog.w(TAG, "Failed to restorecon"); 15698 return false; 15699 } 15700 15701 // Reflect the rename internally 15702 codeFile = afterCodeFile; 15703 resourceFile = afterCodeFile; 15704 15705 // Reflect the rename in scanned details 15706 try { 15707 pkg.setCodePath(afterCodeFile.getCanonicalPath()); 15708 } catch (IOException e) { 15709 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e); 15710 return false; 15711 } 15712 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15713 afterCodeFile, pkg.baseCodePath)); 15714 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15715 afterCodeFile, pkg.splitCodePaths)); 15716 15717 // Reflect the rename in app info 15718 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15719 pkg.setApplicationInfoCodePath(pkg.codePath); 15720 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15721 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15722 pkg.setApplicationInfoResourcePath(pkg.codePath); 15723 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15724 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15725 15726 return true; 15727 } 15728 15729 int doPostInstall(int status, int uid) { 15730 if (status != PackageManager.INSTALL_SUCCEEDED) { 15731 cleanUp(); 15732 } 15733 return status; 15734 } 15735 15736 @Override 15737 String getCodePath() { 15738 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15739 } 15740 15741 @Override 15742 String getResourcePath() { 15743 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15744 } 15745 15746 private boolean cleanUp() { 15747 if (codeFile == null || !codeFile.exists()) { 15748 return false; 15749 } 15750 15751 removeCodePathLI(codeFile); 15752 15753 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15754 resourceFile.delete(); 15755 } 15756 15757 return true; 15758 } 15759 15760 void cleanUpResourcesLI() { 15761 // Try enumerating all code paths before deleting 15762 List<String> allCodePaths = Collections.EMPTY_LIST; 15763 if (codeFile != null && codeFile.exists()) { 15764 try { 15765 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15766 allCodePaths = pkg.getAllCodePaths(); 15767 } catch (PackageParserException e) { 15768 // Ignored; we tried our best 15769 } 15770 } 15771 15772 cleanUp(); 15773 removeDexFiles(allCodePaths, instructionSets); 15774 } 15775 15776 boolean doPostDeleteLI(boolean delete) { 15777 // XXX err, shouldn't we respect the delete flag? 15778 cleanUpResourcesLI(); 15779 return true; 15780 } 15781 } 15782 15783 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15784 PackageManagerException { 15785 if (copyRet < 0) { 15786 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15787 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15788 throw new PackageManagerException(copyRet, message); 15789 } 15790 } 15791 } 15792 15793 /** 15794 * Extract the StorageManagerService "container ID" from the full code path of an 15795 * .apk. 15796 */ 15797 static String cidFromCodePath(String fullCodePath) { 15798 int eidx = fullCodePath.lastIndexOf("/"); 15799 String subStr1 = fullCodePath.substring(0, eidx); 15800 int sidx = subStr1.lastIndexOf("/"); 15801 return subStr1.substring(sidx+1, eidx); 15802 } 15803 15804 /** 15805 * Logic to handle movement of existing installed applications. 15806 */ 15807 class MoveInstallArgs extends InstallArgs { 15808 private File codeFile; 15809 private File resourceFile; 15810 15811 /** New install */ 15812 MoveInstallArgs(InstallParams params) { 15813 super(params.origin, params.move, params.observer, params.installFlags, 15814 params.installerPackageName, params.volumeUuid, 15815 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15816 params.grantedRuntimePermissions, 15817 params.traceMethod, params.traceCookie, params.signingDetails, 15818 params.installReason); 15819 } 15820 15821 int copyApk(IMediaContainerService imcs, boolean temp) { 15822 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15823 + move.fromUuid + " to " + move.toUuid); 15824 synchronized (mInstaller) { 15825 try { 15826 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15827 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15828 } catch (InstallerException e) { 15829 Slog.w(TAG, "Failed to move app", e); 15830 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15831 } 15832 } 15833 15834 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15835 resourceFile = codeFile; 15836 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15837 15838 return PackageManager.INSTALL_SUCCEEDED; 15839 } 15840 15841 int doPreInstall(int status) { 15842 if (status != PackageManager.INSTALL_SUCCEEDED) { 15843 cleanUp(move.toUuid); 15844 } 15845 return status; 15846 } 15847 15848 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15849 if (status != PackageManager.INSTALL_SUCCEEDED) { 15850 cleanUp(move.toUuid); 15851 return false; 15852 } 15853 15854 // Reflect the move in app info 15855 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15856 pkg.setApplicationInfoCodePath(pkg.codePath); 15857 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15858 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15859 pkg.setApplicationInfoResourcePath(pkg.codePath); 15860 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15861 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15862 15863 return true; 15864 } 15865 15866 int doPostInstall(int status, int uid) { 15867 if (status == PackageManager.INSTALL_SUCCEEDED) { 15868 cleanUp(move.fromUuid); 15869 } else { 15870 cleanUp(move.toUuid); 15871 } 15872 return status; 15873 } 15874 15875 @Override 15876 String getCodePath() { 15877 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15878 } 15879 15880 @Override 15881 String getResourcePath() { 15882 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15883 } 15884 15885 private boolean cleanUp(String volumeUuid) { 15886 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15887 move.dataAppName); 15888 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15889 final int[] userIds = sUserManager.getUserIds(); 15890 synchronized (mInstallLock) { 15891 // Clean up both app data and code 15892 // All package moves are frozen until finished 15893 for (int userId : userIds) { 15894 try { 15895 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15896 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15897 } catch (InstallerException e) { 15898 Slog.w(TAG, String.valueOf(e)); 15899 } 15900 } 15901 removeCodePathLI(codeFile); 15902 } 15903 return true; 15904 } 15905 15906 void cleanUpResourcesLI() { 15907 throw new UnsupportedOperationException(); 15908 } 15909 15910 boolean doPostDeleteLI(boolean delete) { 15911 throw new UnsupportedOperationException(); 15912 } 15913 } 15914 15915 static String getAsecPackageName(String packageCid) { 15916 int idx = packageCid.lastIndexOf("-"); 15917 if (idx == -1) { 15918 return packageCid; 15919 } 15920 return packageCid.substring(0, idx); 15921 } 15922 15923 // Utility method used to create code paths based on package name and available index. 15924 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15925 String idxStr = ""; 15926 int idx = 1; 15927 // Fall back to default value of idx=1 if prefix is not 15928 // part of oldCodePath 15929 if (oldCodePath != null) { 15930 String subStr = oldCodePath; 15931 // Drop the suffix right away 15932 if (suffix != null && subStr.endsWith(suffix)) { 15933 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15934 } 15935 // If oldCodePath already contains prefix find out the 15936 // ending index to either increment or decrement. 15937 int sidx = subStr.lastIndexOf(prefix); 15938 if (sidx != -1) { 15939 subStr = subStr.substring(sidx + prefix.length()); 15940 if (subStr != null) { 15941 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15942 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15943 } 15944 try { 15945 idx = Integer.parseInt(subStr); 15946 if (idx <= 1) { 15947 idx++; 15948 } else { 15949 idx--; 15950 } 15951 } catch(NumberFormatException e) { 15952 } 15953 } 15954 } 15955 } 15956 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15957 return prefix + idxStr; 15958 } 15959 15960 private File getNextCodePath(File targetDir, String packageName) { 15961 File result; 15962 SecureRandom random = new SecureRandom(); 15963 byte[] bytes = new byte[16]; 15964 do { 15965 random.nextBytes(bytes); 15966 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15967 result = new File(targetDir, packageName + "-" + suffix); 15968 } while (result.exists()); 15969 return result; 15970 } 15971 15972 // Utility method that returns the relative package path with respect 15973 // to the installation directory. Like say for /data/data/com.test-1.apk 15974 // string com.test-1 is returned. 15975 static String deriveCodePathName(String codePath) { 15976 if (codePath == null) { 15977 return null; 15978 } 15979 final File codeFile = new File(codePath); 15980 final String name = codeFile.getName(); 15981 if (codeFile.isDirectory()) { 15982 return name; 15983 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15984 final int lastDot = name.lastIndexOf('.'); 15985 return name.substring(0, lastDot); 15986 } else { 15987 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15988 return null; 15989 } 15990 } 15991 15992 static class PackageInstalledInfo { 15993 String name; 15994 int uid; 15995 // The set of users that originally had this package installed. 15996 int[] origUsers; 15997 // The set of users that now have this package installed. 15998 int[] newUsers; 15999 PackageParser.Package pkg; 16000 int returnCode; 16001 String returnMsg; 16002 String installerPackageName; 16003 PackageRemovedInfo removedInfo; 16004 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 16005 16006 public void setError(int code, String msg) { 16007 setReturnCode(code); 16008 setReturnMessage(msg); 16009 Slog.w(TAG, msg); 16010 } 16011 16012 public void setError(String msg, PackageParserException e) { 16013 setReturnCode(e.error); 16014 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 16015 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16016 for (int i = 0; i < childCount; i++) { 16017 addedChildPackages.valueAt(i).setError(msg, e); 16018 } 16019 Slog.w(TAG, msg, e); 16020 } 16021 16022 public void setError(String msg, PackageManagerException e) { 16023 returnCode = e.error; 16024 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 16025 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16026 for (int i = 0; i < childCount; i++) { 16027 addedChildPackages.valueAt(i).setError(msg, e); 16028 } 16029 Slog.w(TAG, msg, e); 16030 } 16031 16032 public void setReturnCode(int returnCode) { 16033 this.returnCode = returnCode; 16034 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16035 for (int i = 0; i < childCount; i++) { 16036 addedChildPackages.valueAt(i).returnCode = returnCode; 16037 } 16038 } 16039 16040 private void setReturnMessage(String returnMsg) { 16041 this.returnMsg = returnMsg; 16042 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16043 for (int i = 0; i < childCount; i++) { 16044 addedChildPackages.valueAt(i).returnMsg = returnMsg; 16045 } 16046 } 16047 16048 // In some error cases we want to convey more info back to the observer 16049 String origPackage; 16050 String origPermission; 16051 } 16052 16053 /* 16054 * Install a non-existing package. 16055 */ 16056 private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 16057 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 16058 String volumeUuid, PackageInstalledInfo res, int installReason) { 16059 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 16060 16061 // Remember this for later, in case we need to rollback this install 16062 String pkgName = pkg.packageName; 16063 16064 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 16065 16066 synchronized(mPackages) { 16067 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 16068 if (renamedPackage != null) { 16069 // A package with the same name is already installed, though 16070 // it has been renamed to an older name. The package we 16071 // are trying to install should be installed as an update to 16072 // the existing one, but that has not been requested, so bail. 16073 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16074 + " without first uninstalling package running as " 16075 + renamedPackage); 16076 return; 16077 } 16078 if (mPackages.containsKey(pkgName)) { 16079 // Don't allow installation over an existing package with the same name. 16080 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16081 + " without first uninstalling."); 16082 return; 16083 } 16084 } 16085 16086 try { 16087 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 16088 System.currentTimeMillis(), user); 16089 16090 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 16091 16092 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16093 prepareAppDataAfterInstallLIF(newPackage); 16094 16095 } else { 16096 // Remove package from internal structures, but keep around any 16097 // data that might have already existed 16098 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 16099 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 16100 } 16101 } catch (PackageManagerException e) { 16102 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16103 } 16104 16105 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16106 } 16107 16108 private static void updateDigest(MessageDigest digest, File file) throws IOException { 16109 try (DigestInputStream digestStream = 16110 new DigestInputStream(new FileInputStream(file), digest)) { 16111 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 16112 } 16113 } 16114 16115 private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 16116 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 16117 PackageInstalledInfo res, int installReason) { 16118 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16119 16120 final PackageParser.Package oldPackage; 16121 final PackageSetting ps; 16122 final String pkgName = pkg.packageName; 16123 final int[] allUsers; 16124 final int[] installedUsers; 16125 16126 synchronized(mPackages) { 16127 oldPackage = mPackages.get(pkgName); 16128 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 16129 16130 // don't allow upgrade to target a release SDK from a pre-release SDK 16131 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 16132 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16133 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 16134 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16135 if (oldTargetsPreRelease 16136 && !newTargetsPreRelease 16137 && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 16138 Slog.w(TAG, "Can't install package targeting released sdk"); 16139 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 16140 return; 16141 } 16142 16143 ps = mSettings.mPackages.get(pkgName); 16144 16145 // verify signatures are valid 16146 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16147 if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) { 16148 if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) { 16149 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16150 "New package not signed by keys specified by upgrade-keysets: " 16151 + pkgName); 16152 return; 16153 } 16154 } else { 16155 16156 // default to original signature matching 16157 if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails, 16158 PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) { 16159 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16160 "New package has a different signature: " + pkgName); 16161 return; 16162 } 16163 } 16164 16165 // don't allow a system upgrade unless the upgrade hash matches 16166 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) { 16167 byte[] digestBytes = null; 16168 try { 16169 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 16170 updateDigest(digest, new File(pkg.baseCodePath)); 16171 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 16172 for (String path : pkg.splitCodePaths) { 16173 updateDigest(digest, new File(path)); 16174 } 16175 } 16176 digestBytes = digest.digest(); 16177 } catch (NoSuchAlgorithmException | IOException e) { 16178 res.setError(INSTALL_FAILED_INVALID_APK, 16179 "Could not compute hash: " + pkgName); 16180 return; 16181 } 16182 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 16183 res.setError(INSTALL_FAILED_INVALID_APK, 16184 "New package fails restrict-update check: " + pkgName); 16185 return; 16186 } 16187 // retain upgrade restriction 16188 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 16189 } 16190 16191 // Check for shared user id changes 16192 String invalidPackageName = 16193 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 16194 if (invalidPackageName != null) { 16195 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 16196 "Package " + invalidPackageName + " tried to change user " 16197 + oldPackage.mSharedUserId); 16198 return; 16199 } 16200 16201 // check if the new package supports all of the abis which the old package supports 16202 boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null; 16203 boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null; 16204 if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) { 16205 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16206 "Update to package " + pkgName + " doesn't support multi arch"); 16207 return; 16208 } 16209 16210 // In case of rollback, remember per-user/profile install state 16211 allUsers = sUserManager.getUserIds(); 16212 installedUsers = ps.queryInstalledUsers(allUsers, true); 16213 16214 // don't allow an upgrade from full to ephemeral 16215 if (isInstantApp) { 16216 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 16217 for (int currentUser : allUsers) { 16218 if (!ps.getInstantApp(currentUser)) { 16219 // can't downgrade from full to instant 16220 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16221 + " for user: " + currentUser); 16222 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16223 return; 16224 } 16225 } 16226 } else if (!ps.getInstantApp(user.getIdentifier())) { 16227 // can't downgrade from full to instant 16228 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16229 + " for user: " + user.getIdentifier()); 16230 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16231 return; 16232 } 16233 } 16234 } 16235 16236 // Update what is removed 16237 res.removedInfo = new PackageRemovedInfo(this); 16238 res.removedInfo.uid = oldPackage.applicationInfo.uid; 16239 res.removedInfo.removedPackage = oldPackage.packageName; 16240 res.removedInfo.installerPackageName = ps.installerPackageName; 16241 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 16242 res.removedInfo.isUpdate = true; 16243 res.removedInfo.origUsers = installedUsers; 16244 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16245 for (int i = 0; i < installedUsers.length; i++) { 16246 final int userId = installedUsers[i]; 16247 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16248 } 16249 16250 final int childCount = (oldPackage.childPackages != null) 16251 ? oldPackage.childPackages.size() : 0; 16252 for (int i = 0; i < childCount; i++) { 16253 boolean childPackageUpdated = false; 16254 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16255 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16256 if (res.addedChildPackages != null) { 16257 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16258 if (childRes != null) { 16259 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16260 childRes.removedInfo.removedPackage = childPkg.packageName; 16261 if (childPs != null) { 16262 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16263 } 16264 childRes.removedInfo.isUpdate = true; 16265 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16266 childPackageUpdated = true; 16267 } 16268 } 16269 if (!childPackageUpdated) { 16270 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 16271 childRemovedRes.removedPackage = childPkg.packageName; 16272 if (childPs != null) { 16273 childRemovedRes.installerPackageName = childPs.installerPackageName; 16274 } 16275 childRemovedRes.isUpdate = false; 16276 childRemovedRes.dataRemoved = true; 16277 synchronized (mPackages) { 16278 if (childPs != null) { 16279 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16280 } 16281 } 16282 if (res.removedInfo.removedChildPackages == null) { 16283 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16284 } 16285 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16286 } 16287 } 16288 16289 boolean sysPkg = (isSystemApp(oldPackage)); 16290 if (sysPkg) { 16291 // Set the system/privileged/oem/vendor/product flags as needed 16292 final boolean privileged = 16293 (oldPackage.applicationInfo.privateFlags 16294 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16295 final boolean oem = 16296 (oldPackage.applicationInfo.privateFlags 16297 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 16298 final boolean vendor = 16299 (oldPackage.applicationInfo.privateFlags 16300 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 16301 final boolean product = 16302 (oldPackage.applicationInfo.privateFlags 16303 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 16304 final @ParseFlags int systemParseFlags = parseFlags; 16305 final @ScanFlags int systemScanFlags = scanFlags 16306 | SCAN_AS_SYSTEM 16307 | (privileged ? SCAN_AS_PRIVILEGED : 0) 16308 | (oem ? SCAN_AS_OEM : 0) 16309 | (vendor ? SCAN_AS_VENDOR : 0) 16310 | (product ? SCAN_AS_PRODUCT : 0); 16311 16312 replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags, 16313 user, allUsers, installerPackageName, res, installReason); 16314 } else { 16315 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 16316 user, allUsers, installerPackageName, res, installReason); 16317 } 16318 } 16319 16320 @Override 16321 public List<String> getPreviousCodePaths(String packageName) { 16322 final int callingUid = Binder.getCallingUid(); 16323 final List<String> result = new ArrayList<>(); 16324 if (getInstantAppPackageName(callingUid) != null) { 16325 return result; 16326 } 16327 final PackageSetting ps = mSettings.mPackages.get(packageName); 16328 if (ps != null 16329 && ps.oldCodePaths != null 16330 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 16331 result.addAll(ps.oldCodePaths); 16332 } 16333 return result; 16334 } 16335 16336 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16337 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16338 final @ScanFlags int scanFlags, UserHandle user, int[] allUsers, 16339 String installerPackageName, PackageInstalledInfo res, int installReason) { 16340 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16341 + deletedPackage); 16342 16343 String pkgName = deletedPackage.packageName; 16344 boolean deletedPkg = true; 16345 boolean addedPkg = false; 16346 boolean updatedSettings = false; 16347 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16348 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16349 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16350 16351 final long origUpdateTime = (pkg.mExtras != null) 16352 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16353 16354 // First delete the existing package while retaining the data directory 16355 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16356 res.removedInfo, true, pkg)) { 16357 // If the existing package wasn't successfully deleted 16358 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16359 deletedPkg = false; 16360 } else { 16361 // Successfully deleted the old package; proceed with replace. 16362 16363 // If deleted package lived in a container, give users a chance to 16364 // relinquish resources before killing. 16365 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16366 if (DEBUG_INSTALL) { 16367 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16368 } 16369 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16370 final ArrayList<String> pkgList = new ArrayList<String>(1); 16371 pkgList.add(deletedPackage.applicationInfo.packageName); 16372 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16373 } 16374 16375 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16376 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16377 16378 try { 16379 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 16380 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16381 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16382 installReason); 16383 16384 // Update the in-memory copy of the previous code paths. 16385 PackageSetting ps = mSettings.mPackages.get(pkgName); 16386 if (!killApp) { 16387 if (ps.oldCodePaths == null) { 16388 ps.oldCodePaths = new ArraySet<>(); 16389 } 16390 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16391 if (deletedPackage.splitCodePaths != null) { 16392 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16393 } 16394 } else { 16395 ps.oldCodePaths = null; 16396 } 16397 if (ps.childPackageNames != null) { 16398 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16399 final String childPkgName = ps.childPackageNames.get(i); 16400 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16401 childPs.oldCodePaths = ps.oldCodePaths; 16402 } 16403 } 16404 // set instant app status, but, only if it's explicitly specified 16405 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16406 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16407 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16408 prepareAppDataAfterInstallLIF(newPackage); 16409 addedPkg = true; 16410 mDexManager.notifyPackageUpdated(newPackage.packageName, 16411 newPackage.baseCodePath, newPackage.splitCodePaths); 16412 } catch (PackageManagerException e) { 16413 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16414 } 16415 } 16416 16417 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16418 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16419 16420 // Revert all internal state mutations and added folders for the failed install 16421 if (addedPkg) { 16422 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16423 res.removedInfo, true, null); 16424 } 16425 16426 // Restore the old package 16427 if (deletedPkg) { 16428 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16429 File restoreFile = new File(deletedPackage.codePath); 16430 // Parse old package 16431 boolean oldExternal = isExternal(deletedPackage); 16432 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16433 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16434 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16435 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16436 try { 16437 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16438 null); 16439 } catch (PackageManagerException e) { 16440 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16441 + e.getMessage()); 16442 return; 16443 } 16444 16445 synchronized (mPackages) { 16446 // Ensure the installer package name up to date 16447 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16448 16449 // Update permissions for restored package 16450 mPermissionManager.updatePermissions( 16451 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16452 mPermissionCallback); 16453 16454 mSettings.writeLPr(); 16455 } 16456 16457 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16458 } 16459 } else { 16460 synchronized (mPackages) { 16461 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16462 if (ps != null) { 16463 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16464 if (res.removedInfo.removedChildPackages != null) { 16465 final int childCount = res.removedInfo.removedChildPackages.size(); 16466 // Iterate in reverse as we may modify the collection 16467 for (int i = childCount - 1; i >= 0; i--) { 16468 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16469 if (res.addedChildPackages.containsKey(childPackageName)) { 16470 res.removedInfo.removedChildPackages.removeAt(i); 16471 } else { 16472 PackageRemovedInfo childInfo = res.removedInfo 16473 .removedChildPackages.valueAt(i); 16474 childInfo.removedForAllUsers = mPackages.get( 16475 childInfo.removedPackage) == null; 16476 } 16477 } 16478 } 16479 } 16480 } 16481 } 16482 } 16483 16484 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16485 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16486 final @ScanFlags int scanFlags, UserHandle user, 16487 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16488 int installReason) { 16489 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16490 + ", old=" + deletedPackage); 16491 16492 final boolean disabledSystem; 16493 16494 // Remove existing system package 16495 removePackageLI(deletedPackage, true); 16496 16497 synchronized (mPackages) { 16498 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16499 } 16500 if (!disabledSystem) { 16501 // We didn't need to disable the .apk as a current system package, 16502 // which means we are replacing another update that is already 16503 // installed. We need to make sure to delete the older one's .apk. 16504 res.removedInfo.args = createInstallArgsForExisting(0, 16505 deletedPackage.applicationInfo.getCodePath(), 16506 deletedPackage.applicationInfo.getResourcePath(), 16507 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16508 } else { 16509 res.removedInfo.args = null; 16510 } 16511 16512 // Successfully disabled the old package. Now proceed with re-installation 16513 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16514 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16515 16516 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16517 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16518 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16519 16520 PackageParser.Package newPackage = null; 16521 try { 16522 // Add the package to the internal data structures 16523 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 16524 16525 // Set the update and install times 16526 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16527 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16528 System.currentTimeMillis()); 16529 16530 // Update the package dynamic state if succeeded 16531 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16532 // Now that the install succeeded make sure we remove data 16533 // directories for any child package the update removed. 16534 final int deletedChildCount = (deletedPackage.childPackages != null) 16535 ? deletedPackage.childPackages.size() : 0; 16536 final int newChildCount = (newPackage.childPackages != null) 16537 ? newPackage.childPackages.size() : 0; 16538 for (int i = 0; i < deletedChildCount; i++) { 16539 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16540 boolean childPackageDeleted = true; 16541 for (int j = 0; j < newChildCount; j++) { 16542 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16543 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16544 childPackageDeleted = false; 16545 break; 16546 } 16547 } 16548 if (childPackageDeleted) { 16549 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16550 deletedChildPkg.packageName); 16551 if (ps != null && res.removedInfo.removedChildPackages != null) { 16552 PackageRemovedInfo removedChildRes = res.removedInfo 16553 .removedChildPackages.get(deletedChildPkg.packageName); 16554 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16555 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16556 } 16557 } 16558 } 16559 16560 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16561 installReason); 16562 prepareAppDataAfterInstallLIF(newPackage); 16563 16564 mDexManager.notifyPackageUpdated(newPackage.packageName, 16565 newPackage.baseCodePath, newPackage.splitCodePaths); 16566 } 16567 } catch (PackageManagerException e) { 16568 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16569 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16570 } 16571 16572 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16573 // Re installation failed. Restore old information 16574 // Remove new pkg information 16575 if (newPackage != null) { 16576 removeInstalledPackageLI(newPackage, true); 16577 } 16578 // Add back the old system package 16579 try { 16580 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16581 } catch (PackageManagerException e) { 16582 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16583 } 16584 16585 synchronized (mPackages) { 16586 if (disabledSystem) { 16587 enableSystemPackageLPw(deletedPackage); 16588 } 16589 16590 // Ensure the installer package name up to date 16591 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16592 16593 // Update permissions for restored package 16594 mPermissionManager.updatePermissions( 16595 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16596 mPermissionCallback); 16597 16598 mSettings.writeLPr(); 16599 } 16600 16601 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16602 + " after failed upgrade"); 16603 } 16604 } 16605 16606 /** 16607 * Checks whether the parent or any of the child packages have a change shared 16608 * user. For a package to be a valid update the shred users of the parent and 16609 * the children should match. We may later support changing child shared users. 16610 * @param oldPkg The updated package. 16611 * @param newPkg The update package. 16612 * @return The shared user that change between the versions. 16613 */ 16614 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16615 PackageParser.Package newPkg) { 16616 // Check parent shared user 16617 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16618 return newPkg.packageName; 16619 } 16620 // Check child shared users 16621 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16622 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16623 for (int i = 0; i < newChildCount; i++) { 16624 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16625 // If this child was present, did it have the same shared user? 16626 for (int j = 0; j < oldChildCount; j++) { 16627 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16628 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16629 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16630 return newChildPkg.packageName; 16631 } 16632 } 16633 } 16634 return null; 16635 } 16636 16637 private void removeNativeBinariesLI(PackageSetting ps) { 16638 // Remove the lib path for the parent package 16639 if (ps != null) { 16640 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16641 // Remove the lib path for the child packages 16642 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16643 for (int i = 0; i < childCount; i++) { 16644 PackageSetting childPs = null; 16645 synchronized (mPackages) { 16646 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16647 } 16648 if (childPs != null) { 16649 NativeLibraryHelper.removeNativeBinariesLI(childPs 16650 .legacyNativeLibraryPathString); 16651 } 16652 } 16653 } 16654 } 16655 16656 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16657 // Enable the parent package 16658 mSettings.enableSystemPackageLPw(pkg.packageName); 16659 // Enable the child packages 16660 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16661 for (int i = 0; i < childCount; i++) { 16662 PackageParser.Package childPkg = pkg.childPackages.get(i); 16663 mSettings.enableSystemPackageLPw(childPkg.packageName); 16664 } 16665 } 16666 16667 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16668 PackageParser.Package newPkg) { 16669 // Disable the parent package (parent always replaced) 16670 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16671 // Disable the child packages 16672 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16673 for (int i = 0; i < childCount; i++) { 16674 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16675 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16676 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16677 } 16678 return disabled; 16679 } 16680 16681 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16682 String installerPackageName) { 16683 // Enable the parent package 16684 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16685 // Enable the child packages 16686 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16687 for (int i = 0; i < childCount; i++) { 16688 PackageParser.Package childPkg = pkg.childPackages.get(i); 16689 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16690 } 16691 } 16692 16693 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16694 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16695 // Update the parent package setting 16696 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16697 res, user, installReason); 16698 // Update the child packages setting 16699 final int childCount = (newPackage.childPackages != null) 16700 ? newPackage.childPackages.size() : 0; 16701 for (int i = 0; i < childCount; i++) { 16702 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16703 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16704 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16705 childRes.origUsers, childRes, user, installReason); 16706 } 16707 } 16708 16709 private void updateSettingsInternalLI(PackageParser.Package pkg, 16710 String installerPackageName, int[] allUsers, int[] installedForUsers, 16711 PackageInstalledInfo res, UserHandle user, int installReason) { 16712 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16713 16714 final String pkgName = pkg.packageName; 16715 16716 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath); 16717 synchronized (mPackages) { 16718// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions 16719 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 16720 mPermissionCallback); 16721 // For system-bundled packages, we assume that installing an upgraded version 16722 // of the package implies that the user actually wants to run that new code, 16723 // so we enable the package. 16724 PackageSetting ps = mSettings.mPackages.get(pkgName); 16725 final int userId = user.getIdentifier(); 16726 if (ps != null) { 16727 if (isSystemApp(pkg)) { 16728 if (DEBUG_INSTALL) { 16729 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16730 } 16731 // Enable system package for requested users 16732 if (res.origUsers != null) { 16733 for (int origUserId : res.origUsers) { 16734 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16735 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16736 origUserId, installerPackageName); 16737 } 16738 } 16739 } 16740 // Also convey the prior install/uninstall state 16741 if (allUsers != null && installedForUsers != null) { 16742 for (int currentUserId : allUsers) { 16743 final boolean installed = ArrayUtils.contains( 16744 installedForUsers, currentUserId); 16745 if (DEBUG_INSTALL) { 16746 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16747 } 16748 ps.setInstalled(installed, currentUserId); 16749 } 16750 // these install state changes will be persisted in the 16751 // upcoming call to mSettings.writeLPr(). 16752 } 16753 } 16754 // It's implied that when a user requests installation, they want the app to be 16755 // installed and enabled. 16756 if (userId != UserHandle.USER_ALL) { 16757 ps.setInstalled(true, userId); 16758 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16759 } else { 16760 for (int currentUserId : sUserManager.getUserIds()) { 16761 ps.setInstalled(true, currentUserId); 16762 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId, 16763 installerPackageName); 16764 } 16765 } 16766 16767 // When replacing an existing package, preserve the original install reason for all 16768 // users that had the package installed before. 16769 final Set<Integer> previousUserIds = new ArraySet<>(); 16770 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16771 final int installReasonCount = res.removedInfo.installReasons.size(); 16772 for (int i = 0; i < installReasonCount; i++) { 16773 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16774 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16775 ps.setInstallReason(previousInstallReason, previousUserId); 16776 previousUserIds.add(previousUserId); 16777 } 16778 } 16779 16780 // Set install reason for users that are having the package newly installed. 16781 if (userId == UserHandle.USER_ALL) { 16782 for (int currentUserId : sUserManager.getUserIds()) { 16783 if (!previousUserIds.contains(currentUserId)) { 16784 ps.setInstallReason(installReason, currentUserId); 16785 } 16786 } 16787 } else if (!previousUserIds.contains(userId)) { 16788 ps.setInstallReason(installReason, userId); 16789 } 16790 mSettings.writeKernelMappingLPr(ps); 16791 } 16792 res.name = pkgName; 16793 res.uid = pkg.applicationInfo.uid; 16794 res.pkg = pkg; 16795 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16796 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16797 //to update install status 16798 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16799 mSettings.writeLPr(); 16800 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16801 } 16802 16803 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16804 } 16805 16806 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16807 try { 16808 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16809 installPackageLI(args, res); 16810 } finally { 16811 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16812 } 16813 } 16814 16815 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16816 final int installFlags = args.installFlags; 16817 final String installerPackageName = args.installerPackageName; 16818 final String volumeUuid = args.volumeUuid; 16819 final File tmpPackageFile = new File(args.getCodePath()); 16820 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16821 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16822 || (args.volumeUuid != null)); 16823 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16824 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16825 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16826 final boolean virtualPreload = 16827 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 16828 boolean replace = false; 16829 @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16830 if (args.move != null) { 16831 // moving a complete application; perform an initial scan on the new install location 16832 scanFlags |= SCAN_INITIAL; 16833 } 16834 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16835 scanFlags |= SCAN_DONT_KILL_APP; 16836 } 16837 if (instantApp) { 16838 scanFlags |= SCAN_AS_INSTANT_APP; 16839 } 16840 if (fullApp) { 16841 scanFlags |= SCAN_AS_FULL_APP; 16842 } 16843 if (virtualPreload) { 16844 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 16845 } 16846 16847 // Result object to be returned 16848 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16849 res.installerPackageName = installerPackageName; 16850 16851 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16852 16853 // Sanity check 16854 if (instantApp && (forwardLocked || onExternal)) { 16855 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16856 + " external=" + onExternal); 16857 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16858 return; 16859 } 16860 16861 // Retrieve PackageSettings and parse package 16862 @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16863 | PackageParser.PARSE_ENFORCE_CODE 16864 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16865 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16866 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16867 PackageParser pp = new PackageParser(); 16868 pp.setSeparateProcesses(mSeparateProcesses); 16869 pp.setDisplayMetrics(mMetrics); 16870 pp.setCallback(mPackageParserCallback); 16871 16872 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16873 final PackageParser.Package pkg; 16874 try { 16875 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16876 DexMetadataHelper.validatePackageDexMetadata(pkg); 16877 } catch (PackageParserException e) { 16878 res.setError("Failed parse during installPackageLI", e); 16879 return; 16880 } finally { 16881 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16882 } 16883 16884 // Instant apps have several additional install-time checks. 16885 if (instantApp) { 16886 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 16887 Slog.w(TAG, 16888 "Instant app package " + pkg.packageName + " does not target at least O"); 16889 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16890 "Instant app package must target at least O"); 16891 return; 16892 } 16893 if (pkg.applicationInfo.targetSandboxVersion != 2) { 16894 Slog.w(TAG, "Instant app package " + pkg.packageName 16895 + " does not target targetSandboxVersion 2"); 16896 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16897 "Instant app package must use targetSandboxVersion 2"); 16898 return; 16899 } 16900 if (pkg.mSharedUserId != null) { 16901 Slog.w(TAG, "Instant app package " + pkg.packageName 16902 + " may not declare sharedUserId."); 16903 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16904 "Instant app package may not declare a sharedUserId"); 16905 return; 16906 } 16907 } 16908 16909 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16910 // Static shared libraries have synthetic package names 16911 renameStaticSharedLibraryPackage(pkg); 16912 16913 // No static shared libs on external storage 16914 if (onExternal) { 16915 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16916 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16917 "Packages declaring static-shared libs cannot be updated"); 16918 return; 16919 } 16920 } 16921 16922 // If we are installing a clustered package add results for the children 16923 if (pkg.childPackages != null) { 16924 synchronized (mPackages) { 16925 final int childCount = pkg.childPackages.size(); 16926 for (int i = 0; i < childCount; i++) { 16927 PackageParser.Package childPkg = pkg.childPackages.get(i); 16928 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16929 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16930 childRes.pkg = childPkg; 16931 childRes.name = childPkg.packageName; 16932 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16933 if (childPs != null) { 16934 childRes.origUsers = childPs.queryInstalledUsers( 16935 sUserManager.getUserIds(), true); 16936 } 16937 if ((mPackages.containsKey(childPkg.packageName))) { 16938 childRes.removedInfo = new PackageRemovedInfo(this); 16939 childRes.removedInfo.removedPackage = childPkg.packageName; 16940 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16941 } 16942 if (res.addedChildPackages == null) { 16943 res.addedChildPackages = new ArrayMap<>(); 16944 } 16945 res.addedChildPackages.put(childPkg.packageName, childRes); 16946 } 16947 } 16948 } 16949 16950 // If package doesn't declare API override, mark that we have an install 16951 // time CPU ABI override. 16952 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16953 pkg.cpuAbiOverride = args.abiOverride; 16954 } 16955 16956 String pkgName = res.name = pkg.packageName; 16957 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16958 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16959 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16960 return; 16961 } 16962 } 16963 16964 try { 16965 // either use what we've been given or parse directly from the APK 16966 if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) { 16967 pkg.setSigningDetails(args.signingDetails); 16968 } else { 16969 PackageParser.collectCertificates(pkg, false /* skipVerify */); 16970 } 16971 } catch (PackageParserException e) { 16972 res.setError("Failed collect during installPackageLI", e); 16973 return; 16974 } 16975 16976 if (instantApp && pkg.mSigningDetails.signatureSchemeVersion 16977 < SignatureSchemeVersion.SIGNING_BLOCK_V2) { 16978 Slog.w(TAG, "Instant app package " + pkg.packageName 16979 + " is not signed with at least APK Signature Scheme v2"); 16980 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16981 "Instant app package must be signed with APK Signature Scheme v2 or greater"); 16982 return; 16983 } 16984 16985 // Get rid of all references to package scan path via parser. 16986 pp = null; 16987 String oldCodePath = null; 16988 boolean systemApp = false; 16989 synchronized (mPackages) { 16990 // Check if installing already existing package 16991 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16992 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16993 if (pkg.mOriginalPackages != null 16994 && pkg.mOriginalPackages.contains(oldName) 16995 && mPackages.containsKey(oldName)) { 16996 // This package is derived from an original package, 16997 // and this device has been updating from that original 16998 // name. We must continue using the original name, so 16999 // rename the new package here. 17000 pkg.setPackageName(oldName); 17001 pkgName = pkg.packageName; 17002 replace = true; 17003 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 17004 + oldName + " pkgName=" + pkgName); 17005 } else if (mPackages.containsKey(pkgName)) { 17006 // This package, under its official name, already exists 17007 // on the device; we should replace it. 17008 replace = true; 17009 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 17010 } 17011 17012 // Child packages are installed through the parent package 17013 if (pkg.parentPackage != null) { 17014 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 17015 "Package " + pkg.packageName + " is child of package " 17016 + pkg.parentPackage.parentPackage + ". Child packages " 17017 + "can be updated only through the parent package."); 17018 return; 17019 } 17020 17021 if (replace) { 17022 // Prevent apps opting out from runtime permissions 17023 PackageParser.Package oldPackage = mPackages.get(pkgName); 17024 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 17025 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 17026 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 17027 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 17028 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 17029 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 17030 + " doesn't support runtime permissions but the old" 17031 + " target SDK " + oldTargetSdk + " does."); 17032 return; 17033 } 17034 // Prevent persistent apps from being updated 17035 if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) { 17036 res.setError(PackageManager.INSTALL_FAILED_INVALID_APK, 17037 "Package " + oldPackage.packageName + " is a persistent app. " 17038 + "Persistent apps are not updateable."); 17039 return; 17040 } 17041 // Prevent apps from downgrading their targetSandbox. 17042 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 17043 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 17044 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 17045 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 17046 "Package " + pkg.packageName + " new target sandbox " 17047 + newTargetSandbox + " is incompatible with the previous value of" 17048 + oldTargetSandbox + "."); 17049 return; 17050 } 17051 17052 // Prevent installing of child packages 17053 if (oldPackage.parentPackage != null) { 17054 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 17055 "Package " + pkg.packageName + " is child of package " 17056 + oldPackage.parentPackage + ". Child packages " 17057 + "can be updated only through the parent package."); 17058 return; 17059 } 17060 } 17061 } 17062 17063 PackageSetting ps = mSettings.mPackages.get(pkgName); 17064 if (ps != null) { 17065 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 17066 17067 // Static shared libs have same package with different versions where 17068 // we internally use a synthetic package name to allow multiple versions 17069 // of the same package, therefore we need to compare signatures against 17070 // the package setting for the latest library version. 17071 PackageSetting signatureCheckPs = ps; 17072 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17073 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 17074 if (libraryEntry != null) { 17075 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 17076 } 17077 } 17078 17079 // Quick sanity check that we're signed correctly if updating; 17080 // we'll check this again later when scanning, but we want to 17081 // bail early here before tripping over redefined permissions. 17082 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 17083 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 17084 if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 17085 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 17086 + pkg.packageName + " upgrade keys do not match the " 17087 + "previously installed version"); 17088 return; 17089 } 17090 } else { 17091 try { 17092 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 17093 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 17094 // We don't care about disabledPkgSetting on install for now. 17095 final boolean compatMatch = verifySignatures( 17096 signatureCheckPs, null, pkg.mSigningDetails, compareCompat, 17097 compareRecover); 17098 // The new KeySets will be re-added later in the scanning process. 17099 if (compatMatch) { 17100 synchronized (mPackages) { 17101 ksms.removeAppKeySetDataLPw(pkg.packageName); 17102 } 17103 } 17104 } catch (PackageManagerException e) { 17105 res.setError(e.error, e.getMessage()); 17106 return; 17107 } 17108 } 17109 17110 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 17111 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 17112 systemApp = (ps.pkg.applicationInfo.flags & 17113 ApplicationInfo.FLAG_SYSTEM) != 0; 17114 } 17115 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17116 } 17117 17118 int N = pkg.permissions.size(); 17119 for (int i = N-1; i >= 0; i--) { 17120 final PackageParser.Permission perm = pkg.permissions.get(i); 17121 final BasePermission bp = 17122 (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name); 17123 17124 // Don't allow anyone but the system to define ephemeral permissions. 17125 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 17126 && !systemApp) { 17127 Slog.w(TAG, "Non-System package " + pkg.packageName 17128 + " attempting to delcare ephemeral permission " 17129 + perm.info.name + "; Removing ephemeral."); 17130 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 17131 } 17132 17133 // Check whether the newly-scanned package wants to define an already-defined perm 17134 if (bp != null) { 17135 // If the defining package is signed with our cert, it's okay. This 17136 // also includes the "updating the same package" case, of course. 17137 // "updating same package" could also involve key-rotation. 17138 final boolean sigsOk; 17139 final String sourcePackageName = bp.getSourcePackageName(); 17140 final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting(); 17141 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 17142 if (sourcePackageName.equals(pkg.packageName) 17143 && (ksms.shouldCheckUpgradeKeySetLocked( 17144 sourcePackageSetting, scanFlags))) { 17145 sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg); 17146 } else { 17147 17148 // in the event of signing certificate rotation, we need to see if the 17149 // package's certificate has rotated from the current one, or if it is an 17150 // older certificate with which the current is ok with sharing permissions 17151 if (sourcePackageSetting.signatures.mSigningDetails.checkCapability( 17152 pkg.mSigningDetails, 17153 PackageParser.SigningDetails.CertCapabilities.PERMISSION)) { 17154 sigsOk = true; 17155 } else if (pkg.mSigningDetails.checkCapability( 17156 sourcePackageSetting.signatures.mSigningDetails, 17157 PackageParser.SigningDetails.CertCapabilities.PERMISSION)) { 17158 17159 // the scanned package checks out, has signing certificate rotation 17160 // history, and is newer; bring it over 17161 sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails; 17162 sigsOk = true; 17163 } else { 17164 sigsOk = false; 17165 } 17166 } 17167 if (!sigsOk) { 17168 // If the owning package is the system itself, we log but allow 17169 // install to proceed; we fail the install on all other permission 17170 // redefinitions. 17171 if (!sourcePackageName.equals("android")) { 17172 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 17173 + pkg.packageName + " attempting to redeclare permission " 17174 + perm.info.name + " already owned by " + sourcePackageName); 17175 res.origPermission = perm.info.name; 17176 res.origPackage = sourcePackageName; 17177 return; 17178 } else { 17179 Slog.w(TAG, "Package " + pkg.packageName 17180 + " attempting to redeclare system permission " 17181 + perm.info.name + "; ignoring new declaration"); 17182 pkg.permissions.remove(i); 17183 } 17184 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 17185 // Prevent apps to change protection level to dangerous from any other 17186 // type as this would allow a privilege escalation where an app adds a 17187 // normal/signature permission in other app's group and later redefines 17188 // it as dangerous leading to the group auto-grant. 17189 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 17190 == PermissionInfo.PROTECTION_DANGEROUS) { 17191 if (bp != null && !bp.isRuntime()) { 17192 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 17193 + "non-runtime permission " + perm.info.name 17194 + " to runtime; keeping old protection level"); 17195 perm.info.protectionLevel = bp.getProtectionLevel(); 17196 } 17197 } 17198 } 17199 } 17200 } 17201 } 17202 17203 if (systemApp) { 17204 if (onExternal) { 17205 // Abort update; system app can't be replaced with app on sdcard 17206 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17207 "Cannot install updates to system apps on sdcard"); 17208 return; 17209 } else if (instantApp) { 17210 // Abort update; system app can't be replaced with an instant app 17211 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 17212 "Cannot update a system app with an instant app"); 17213 return; 17214 } 17215 } 17216 17217 if (args.move != null) { 17218 // We did an in-place move, so dex is ready to roll 17219 scanFlags |= SCAN_NO_DEX; 17220 scanFlags |= SCAN_MOVE; 17221 17222 synchronized (mPackages) { 17223 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17224 if (ps == null) { 17225 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17226 "Missing settings for moved package " + pkgName); 17227 } 17228 17229 // We moved the entire application as-is, so bring over the 17230 // previously derived ABI information. 17231 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 17232 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 17233 } 17234 17235 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 17236 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 17237 scanFlags |= SCAN_NO_DEX; 17238 17239 try { 17240 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 17241 args.abiOverride : pkg.cpuAbiOverride); 17242 final boolean extractNativeLibs = !pkg.isLibrary(); 17243 derivePackageAbi(pkg, abiOverride, extractNativeLibs); 17244 } catch (PackageManagerException pme) { 17245 Slog.e(TAG, "Error deriving application ABI", pme); 17246 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 17247 return; 17248 } 17249 17250 // Shared libraries for the package need to be updated. 17251 synchronized (mPackages) { 17252 try { 17253 updateSharedLibrariesLPr(pkg, null); 17254 } catch (PackageManagerException e) { 17255 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17256 } 17257 } 17258 } 17259 17260 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 17261 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17262 return; 17263 } 17264 17265 if (PackageManagerServiceUtils.isApkVerityEnabled()) { 17266 String apkPath = null; 17267 synchronized (mPackages) { 17268 // Note that if the attacker managed to skip verify setup, for example by tampering 17269 // with the package settings, upon reboot we will do full apk verification when 17270 // verity is not detected. 17271 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17272 if (ps != null && ps.isPrivileged()) { 17273 apkPath = pkg.baseCodePath; 17274 } 17275 } 17276 17277 if (apkPath != null) { 17278 final VerityUtils.SetupResult result = 17279 VerityUtils.generateApkVeritySetupData(apkPath); 17280 if (result.isOk()) { 17281 if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath); 17282 FileDescriptor fd = result.getUnownedFileDescriptor(); 17283 try { 17284 mInstaller.installApkVerity(apkPath, fd); 17285 } catch (InstallerException e) { 17286 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17287 "Failed to set up verity: " + e); 17288 return; 17289 } finally { 17290 IoUtils.closeQuietly(fd); 17291 } 17292 } else if (result.isFailed()) { 17293 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity"); 17294 return; 17295 } else { 17296 // Do nothing if verity is skipped. Will fall back to full apk verification on 17297 // reboot. 17298 } 17299 } 17300 } 17301 17302 if (!instantApp) { 17303 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17304 } else { 17305 if (DEBUG_DOMAIN_VERIFICATION) { 17306 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName); 17307 } 17308 } 17309 17310 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17311 "installPackageLI")) { 17312 if (replace) { 17313 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17314 // Static libs have a synthetic package name containing the version 17315 // and cannot be updated as an update would get a new package name, 17316 // unless this is the exact same version code which is useful for 17317 // development. 17318 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17319 if (existingPkg != null && 17320 existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) { 17321 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17322 + "static-shared libs cannot be updated"); 17323 return; 17324 } 17325 } 17326 replacePackageLIF(pkg, parseFlags, scanFlags, args.user, 17327 installerPackageName, res, args.installReason); 17328 } else { 17329 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17330 args.user, installerPackageName, volumeUuid, res, args.installReason); 17331 } 17332 } 17333 17334 // Prepare the application profiles for the new code paths. 17335 // This needs to be done before invoking dexopt so that any install-time profile 17336 // can be used for optimizations. 17337 mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier())); 17338 17339 // Check whether we need to dexopt the app. 17340 // 17341 // NOTE: it is IMPORTANT to call dexopt: 17342 // - after doRename which will sync the package data from PackageParser.Package and its 17343 // corresponding ApplicationInfo. 17344 // - after installNewPackageLIF or replacePackageLIF which will update result with the 17345 // uid of the application (pkg.applicationInfo.uid). 17346 // This update happens in place! 17347 // 17348 // We only need to dexopt if the package meets ALL of the following conditions: 17349 // 1) it is not forward locked. 17350 // 2) it is not on on an external ASEC container. 17351 // 3) it is not an instant app or if it is then dexopt is enabled via gservices. 17352 // 17353 // Note that we do not dexopt instant apps by default. dexopt can take some time to 17354 // complete, so we skip this step during installation. Instead, we'll take extra time 17355 // the first time the instant app starts. It's preferred to do it this way to provide 17356 // continuous progress to the useur instead of mysteriously blocking somewhere in the 17357 // middle of running an instant app. The default behaviour can be overridden 17358 // via gservices. 17359 final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED) 17360 && !forwardLocked 17361 && !pkg.applicationInfo.isExternalAsec() 17362 && (!instantApp || Global.getInt(mContext.getContentResolver(), 17363 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0); 17364 17365 if (performDexopt) { 17366 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17367 // Do not run PackageDexOptimizer through the local performDexOpt 17368 // method because `pkg` may not be in `mPackages` yet. 17369 // 17370 // Also, don't fail application installs if the dexopt step fails. 17371 DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName, 17372 REASON_INSTALL, 17373 DexoptOptions.DEXOPT_BOOT_COMPLETE | 17374 DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE); 17375 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17376 null /* instructionSets */, 17377 getOrCreateCompilerPackageStats(pkg), 17378 mDexManager.getPackageUseInfoOrDefault(pkg.packageName), 17379 dexoptOptions); 17380 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17381 } 17382 17383 // Notify BackgroundDexOptService that the package has been changed. 17384 // If this is an update of a package which used to fail to compile, 17385 // BackgroundDexOptService will remove it from its blacklist. 17386 // TODO: Layering violation 17387 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17388 17389 synchronized (mPackages) { 17390 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17391 if (ps != null) { 17392 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17393 ps.setUpdateAvailable(false /*updateAvailable*/); 17394 } 17395 17396 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17397 for (int i = 0; i < childCount; i++) { 17398 PackageParser.Package childPkg = pkg.childPackages.get(i); 17399 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17400 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17401 if (childPs != null) { 17402 childRes.newUsers = childPs.queryInstalledUsers( 17403 sUserManager.getUserIds(), true); 17404 } 17405 } 17406 17407 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17408 updateSequenceNumberLP(ps, res.newUsers); 17409 updateInstantAppInstallerLocked(pkgName); 17410 } 17411 } 17412 } 17413 17414 private void startIntentFilterVerifications(int userId, boolean replacing, 17415 PackageParser.Package pkg) { 17416 if (mIntentFilterVerifierComponent == null) { 17417 Slog.w(TAG, "No IntentFilter verification will not be done as " 17418 + "there is no IntentFilterVerifier available!"); 17419 return; 17420 } 17421 17422 final int verifierUid = getPackageUid( 17423 mIntentFilterVerifierComponent.getPackageName(), 17424 MATCH_DEBUG_TRIAGED_MISSING, 17425 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17426 17427 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17428 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17429 mHandler.sendMessage(msg); 17430 17431 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17432 for (int i = 0; i < childCount; i++) { 17433 PackageParser.Package childPkg = pkg.childPackages.get(i); 17434 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17435 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17436 mHandler.sendMessage(msg); 17437 } 17438 } 17439 17440 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17441 PackageParser.Package pkg) { 17442 int size = pkg.activities.size(); 17443 if (size == 0) { 17444 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17445 "No activity, so no need to verify any IntentFilter!"); 17446 return; 17447 } 17448 17449 final boolean hasDomainURLs = hasDomainURLs(pkg); 17450 if (!hasDomainURLs) { 17451 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17452 "No domain URLs, so no need to verify any IntentFilter!"); 17453 return; 17454 } 17455 17456 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17457 + " if any IntentFilter from the " + size 17458 + " Activities needs verification ..."); 17459 17460 int count = 0; 17461 final String packageName = pkg.packageName; 17462 17463 synchronized (mPackages) { 17464 // If this is a new install and we see that we've already run verification for this 17465 // package, we have nothing to do: it means the state was restored from backup. 17466 if (!replacing) { 17467 IntentFilterVerificationInfo ivi = 17468 mSettings.getIntentFilterVerificationLPr(packageName); 17469 if (ivi != null) { 17470 if (DEBUG_DOMAIN_VERIFICATION) { 17471 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17472 + ivi.getStatusString()); 17473 } 17474 return; 17475 } 17476 } 17477 17478 // If any filters need to be verified, then all need to be. 17479 boolean needToVerify = false; 17480 for (PackageParser.Activity a : pkg.activities) { 17481 for (ActivityIntentInfo filter : a.intents) { 17482 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17483 if (DEBUG_DOMAIN_VERIFICATION) { 17484 Slog.d(TAG, 17485 "Intent filter needs verification, so processing all filters"); 17486 } 17487 needToVerify = true; 17488 break; 17489 } 17490 } 17491 } 17492 17493 if (needToVerify) { 17494 final int verificationId = mIntentFilterVerificationToken++; 17495 for (PackageParser.Activity a : pkg.activities) { 17496 for (ActivityIntentInfo filter : a.intents) { 17497 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17498 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17499 "Verification needed for IntentFilter:" + filter.toString()); 17500 mIntentFilterVerifier.addOneIntentFilterVerification( 17501 verifierUid, userId, verificationId, filter, packageName); 17502 count++; 17503 } 17504 } 17505 } 17506 } 17507 } 17508 17509 if (count > 0) { 17510 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17511 + " IntentFilter verification" + (count > 1 ? "s" : "") 17512 + " for userId:" + userId); 17513 mIntentFilterVerifier.startVerifications(userId); 17514 } else { 17515 if (DEBUG_DOMAIN_VERIFICATION) { 17516 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17517 } 17518 } 17519 } 17520 17521 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17522 final ComponentName cn = filter.activity.getComponentName(); 17523 final String packageName = cn.getPackageName(); 17524 17525 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17526 packageName); 17527 if (ivi == null) { 17528 return true; 17529 } 17530 int status = ivi.getStatus(); 17531 switch (status) { 17532 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17533 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17534 return true; 17535 17536 default: 17537 // Nothing to do 17538 return false; 17539 } 17540 } 17541 17542 private static boolean isMultiArch(ApplicationInfo info) { 17543 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17544 } 17545 17546 private static boolean isExternal(PackageParser.Package pkg) { 17547 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17548 } 17549 17550 private static boolean isExternal(PackageSetting ps) { 17551 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17552 } 17553 17554 private static boolean isSystemApp(PackageParser.Package pkg) { 17555 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17556 } 17557 17558 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17559 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17560 } 17561 17562 private static boolean isOemApp(PackageParser.Package pkg) { 17563 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 17564 } 17565 17566 private static boolean isVendorApp(PackageParser.Package pkg) { 17567 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 17568 } 17569 17570 private static boolean isProductApp(PackageParser.Package pkg) { 17571 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 17572 } 17573 17574 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17575 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17576 } 17577 17578 private static boolean isSystemApp(PackageSetting ps) { 17579 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17580 } 17581 17582 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17583 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17584 } 17585 17586 private int packageFlagsToInstallFlags(PackageSetting ps) { 17587 int installFlags = 0; 17588 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17589 // This existing package was an external ASEC install when we have 17590 // the external flag without a UUID 17591 installFlags |= PackageManager.INSTALL_EXTERNAL; 17592 } 17593 if (ps.isForwardLocked()) { 17594 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17595 } 17596 return installFlags; 17597 } 17598 17599 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17600 if (isExternal(pkg)) { 17601 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17602 return mSettings.getExternalVersion(); 17603 } else { 17604 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17605 } 17606 } else { 17607 return mSettings.getInternalVersion(); 17608 } 17609 } 17610 17611 private void deleteTempPackageFiles() { 17612 final FilenameFilter filter = new FilenameFilter() { 17613 public boolean accept(File dir, String name) { 17614 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17615 } 17616 }; 17617 for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) { 17618 file.delete(); 17619 } 17620 } 17621 17622 @Override 17623 public void deletePackageAsUser(String packageName, int versionCode, 17624 IPackageDeleteObserver observer, int userId, int flags) { 17625 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17626 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17627 } 17628 17629 @Override 17630 public void deletePackageVersioned(VersionedPackage versionedPackage, 17631 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17632 final int callingUid = Binder.getCallingUid(); 17633 mContext.enforceCallingOrSelfPermission( 17634 android.Manifest.permission.DELETE_PACKAGES, null); 17635 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 17636 Preconditions.checkNotNull(versionedPackage); 17637 Preconditions.checkNotNull(observer); 17638 Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(), 17639 PackageManager.VERSION_CODE_HIGHEST, 17640 Long.MAX_VALUE, "versionCode must be >= -1"); 17641 17642 final String packageName = versionedPackage.getPackageName(); 17643 final long versionCode = versionedPackage.getLongVersionCode(); 17644 final String internalPackageName; 17645 synchronized (mPackages) { 17646 // Normalize package name to handle renamed packages and static libs 17647 internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode); 17648 } 17649 17650 final int uid = Binder.getCallingUid(); 17651 if (!isOrphaned(internalPackageName) 17652 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17653 try { 17654 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17655 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17656 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17657 observer.onUserActionRequired(intent); 17658 } catch (RemoteException re) { 17659 } 17660 return; 17661 } 17662 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17663 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17664 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17665 mContext.enforceCallingOrSelfPermission( 17666 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17667 "deletePackage for user " + userId); 17668 } 17669 17670 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17671 try { 17672 observer.onPackageDeleted(packageName, 17673 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17674 } catch (RemoteException re) { 17675 } 17676 return; 17677 } 17678 17679 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17680 try { 17681 observer.onPackageDeleted(packageName, 17682 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17683 } catch (RemoteException re) { 17684 } 17685 return; 17686 } 17687 17688 if (DEBUG_REMOVE) { 17689 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17690 + " deleteAllUsers: " + deleteAllUsers + " version=" 17691 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17692 ? "VERSION_CODE_HIGHEST" : versionCode)); 17693 } 17694 // Queue up an async operation since the package deletion may take a little while. 17695 mHandler.post(new Runnable() { 17696 public void run() { 17697 mHandler.removeCallbacks(this); 17698 int returnCode; 17699 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 17700 boolean doDeletePackage = true; 17701 if (ps != null) { 17702 final boolean targetIsInstantApp = 17703 ps.getInstantApp(UserHandle.getUserId(callingUid)); 17704 doDeletePackage = !targetIsInstantApp 17705 || canViewInstantApps; 17706 } 17707 if (doDeletePackage) { 17708 if (!deleteAllUsers) { 17709 returnCode = deletePackageX(internalPackageName, versionCode, 17710 userId, deleteFlags); 17711 } else { 17712 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17713 internalPackageName, users); 17714 // If nobody is blocking uninstall, proceed with delete for all users 17715 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17716 returnCode = deletePackageX(internalPackageName, versionCode, 17717 userId, deleteFlags); 17718 } else { 17719 // Otherwise uninstall individually for users with blockUninstalls=false 17720 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17721 for (int userId : users) { 17722 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17723 returnCode = deletePackageX(internalPackageName, versionCode, 17724 userId, userFlags); 17725 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17726 Slog.w(TAG, "Package delete failed for user " + userId 17727 + ", returnCode " + returnCode); 17728 } 17729 } 17730 } 17731 // The app has only been marked uninstalled for certain users. 17732 // We still need to report that delete was blocked 17733 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17734 } 17735 } 17736 } else { 17737 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17738 } 17739 try { 17740 observer.onPackageDeleted(packageName, returnCode, null); 17741 } catch (RemoteException e) { 17742 Log.i(TAG, "Observer no longer exists."); 17743 } //end catch 17744 } //end run 17745 }); 17746 } 17747 17748 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17749 if (pkg.staticSharedLibName != null) { 17750 return pkg.manifestPackageName; 17751 } 17752 return pkg.packageName; 17753 } 17754 17755 private String resolveInternalPackageNameLPr(String packageName, long versionCode) { 17756 // Handle renamed packages 17757 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17758 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17759 17760 // Is this a static library? 17761 LongSparseArray<SharedLibraryEntry> versionedLib = 17762 mStaticLibsByDeclaringPackage.get(packageName); 17763 if (versionedLib == null || versionedLib.size() <= 0) { 17764 return packageName; 17765 } 17766 17767 // Figure out which lib versions the caller can see 17768 LongSparseLongArray versionsCallerCanSee = null; 17769 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17770 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17771 && callingAppId != Process.ROOT_UID) { 17772 versionsCallerCanSee = new LongSparseLongArray(); 17773 String libName = versionedLib.valueAt(0).info.getName(); 17774 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17775 if (uidPackages != null) { 17776 for (String uidPackage : uidPackages) { 17777 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17778 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17779 if (libIdx >= 0) { 17780 final long libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17781 versionsCallerCanSee.append(libVersion, libVersion); 17782 } 17783 } 17784 } 17785 } 17786 17787 // Caller can see nothing - done 17788 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17789 return packageName; 17790 } 17791 17792 // Find the version the caller can see and the app version code 17793 SharedLibraryEntry highestVersion = null; 17794 final int versionCount = versionedLib.size(); 17795 for (int i = 0; i < versionCount; i++) { 17796 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17797 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17798 libEntry.info.getLongVersion()) < 0) { 17799 continue; 17800 } 17801 final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode(); 17802 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17803 if (libVersionCode == versionCode) { 17804 return libEntry.apk; 17805 } 17806 } else if (highestVersion == null) { 17807 highestVersion = libEntry; 17808 } else if (libVersionCode > highestVersion.info 17809 .getDeclaringPackage().getLongVersionCode()) { 17810 highestVersion = libEntry; 17811 } 17812 } 17813 17814 if (highestVersion != null) { 17815 return highestVersion.apk; 17816 } 17817 17818 return packageName; 17819 } 17820 17821 boolean isCallerVerifier(int callingUid) { 17822 final int callingUserId = UserHandle.getUserId(callingUid); 17823 return mRequiredVerifierPackage != null && 17824 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 17825 } 17826 17827 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17828 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17829 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17830 return true; 17831 } 17832 final int callingUserId = UserHandle.getUserId(callingUid); 17833 // If the caller installed the pkgName, then allow it to silently uninstall. 17834 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17835 return true; 17836 } 17837 17838 // Allow package verifier to silently uninstall. 17839 if (mRequiredVerifierPackage != null && 17840 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17841 return true; 17842 } 17843 17844 // Allow package uninstaller to silently uninstall. 17845 if (mRequiredUninstallerPackage != null && 17846 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17847 return true; 17848 } 17849 17850 // Allow storage manager to silently uninstall. 17851 if (mStorageManagerPackage != null && 17852 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17853 return true; 17854 } 17855 17856 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 17857 // uninstall for device owner provisioning. 17858 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 17859 == PERMISSION_GRANTED) { 17860 return true; 17861 } 17862 17863 return false; 17864 } 17865 17866 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17867 int[] result = EMPTY_INT_ARRAY; 17868 for (int userId : userIds) { 17869 if (getBlockUninstallForUser(packageName, userId)) { 17870 result = ArrayUtils.appendInt(result, userId); 17871 } 17872 } 17873 return result; 17874 } 17875 17876 @Override 17877 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17878 final int callingUid = Binder.getCallingUid(); 17879 if (getInstantAppPackageName(callingUid) != null 17880 && !isCallerSameApp(packageName, callingUid)) { 17881 return false; 17882 } 17883 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17884 } 17885 17886 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17887 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17888 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17889 try { 17890 if (dpm != null) { 17891 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17892 /* callingUserOnly =*/ false); 17893 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17894 : deviceOwnerComponentName.getPackageName(); 17895 // Does the package contains the device owner? 17896 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17897 // this check is probably not needed, since DO should be registered as a device 17898 // admin on some user too. (Original bug for this: b/17657954) 17899 if (packageName.equals(deviceOwnerPackageName)) { 17900 return true; 17901 } 17902 // Does it contain a device admin for any user? 17903 int[] users; 17904 if (userId == UserHandle.USER_ALL) { 17905 users = sUserManager.getUserIds(); 17906 } else { 17907 users = new int[]{userId}; 17908 } 17909 for (int i = 0; i < users.length; ++i) { 17910 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17911 return true; 17912 } 17913 } 17914 } 17915 } catch (RemoteException e) { 17916 } 17917 return false; 17918 } 17919 17920 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17921 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17922 } 17923 17924 /** 17925 * This method is an internal method that could be get invoked either 17926 * to delete an installed package or to clean up a failed installation. 17927 * After deleting an installed package, a broadcast is sent to notify any 17928 * listeners that the package has been removed. For cleaning up a failed 17929 * installation, the broadcast is not necessary since the package's 17930 * installation wouldn't have sent the initial broadcast either 17931 * The key steps in deleting a package are 17932 * deleting the package information in internal structures like mPackages, 17933 * deleting the packages base directories through installd 17934 * updating mSettings to reflect current status 17935 * persisting settings for later use 17936 * sending a broadcast if necessary 17937 */ 17938 int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) { 17939 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17940 final boolean res; 17941 17942 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17943 ? UserHandle.USER_ALL : userId; 17944 17945 if (isPackageDeviceAdmin(packageName, removeUser)) { 17946 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17947 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17948 } 17949 17950 PackageSetting uninstalledPs = null; 17951 PackageParser.Package pkg = null; 17952 17953 // for the uninstall-updates case and restricted profiles, remember the per- 17954 // user handle installed state 17955 int[] allUsers; 17956 synchronized (mPackages) { 17957 uninstalledPs = mSettings.mPackages.get(packageName); 17958 if (uninstalledPs == null) { 17959 Slog.w(TAG, "Not removing non-existent package " + packageName); 17960 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17961 } 17962 17963 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17964 && uninstalledPs.versionCode != versionCode) { 17965 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17966 + uninstalledPs.versionCode + " != " + versionCode); 17967 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17968 } 17969 17970 // Static shared libs can be declared by any package, so let us not 17971 // allow removing a package if it provides a lib others depend on. 17972 pkg = mPackages.get(packageName); 17973 17974 allUsers = sUserManager.getUserIds(); 17975 17976 if (pkg != null && pkg.staticSharedLibName != null) { 17977 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17978 pkg.staticSharedLibVersion); 17979 if (libEntry != null) { 17980 for (int currUserId : allUsers) { 17981 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 17982 continue; 17983 } 17984 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17985 libEntry.info, 0, currUserId); 17986 if (!ArrayUtils.isEmpty(libClientPackages)) { 17987 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17988 + " hosting lib " + libEntry.info.getName() + " version " 17989 + libEntry.info.getLongVersion() + " used by " + libClientPackages 17990 + " for user " + currUserId); 17991 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17992 } 17993 } 17994 } 17995 } 17996 17997 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17998 } 17999 18000 final int freezeUser; 18001 if (isUpdatedSystemApp(uninstalledPs) 18002 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 18003 // We're downgrading a system app, which will apply to all users, so 18004 // freeze them all during the downgrade 18005 freezeUser = UserHandle.USER_ALL; 18006 } else { 18007 freezeUser = removeUser; 18008 } 18009 18010 synchronized (mInstallLock) { 18011 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 18012 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 18013 deleteFlags, "deletePackageX")) { 18014 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 18015 deleteFlags | PackageManager.DELETE_CHATTY, info, true, null); 18016 } 18017 synchronized (mPackages) { 18018 if (res) { 18019 if (pkg != null) { 18020 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 18021 } 18022 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 18023 updateInstantAppInstallerLocked(packageName); 18024 } 18025 } 18026 } 18027 18028 if (res) { 18029 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 18030 info.sendPackageRemovedBroadcasts(killApp); 18031 info.sendSystemPackageUpdatedBroadcasts(); 18032 info.sendSystemPackageAppearedBroadcasts(); 18033 } 18034 // Force a gc here. 18035 Runtime.getRuntime().gc(); 18036 // Delete the resources here after sending the broadcast to let 18037 // other processes clean up before deleting resources. 18038 if (info.args != null) { 18039 synchronized (mInstallLock) { 18040 info.args.doPostDeleteLI(true); 18041 } 18042 } 18043 18044 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18045 } 18046 18047 static class PackageRemovedInfo { 18048 final PackageSender packageSender; 18049 String removedPackage; 18050 String installerPackageName; 18051 int uid = -1; 18052 int removedAppId = -1; 18053 int[] origUsers; 18054 int[] removedUsers = null; 18055 int[] broadcastUsers = null; 18056 int[] instantUserIds = null; 18057 SparseArray<Integer> installReasons; 18058 boolean isRemovedPackageSystemUpdate = false; 18059 boolean isUpdate; 18060 boolean dataRemoved; 18061 boolean removedForAllUsers; 18062 boolean isStaticSharedLib; 18063 // Clean up resources deleted packages. 18064 InstallArgs args = null; 18065 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 18066 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 18067 18068 PackageRemovedInfo(PackageSender packageSender) { 18069 this.packageSender = packageSender; 18070 } 18071 18072 void sendPackageRemovedBroadcasts(boolean killApp) { 18073 sendPackageRemovedBroadcastInternal(killApp); 18074 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 18075 for (int i = 0; i < childCount; i++) { 18076 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18077 childInfo.sendPackageRemovedBroadcastInternal(killApp); 18078 } 18079 } 18080 18081 void sendSystemPackageUpdatedBroadcasts() { 18082 if (isRemovedPackageSystemUpdate) { 18083 sendSystemPackageUpdatedBroadcastsInternal(); 18084 final int childCount = (removedChildPackages != null) 18085 ? removedChildPackages.size() : 0; 18086 for (int i = 0; i < childCount; i++) { 18087 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18088 if (childInfo.isRemovedPackageSystemUpdate) { 18089 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 18090 } 18091 } 18092 } 18093 } 18094 18095 void sendSystemPackageAppearedBroadcasts() { 18096 final int packageCount = (appearedChildPackages != null) 18097 ? appearedChildPackages.size() : 0; 18098 for (int i = 0; i < packageCount; i++) { 18099 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 18100 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 18101 true /*sendBootCompleted*/, false /*startReceiver*/, 18102 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null); 18103 } 18104 } 18105 18106 private void sendSystemPackageUpdatedBroadcastsInternal() { 18107 Bundle extras = new Bundle(2); 18108 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18109 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18110 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18111 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 18112 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18113 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 18114 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 18115 null, null, 0, removedPackage, null, null, null); 18116 if (installerPackageName != null) { 18117 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18118 removedPackage, extras, 0 /*flags*/, 18119 installerPackageName, null, null, null); 18120 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18121 removedPackage, extras, 0 /*flags*/, 18122 installerPackageName, null, null, null); 18123 } 18124 } 18125 18126 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 18127 // Don't send static shared library removal broadcasts as these 18128 // libs are visible only the the apps that depend on them an one 18129 // cannot remove the library if it has a dependency. 18130 if (isStaticSharedLib) { 18131 return; 18132 } 18133 Bundle extras = new Bundle(2); 18134 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18135 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 18136 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 18137 if (isUpdate || isRemovedPackageSystemUpdate) { 18138 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18139 } 18140 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 18141 if (removedPackage != null) { 18142 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18143 removedPackage, extras, 0, null /*targetPackage*/, null, 18144 broadcastUsers, instantUserIds); 18145 if (installerPackageName != null) { 18146 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18147 removedPackage, extras, 0 /*flags*/, 18148 installerPackageName, null, broadcastUsers, instantUserIds); 18149 } 18150 if (dataRemoved && !isRemovedPackageSystemUpdate) { 18151 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 18152 removedPackage, extras, 18153 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18154 null, null, broadcastUsers, instantUserIds); 18155 packageSender.notifyPackageRemoved(removedPackage); 18156 } 18157 } 18158 if (removedAppId >= 0) { 18159 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 18160 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18161 null, null, broadcastUsers, instantUserIds); 18162 } 18163 } 18164 18165 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 18166 removedUsers = userIds; 18167 if (removedUsers == null) { 18168 broadcastUsers = null; 18169 return; 18170 } 18171 18172 broadcastUsers = EMPTY_INT_ARRAY; 18173 instantUserIds = EMPTY_INT_ARRAY; 18174 for (int i = userIds.length - 1; i >= 0; --i) { 18175 final int userId = userIds[i]; 18176 if (deletedPackageSetting.getInstantApp(userId)) { 18177 instantUserIds = ArrayUtils.appendInt(instantUserIds, userId); 18178 } else { 18179 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 18180 } 18181 } 18182 } 18183 } 18184 18185 /* 18186 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 18187 * flag is not set, the data directory is removed as well. 18188 * make sure this flag is set for partially installed apps. If not its meaningless to 18189 * delete a partially installed application. 18190 */ 18191 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 18192 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 18193 String packageName = ps.name; 18194 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 18195 // Retrieve object to delete permissions for shared user later on 18196 final PackageParser.Package deletedPkg; 18197 final PackageSetting deletedPs; 18198 // reader 18199 synchronized (mPackages) { 18200 deletedPkg = mPackages.get(packageName); 18201 deletedPs = mSettings.mPackages.get(packageName); 18202 if (outInfo != null) { 18203 outInfo.removedPackage = packageName; 18204 outInfo.installerPackageName = ps.installerPackageName; 18205 outInfo.isStaticSharedLib = deletedPkg != null 18206 && deletedPkg.staticSharedLibName != null; 18207 outInfo.populateUsers(deletedPs == null ? null 18208 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 18209 } 18210 } 18211 18212 removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0); 18213 18214 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 18215 final PackageParser.Package resolvedPkg; 18216 if (deletedPkg != null) { 18217 resolvedPkg = deletedPkg; 18218 } else { 18219 // We don't have a parsed package when it lives on an ejected 18220 // adopted storage device, so fake something together 18221 resolvedPkg = new PackageParser.Package(ps.name); 18222 resolvedPkg.setVolumeUuid(ps.volumeUuid); 18223 } 18224 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 18225 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18226 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 18227 if (outInfo != null) { 18228 outInfo.dataRemoved = true; 18229 } 18230 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 18231 } 18232 18233 int removedAppId = -1; 18234 18235 // writer 18236 synchronized (mPackages) { 18237 boolean installedStateChanged = false; 18238 if (deletedPs != null) { 18239 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 18240 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 18241 clearDefaultBrowserIfNeeded(packageName); 18242 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 18243 removedAppId = mSettings.removePackageLPw(packageName); 18244 if (outInfo != null) { 18245 outInfo.removedAppId = removedAppId; 18246 } 18247 mPermissionManager.updatePermissions( 18248 deletedPs.name, null, false, mPackages.values(), mPermissionCallback); 18249 if (deletedPs.sharedUser != null) { 18250 // Remove permissions associated with package. Since runtime 18251 // permissions are per user we have to kill the removed package 18252 // or packages running under the shared user of the removed 18253 // package if revoking the permissions requested only by the removed 18254 // package is successful and this causes a change in gids. 18255 for (int userId : UserManagerService.getInstance().getUserIds()) { 18256 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 18257 userId); 18258 if (userIdToKill == UserHandle.USER_ALL 18259 || userIdToKill >= UserHandle.USER_SYSTEM) { 18260 // If gids changed for this user, kill all affected packages. 18261 mHandler.post(new Runnable() { 18262 @Override 18263 public void run() { 18264 // This has to happen with no lock held. 18265 killApplication(deletedPs.name, deletedPs.appId, 18266 KILL_APP_REASON_GIDS_CHANGED); 18267 } 18268 }); 18269 break; 18270 } 18271 } 18272 } 18273 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 18274 } 18275 // make sure to preserve per-user disabled state if this removal was just 18276 // a downgrade of a system app to the factory package 18277 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 18278 if (DEBUG_REMOVE) { 18279 Slog.d(TAG, "Propagating install state across downgrade"); 18280 } 18281 for (int userId : allUserHandles) { 18282 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18283 if (DEBUG_REMOVE) { 18284 Slog.d(TAG, " user " + userId + " => " + installed); 18285 } 18286 if (installed != ps.getInstalled(userId)) { 18287 installedStateChanged = true; 18288 } 18289 ps.setInstalled(installed, userId); 18290 } 18291 } 18292 } 18293 // can downgrade to reader 18294 if (writeSettings) { 18295 // Save settings now 18296 mSettings.writeLPr(); 18297 } 18298 if (installedStateChanged) { 18299 mSettings.writeKernelMappingLPr(ps); 18300 } 18301 } 18302 if (removedAppId != -1) { 18303 // A user ID was deleted here. Go through all users and remove it 18304 // from KeyStore. 18305 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 18306 } 18307 } 18308 18309 static boolean locationIsPrivileged(String path) { 18310 try { 18311 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 18312 final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 18313 final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app"); 18314 final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 18315 return path.startsWith(privilegedAppDir.getCanonicalPath()) 18316 || path.startsWith(privilegedVendorAppDir.getCanonicalPath()) 18317 || path.startsWith(privilegedOdmAppDir.getCanonicalPath()) 18318 || path.startsWith(privilegedProductAppDir.getCanonicalPath()); 18319 } catch (IOException e) { 18320 Slog.e(TAG, "Unable to access code path " + path); 18321 } 18322 return false; 18323 } 18324 18325 static boolean locationIsOem(String path) { 18326 try { 18327 return path.startsWith(Environment.getOemDirectory().getCanonicalPath()); 18328 } catch (IOException e) { 18329 Slog.e(TAG, "Unable to access code path " + path); 18330 } 18331 return false; 18332 } 18333 18334 static boolean locationIsVendor(String path) { 18335 try { 18336 return path.startsWith(Environment.getVendorDirectory().getCanonicalPath()) 18337 || path.startsWith(Environment.getOdmDirectory().getCanonicalPath()); 18338 } catch (IOException e) { 18339 Slog.e(TAG, "Unable to access code path " + path); 18340 } 18341 return false; 18342 } 18343 18344 static boolean locationIsProduct(String path) { 18345 try { 18346 return path.startsWith(Environment.getProductDirectory().getCanonicalPath()); 18347 } catch (IOException e) { 18348 Slog.e(TAG, "Unable to access code path " + path); 18349 } 18350 return false; 18351 } 18352 18353 /* 18354 * Tries to delete system package. 18355 */ 18356 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 18357 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 18358 boolean writeSettings) { 18359 if (deletedPs.parentPackageName != null) { 18360 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 18361 return false; 18362 } 18363 18364 final boolean applyUserRestrictions 18365 = (allUserHandles != null) && (outInfo.origUsers != null); 18366 final PackageSetting disabledPs; 18367 // Confirm if the system package has been updated 18368 // An updated system app can be deleted. This will also have to restore 18369 // the system pkg from system partition 18370 // reader 18371 synchronized (mPackages) { 18372 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 18373 } 18374 18375 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 18376 + " disabledPs=" + disabledPs); 18377 18378 if (disabledPs == null) { 18379 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 18380 return false; 18381 } else if (DEBUG_REMOVE) { 18382 Slog.d(TAG, "Deleting system pkg from data partition"); 18383 } 18384 18385 if (DEBUG_REMOVE) { 18386 if (applyUserRestrictions) { 18387 Slog.d(TAG, "Remembering install states:"); 18388 for (int userId : allUserHandles) { 18389 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 18390 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 18391 } 18392 } 18393 } 18394 18395 // Delete the updated package 18396 outInfo.isRemovedPackageSystemUpdate = true; 18397 if (outInfo.removedChildPackages != null) { 18398 final int childCount = (deletedPs.childPackageNames != null) 18399 ? deletedPs.childPackageNames.size() : 0; 18400 for (int i = 0; i < childCount; i++) { 18401 String childPackageName = deletedPs.childPackageNames.get(i); 18402 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 18403 .contains(childPackageName)) { 18404 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18405 childPackageName); 18406 if (childInfo != null) { 18407 childInfo.isRemovedPackageSystemUpdate = true; 18408 } 18409 } 18410 } 18411 } 18412 18413 if (disabledPs.versionCode < deletedPs.versionCode) { 18414 // Delete data for downgrades 18415 flags &= ~PackageManager.DELETE_KEEP_DATA; 18416 } else { 18417 // Preserve data by setting flag 18418 flags |= PackageManager.DELETE_KEEP_DATA; 18419 } 18420 18421 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 18422 outInfo, writeSettings, disabledPs.pkg); 18423 if (!ret) { 18424 return false; 18425 } 18426 18427 // writer 18428 synchronized (mPackages) { 18429 // NOTE: The system package always needs to be enabled; even if it's for 18430 // a compressed stub. If we don't, installing the system package fails 18431 // during scan [scanning checks the disabled packages]. We will reverse 18432 // this later, after we've "installed" the stub. 18433 // Reinstate the old system package 18434 enableSystemPackageLPw(disabledPs.pkg); 18435 // Remove any native libraries from the upgraded package. 18436 removeNativeBinariesLI(deletedPs); 18437 } 18438 18439 // Install the system package 18440 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18441 try { 18442 installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles, 18443 outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings); 18444 } catch (PackageManagerException e) { 18445 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18446 + e.getMessage()); 18447 return false; 18448 } finally { 18449 if (disabledPs.pkg.isStub) { 18450 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/); 18451 } 18452 } 18453 return true; 18454 } 18455 18456 /** 18457 * Installs a package that's already on the system partition. 18458 */ 18459 private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString, 18460 boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 18461 @Nullable PermissionsState origPermissionState, boolean writeSettings) 18462 throws PackageManagerException { 18463 @ParseFlags int parseFlags = 18464 mDefParseFlags 18465 | PackageParser.PARSE_MUST_BE_APK 18466 | PackageParser.PARSE_IS_SYSTEM_DIR; 18467 @ScanFlags int scanFlags = SCAN_AS_SYSTEM; 18468 if (isPrivileged || locationIsPrivileged(codePathString)) { 18469 scanFlags |= SCAN_AS_PRIVILEGED; 18470 } 18471 if (locationIsOem(codePathString)) { 18472 scanFlags |= SCAN_AS_OEM; 18473 } 18474 if (locationIsVendor(codePathString)) { 18475 scanFlags |= SCAN_AS_VENDOR; 18476 } 18477 if (locationIsProduct(codePathString)) { 18478 scanFlags |= SCAN_AS_PRODUCT; 18479 } 18480 18481 final File codePath = new File(codePathString); 18482 final PackageParser.Package pkg = 18483 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null); 18484 18485 try { 18486 // update shared libraries for the newly re-installed system package 18487 updateSharedLibrariesLPr(pkg, null); 18488 } catch (PackageManagerException e) { 18489 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18490 } 18491 18492 prepareAppDataAfterInstallLIF(pkg); 18493 18494 // writer 18495 synchronized (mPackages) { 18496 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 18497 18498 // Propagate the permissions state as we do not want to drop on the floor 18499 // runtime permissions. The update permissions method below will take 18500 // care of removing obsolete permissions and grant install permissions. 18501 if (origPermissionState != null) { 18502 ps.getPermissionsState().copyFrom(origPermissionState); 18503 } 18504 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 18505 mPermissionCallback); 18506 18507 final boolean applyUserRestrictions 18508 = (allUserHandles != null) && (origUserHandles != null); 18509 if (applyUserRestrictions) { 18510 boolean installedStateChanged = false; 18511 if (DEBUG_REMOVE) { 18512 Slog.d(TAG, "Propagating install state across reinstall"); 18513 } 18514 for (int userId : allUserHandles) { 18515 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 18516 if (DEBUG_REMOVE) { 18517 Slog.d(TAG, " user " + userId + " => " + installed); 18518 } 18519 if (installed != ps.getInstalled(userId)) { 18520 installedStateChanged = true; 18521 } 18522 ps.setInstalled(installed, userId); 18523 18524 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18525 } 18526 // Regardless of writeSettings we need to ensure that this restriction 18527 // state propagation is persisted 18528 mSettings.writeAllUsersPackageRestrictionsLPr(); 18529 if (installedStateChanged) { 18530 mSettings.writeKernelMappingLPr(ps); 18531 } 18532 } 18533 // can downgrade to reader here 18534 if (writeSettings) { 18535 mSettings.writeLPr(); 18536 } 18537 } 18538 return pkg; 18539 } 18540 18541 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18542 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18543 PackageRemovedInfo outInfo, boolean writeSettings, 18544 PackageParser.Package replacingPackage) { 18545 synchronized (mPackages) { 18546 if (outInfo != null) { 18547 outInfo.uid = ps.appId; 18548 } 18549 18550 if (outInfo != null && outInfo.removedChildPackages != null) { 18551 final int childCount = (ps.childPackageNames != null) 18552 ? ps.childPackageNames.size() : 0; 18553 for (int i = 0; i < childCount; i++) { 18554 String childPackageName = ps.childPackageNames.get(i); 18555 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18556 if (childPs == null) { 18557 return false; 18558 } 18559 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18560 childPackageName); 18561 if (childInfo != null) { 18562 childInfo.uid = childPs.appId; 18563 } 18564 } 18565 } 18566 } 18567 18568 // Delete package data from internal structures and also remove data if flag is set 18569 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18570 18571 // Delete the child packages data 18572 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18573 for (int i = 0; i < childCount; i++) { 18574 PackageSetting childPs; 18575 synchronized (mPackages) { 18576 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18577 } 18578 if (childPs != null) { 18579 PackageRemovedInfo childOutInfo = (outInfo != null 18580 && outInfo.removedChildPackages != null) 18581 ? outInfo.removedChildPackages.get(childPs.name) : null; 18582 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18583 && (replacingPackage != null 18584 && !replacingPackage.hasChildPackage(childPs.name)) 18585 ? flags & ~DELETE_KEEP_DATA : flags; 18586 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18587 deleteFlags, writeSettings); 18588 } 18589 } 18590 18591 // Delete application code and resources only for parent packages 18592 if (ps.parentPackageName == null) { 18593 if (deleteCodeAndResources && (outInfo != null)) { 18594 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18595 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18596 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18597 } 18598 } 18599 18600 return true; 18601 } 18602 18603 @Override 18604 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18605 int userId) { 18606 mContext.enforceCallingOrSelfPermission( 18607 android.Manifest.permission.DELETE_PACKAGES, null); 18608 synchronized (mPackages) { 18609 // Cannot block uninstall of static shared libs as they are 18610 // considered a part of the using app (emulating static linking). 18611 // Also static libs are installed always on internal storage. 18612 PackageParser.Package pkg = mPackages.get(packageName); 18613 if (pkg != null && pkg.staticSharedLibName != null) { 18614 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18615 + " providing static shared library: " + pkg.staticSharedLibName); 18616 return false; 18617 } 18618 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 18619 mSettings.writePackageRestrictionsLPr(userId); 18620 } 18621 return true; 18622 } 18623 18624 @Override 18625 public boolean getBlockUninstallForUser(String packageName, int userId) { 18626 synchronized (mPackages) { 18627 final PackageSetting ps = mSettings.mPackages.get(packageName); 18628 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 18629 return false; 18630 } 18631 return mSettings.getBlockUninstallLPr(userId, packageName); 18632 } 18633 } 18634 18635 @Override 18636 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18637 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 18638 synchronized (mPackages) { 18639 PackageSetting ps = mSettings.mPackages.get(packageName); 18640 if (ps == null) { 18641 Log.w(TAG, "Package doesn't exist: " + packageName); 18642 return false; 18643 } 18644 if (systemUserApp) { 18645 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18646 } else { 18647 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18648 } 18649 mSettings.writeLPr(); 18650 } 18651 return true; 18652 } 18653 18654 /* 18655 * This method handles package deletion in general 18656 */ 18657 private boolean deletePackageLIF(String packageName, UserHandle user, 18658 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18659 PackageRemovedInfo outInfo, boolean writeSettings, 18660 PackageParser.Package replacingPackage) { 18661 if (packageName == null) { 18662 Slog.w(TAG, "Attempt to delete null packageName."); 18663 return false; 18664 } 18665 18666 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18667 18668 PackageSetting ps; 18669 synchronized (mPackages) { 18670 ps = mSettings.mPackages.get(packageName); 18671 if (ps == null) { 18672 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18673 return false; 18674 } 18675 18676 if (ps.parentPackageName != null && (!isSystemApp(ps) 18677 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18678 if (DEBUG_REMOVE) { 18679 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18680 + ((user == null) ? UserHandle.USER_ALL : user)); 18681 } 18682 final int removedUserId = (user != null) ? user.getIdentifier() 18683 : UserHandle.USER_ALL; 18684 18685 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18686 return false; 18687 } 18688 markPackageUninstalledForUserLPw(ps, user); 18689 scheduleWritePackageRestrictionsLocked(user); 18690 return true; 18691 } 18692 } 18693 18694 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 18695 if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) { 18696 onSuspendingPackageRemoved(packageName, userId); 18697 } 18698 18699 18700 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18701 && user.getIdentifier() != UserHandle.USER_ALL)) { 18702 // The caller is asking that the package only be deleted for a single 18703 // user. To do this, we just mark its uninstalled state and delete 18704 // its data. If this is a system app, we only allow this to happen if 18705 // they have set the special DELETE_SYSTEM_APP which requests different 18706 // semantics than normal for uninstalling system apps. 18707 markPackageUninstalledForUserLPw(ps, user); 18708 18709 if (!isSystemApp(ps)) { 18710 // Do not uninstall the APK if an app should be cached 18711 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18712 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18713 // Other user still have this package installed, so all 18714 // we need to do is clear this user's data and save that 18715 // it is uninstalled. 18716 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18717 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18718 return false; 18719 } 18720 scheduleWritePackageRestrictionsLocked(user); 18721 return true; 18722 } else { 18723 // We need to set it back to 'installed' so the uninstall 18724 // broadcasts will be sent correctly. 18725 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18726 ps.setInstalled(true, user.getIdentifier()); 18727 mSettings.writeKernelMappingLPr(ps); 18728 } 18729 } else { 18730 // This is a system app, so we assume that the 18731 // other users still have this package installed, so all 18732 // we need to do is clear this user's data and save that 18733 // it is uninstalled. 18734 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18735 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18736 return false; 18737 } 18738 scheduleWritePackageRestrictionsLocked(user); 18739 return true; 18740 } 18741 } 18742 18743 // If we are deleting a composite package for all users, keep track 18744 // of result for each child. 18745 if (ps.childPackageNames != null && outInfo != null) { 18746 synchronized (mPackages) { 18747 final int childCount = ps.childPackageNames.size(); 18748 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18749 for (int i = 0; i < childCount; i++) { 18750 String childPackageName = ps.childPackageNames.get(i); 18751 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18752 childInfo.removedPackage = childPackageName; 18753 childInfo.installerPackageName = ps.installerPackageName; 18754 outInfo.removedChildPackages.put(childPackageName, childInfo); 18755 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18756 if (childPs != null) { 18757 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18758 } 18759 } 18760 } 18761 } 18762 18763 boolean ret = false; 18764 if (isSystemApp(ps)) { 18765 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18766 // When an updated system application is deleted we delete the existing resources 18767 // as well and fall back to existing code in system partition 18768 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18769 } else { 18770 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18771 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18772 outInfo, writeSettings, replacingPackage); 18773 } 18774 18775 // Take a note whether we deleted the package for all users 18776 if (outInfo != null) { 18777 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18778 if (outInfo.removedChildPackages != null) { 18779 synchronized (mPackages) { 18780 final int childCount = outInfo.removedChildPackages.size(); 18781 for (int i = 0; i < childCount; i++) { 18782 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18783 if (childInfo != null) { 18784 childInfo.removedForAllUsers = mPackages.get( 18785 childInfo.removedPackage) == null; 18786 } 18787 } 18788 } 18789 } 18790 // If we uninstalled an update to a system app there may be some 18791 // child packages that appeared as they are declared in the system 18792 // app but were not declared in the update. 18793 if (isSystemApp(ps)) { 18794 synchronized (mPackages) { 18795 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18796 final int childCount = (updatedPs.childPackageNames != null) 18797 ? updatedPs.childPackageNames.size() : 0; 18798 for (int i = 0; i < childCount; i++) { 18799 String childPackageName = updatedPs.childPackageNames.get(i); 18800 if (outInfo.removedChildPackages == null 18801 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18802 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18803 if (childPs == null) { 18804 continue; 18805 } 18806 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18807 installRes.name = childPackageName; 18808 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18809 installRes.pkg = mPackages.get(childPackageName); 18810 installRes.uid = childPs.pkg.applicationInfo.uid; 18811 if (outInfo.appearedChildPackages == null) { 18812 outInfo.appearedChildPackages = new ArrayMap<>(); 18813 } 18814 outInfo.appearedChildPackages.put(childPackageName, installRes); 18815 } 18816 } 18817 } 18818 } 18819 } 18820 18821 return ret; 18822 } 18823 18824 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18825 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18826 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18827 for (int nextUserId : userIds) { 18828 if (DEBUG_REMOVE) { 18829 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18830 } 18831 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18832 false /*installed*/, 18833 true /*stopped*/, 18834 true /*notLaunched*/, 18835 false /*hidden*/, 18836 false /*suspended*/, 18837 null, /*suspendingPackage*/ 18838 null, /*suspendedAppExtras*/ 18839 null, /*suspendedLauncherExtras*/ 18840 false /*instantApp*/, 18841 false /*virtualPreload*/, 18842 null /*lastDisableAppCaller*/, 18843 null /*enabledComponents*/, 18844 null /*disabledComponents*/, 18845 ps.readUserState(nextUserId).domainVerificationStatus, 18846 0, PackageManager.INSTALL_REASON_UNKNOWN, 18847 null /*harmfulAppWarning*/); 18848 } 18849 mSettings.writeKernelMappingLPr(ps); 18850 } 18851 18852 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18853 PackageRemovedInfo outInfo) { 18854 final PackageParser.Package pkg; 18855 synchronized (mPackages) { 18856 pkg = mPackages.get(ps.name); 18857 } 18858 18859 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18860 : new int[] {userId}; 18861 for (int nextUserId : userIds) { 18862 if (DEBUG_REMOVE) { 18863 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18864 + nextUserId); 18865 } 18866 18867 destroyAppDataLIF(pkg, userId, 18868 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18869 destroyAppProfilesLIF(pkg, userId); 18870 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18871 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18872 schedulePackageCleaning(ps.name, nextUserId, false); 18873 synchronized (mPackages) { 18874 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18875 scheduleWritePackageRestrictionsLocked(nextUserId); 18876 } 18877 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18878 } 18879 } 18880 18881 if (outInfo != null) { 18882 outInfo.removedPackage = ps.name; 18883 outInfo.installerPackageName = ps.installerPackageName; 18884 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18885 outInfo.removedAppId = ps.appId; 18886 outInfo.removedUsers = userIds; 18887 outInfo.broadcastUsers = userIds; 18888 } 18889 18890 return true; 18891 } 18892 18893 private static final class ClearStorageConnection implements ServiceConnection { 18894 IMediaContainerService mContainerService; 18895 18896 @Override 18897 public void onServiceConnected(ComponentName name, IBinder service) { 18898 synchronized (this) { 18899 mContainerService = IMediaContainerService.Stub 18900 .asInterface(Binder.allowBlocking(service)); 18901 notifyAll(); 18902 } 18903 } 18904 18905 @Override 18906 public void onServiceDisconnected(ComponentName name) { 18907 } 18908 } 18909 18910 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18911 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18912 18913 final boolean mounted; 18914 if (Environment.isExternalStorageEmulated()) { 18915 mounted = true; 18916 } else { 18917 final String status = Environment.getExternalStorageState(); 18918 18919 mounted = status.equals(Environment.MEDIA_MOUNTED) 18920 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18921 } 18922 18923 if (!mounted) { 18924 return; 18925 } 18926 18927 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18928 int[] users; 18929 if (userId == UserHandle.USER_ALL) { 18930 users = sUserManager.getUserIds(); 18931 } else { 18932 users = new int[] { userId }; 18933 } 18934 final ClearStorageConnection conn = new ClearStorageConnection(); 18935 if (mContext.bindServiceAsUser( 18936 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18937 try { 18938 for (int curUser : users) { 18939 long timeout = SystemClock.uptimeMillis() + 5000; 18940 synchronized (conn) { 18941 long now; 18942 while (conn.mContainerService == null && 18943 (now = SystemClock.uptimeMillis()) < timeout) { 18944 try { 18945 conn.wait(timeout - now); 18946 } catch (InterruptedException e) { 18947 } 18948 } 18949 } 18950 if (conn.mContainerService == null) { 18951 return; 18952 } 18953 18954 final UserEnvironment userEnv = new UserEnvironment(curUser); 18955 clearDirectory(conn.mContainerService, 18956 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18957 if (allData) { 18958 clearDirectory(conn.mContainerService, 18959 userEnv.buildExternalStorageAppDataDirs(packageName)); 18960 clearDirectory(conn.mContainerService, 18961 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18962 } 18963 } 18964 } finally { 18965 mContext.unbindService(conn); 18966 } 18967 } 18968 } 18969 18970 @Override 18971 public void clearApplicationProfileData(String packageName) { 18972 enforceSystemOrRoot("Only the system can clear all profile data"); 18973 18974 final PackageParser.Package pkg; 18975 synchronized (mPackages) { 18976 pkg = mPackages.get(packageName); 18977 } 18978 18979 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18980 synchronized (mInstallLock) { 18981 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18982 } 18983 } 18984 } 18985 18986 @Override 18987 public void clearApplicationUserData(final String packageName, 18988 final IPackageDataObserver observer, final int userId) { 18989 mContext.enforceCallingOrSelfPermission( 18990 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18991 18992 final int callingUid = Binder.getCallingUid(); 18993 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18994 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18995 18996 final PackageSetting ps = mSettings.getPackageLPr(packageName); 18997 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 18998 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18999 throw new SecurityException("Cannot clear data for a protected package: " 19000 + packageName); 19001 } 19002 // Queue up an async operation since the package deletion may take a little while. 19003 mHandler.post(new Runnable() { 19004 public void run() { 19005 mHandler.removeCallbacks(this); 19006 final boolean succeeded; 19007 if (!filterApp) { 19008 try (PackageFreezer freezer = freezePackage(packageName, 19009 "clearApplicationUserData")) { 19010 synchronized (mInstallLock) { 19011 succeeded = clearApplicationUserDataLIF(packageName, userId); 19012 } 19013 clearExternalStorageDataSync(packageName, userId, true); 19014 synchronized (mPackages) { 19015 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 19016 packageName, userId); 19017 } 19018 } 19019 if (succeeded) { 19020 // invoke DeviceStorageMonitor's update method to clear any notifications 19021 DeviceStorageMonitorInternal dsm = LocalServices 19022 .getService(DeviceStorageMonitorInternal.class); 19023 if (dsm != null) { 19024 dsm.checkMemory(); 19025 } 19026 } 19027 } else { 19028 succeeded = false; 19029 } 19030 if (observer != null) { 19031 try { 19032 observer.onRemoveCompleted(packageName, succeeded); 19033 } catch (RemoteException e) { 19034 Log.i(TAG, "Observer no longer exists."); 19035 } 19036 } //end if observer 19037 } //end run 19038 }); 19039 } 19040 19041 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 19042 if (packageName == null) { 19043 Slog.w(TAG, "Attempt to delete null packageName."); 19044 return false; 19045 } 19046 19047 // Try finding details about the requested package 19048 PackageParser.Package pkg; 19049 synchronized (mPackages) { 19050 pkg = mPackages.get(packageName); 19051 if (pkg == null) { 19052 final PackageSetting ps = mSettings.mPackages.get(packageName); 19053 if (ps != null) { 19054 pkg = ps.pkg; 19055 } 19056 } 19057 19058 if (pkg == null) { 19059 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 19060 return false; 19061 } 19062 19063 PackageSetting ps = (PackageSetting) pkg.mExtras; 19064 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 19065 } 19066 19067 clearAppDataLIF(pkg, userId, 19068 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19069 19070 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19071 removeKeystoreDataIfNeeded(userId, appId); 19072 19073 UserManagerInternal umInternal = getUserManagerInternal(); 19074 final int flags; 19075 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 19076 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19077 } else if (umInternal.isUserRunning(userId)) { 19078 flags = StorageManager.FLAG_STORAGE_DE; 19079 } else { 19080 flags = 0; 19081 } 19082 prepareAppDataContentsLIF(pkg, userId, flags); 19083 19084 return true; 19085 } 19086 19087 /** 19088 * Reverts user permission state changes (permissions and flags) in 19089 * all packages for a given user. 19090 * 19091 * @param userId The device user for which to do a reset. 19092 */ 19093 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 19094 final int packageCount = mPackages.size(); 19095 for (int i = 0; i < packageCount; i++) { 19096 PackageParser.Package pkg = mPackages.valueAt(i); 19097 PackageSetting ps = (PackageSetting) pkg.mExtras; 19098 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 19099 } 19100 } 19101 19102 private void resetNetworkPolicies(int userId) { 19103 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 19104 } 19105 19106 /** 19107 * Reverts user permission state changes (permissions and flags). 19108 * 19109 * @param ps The package for which to reset. 19110 * @param userId The device user for which to do a reset. 19111 */ 19112 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 19113 final PackageSetting ps, final int userId) { 19114 if (ps.pkg == null) { 19115 return; 19116 } 19117 19118 // These are flags that can change base on user actions. 19119 final int userSettableMask = FLAG_PERMISSION_USER_SET 19120 | FLAG_PERMISSION_USER_FIXED 19121 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 19122 | FLAG_PERMISSION_REVIEW_REQUIRED; 19123 19124 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 19125 | FLAG_PERMISSION_POLICY_FIXED; 19126 19127 boolean writeInstallPermissions = false; 19128 boolean writeRuntimePermissions = false; 19129 19130 final int permissionCount = ps.pkg.requestedPermissions.size(); 19131 for (int i = 0; i < permissionCount; i++) { 19132 final String permName = ps.pkg.requestedPermissions.get(i); 19133 final BasePermission bp = 19134 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 19135 if (bp == null) { 19136 continue; 19137 } 19138 19139 // If shared user we just reset the state to which only this app contributed. 19140 if (ps.sharedUser != null) { 19141 boolean used = false; 19142 final int packageCount = ps.sharedUser.packages.size(); 19143 for (int j = 0; j < packageCount; j++) { 19144 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 19145 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 19146 && pkg.pkg.requestedPermissions.contains(permName)) { 19147 used = true; 19148 break; 19149 } 19150 } 19151 if (used) { 19152 continue; 19153 } 19154 } 19155 19156 final PermissionsState permissionsState = ps.getPermissionsState(); 19157 19158 final int oldFlags = permissionsState.getPermissionFlags(permName, userId); 19159 19160 // Always clear the user settable flags. 19161 final boolean hasInstallState = 19162 permissionsState.getInstallPermissionState(permName) != null; 19163 // If permission review is enabled and this is a legacy app, mark the 19164 // permission as requiring a review as this is the initial state. 19165 int flags = 0; 19166 if (mSettings.mPermissions.mPermissionReviewRequired 19167 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 19168 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 19169 } 19170 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 19171 if (hasInstallState) { 19172 writeInstallPermissions = true; 19173 } else { 19174 writeRuntimePermissions = true; 19175 } 19176 } 19177 19178 // Below is only runtime permission handling. 19179 if (!bp.isRuntime()) { 19180 continue; 19181 } 19182 19183 // Never clobber system or policy. 19184 if ((oldFlags & policyOrSystemFlags) != 0) { 19185 continue; 19186 } 19187 19188 // If this permission was granted by default, make sure it is. 19189 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 19190 if (permissionsState.grantRuntimePermission(bp, userId) 19191 != PERMISSION_OPERATION_FAILURE) { 19192 writeRuntimePermissions = true; 19193 } 19194 // If permission review is enabled the permissions for a legacy apps 19195 // are represented as constantly granted runtime ones, so don't revoke. 19196 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 19197 // Otherwise, reset the permission. 19198 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 19199 switch (revokeResult) { 19200 case PERMISSION_OPERATION_SUCCESS: 19201 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 19202 writeRuntimePermissions = true; 19203 final int appId = ps.appId; 19204 mHandler.post(new Runnable() { 19205 @Override 19206 public void run() { 19207 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 19208 } 19209 }); 19210 } break; 19211 } 19212 } 19213 } 19214 19215 // Synchronously write as we are taking permissions away. 19216 if (writeRuntimePermissions) { 19217 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 19218 } 19219 19220 // Synchronously write as we are taking permissions away. 19221 if (writeInstallPermissions) { 19222 mSettings.writeLPr(); 19223 } 19224 } 19225 19226 /** 19227 * Remove entries from the keystore daemon. Will only remove it if the 19228 * {@code appId} is valid. 19229 */ 19230 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 19231 if (appId < 0) { 19232 return; 19233 } 19234 19235 final KeyStore keyStore = KeyStore.getInstance(); 19236 if (keyStore != null) { 19237 if (userId == UserHandle.USER_ALL) { 19238 for (final int individual : sUserManager.getUserIds()) { 19239 keyStore.clearUid(UserHandle.getUid(individual, appId)); 19240 } 19241 } else { 19242 keyStore.clearUid(UserHandle.getUid(userId, appId)); 19243 } 19244 } else { 19245 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 19246 } 19247 } 19248 19249 @Override 19250 public void deleteApplicationCacheFiles(final String packageName, 19251 final IPackageDataObserver observer) { 19252 final int userId = UserHandle.getCallingUserId(); 19253 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 19254 } 19255 19256 @Override 19257 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 19258 final IPackageDataObserver observer) { 19259 final int callingUid = Binder.getCallingUid(); 19260 if (mContext.checkCallingOrSelfPermission( 19261 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES) 19262 != PackageManager.PERMISSION_GRANTED) { 19263 // If the caller has the old delete cache permission, silently ignore. Else throw. 19264 if (mContext.checkCallingOrSelfPermission( 19265 android.Manifest.permission.DELETE_CACHE_FILES) 19266 == PackageManager.PERMISSION_GRANTED) { 19267 Slog.w(TAG, "Calling uid " + callingUid + " does not have " + 19268 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES + 19269 ", silently ignoring"); 19270 return; 19271 } 19272 mContext.enforceCallingOrSelfPermission( 19273 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null); 19274 } 19275 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19276 /* requireFullPermission= */ true, /* checkShell= */ false, 19277 "delete application cache files"); 19278 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 19279 android.Manifest.permission.ACCESS_INSTANT_APPS); 19280 19281 final PackageParser.Package pkg; 19282 synchronized (mPackages) { 19283 pkg = mPackages.get(packageName); 19284 } 19285 19286 // Queue up an async operation since the package deletion may take a little while. 19287 mHandler.post(new Runnable() { 19288 public void run() { 19289 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 19290 boolean doClearData = true; 19291 if (ps != null) { 19292 final boolean targetIsInstantApp = 19293 ps.getInstantApp(UserHandle.getUserId(callingUid)); 19294 doClearData = !targetIsInstantApp 19295 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 19296 } 19297 if (doClearData) { 19298 synchronized (mInstallLock) { 19299 final int flags = StorageManager.FLAG_STORAGE_DE 19300 | StorageManager.FLAG_STORAGE_CE; 19301 // We're only clearing cache files, so we don't care if the 19302 // app is unfrozen and still able to run 19303 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 19304 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19305 } 19306 clearExternalStorageDataSync(packageName, userId, false); 19307 } 19308 if (observer != null) { 19309 try { 19310 observer.onRemoveCompleted(packageName, true); 19311 } catch (RemoteException e) { 19312 Log.i(TAG, "Observer no longer exists."); 19313 } 19314 } 19315 } 19316 }); 19317 } 19318 19319 @Override 19320 public void getPackageSizeInfo(final String packageName, int userHandle, 19321 final IPackageStatsObserver observer) { 19322 throw new UnsupportedOperationException( 19323 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 19324 } 19325 19326 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 19327 final PackageSetting ps; 19328 synchronized (mPackages) { 19329 ps = mSettings.mPackages.get(packageName); 19330 if (ps == null) { 19331 Slog.w(TAG, "Failed to find settings for " + packageName); 19332 return false; 19333 } 19334 } 19335 19336 final String[] packageNames = { packageName }; 19337 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 19338 final String[] codePaths = { ps.codePathString }; 19339 19340 try { 19341 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 19342 ps.appId, ceDataInodes, codePaths, stats); 19343 19344 // For now, ignore code size of packages on system partition 19345 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 19346 stats.codeSize = 0; 19347 } 19348 19349 // External clients expect these to be tracked separately 19350 stats.dataSize -= stats.cacheSize; 19351 19352 } catch (InstallerException e) { 19353 Slog.w(TAG, String.valueOf(e)); 19354 return false; 19355 } 19356 19357 return true; 19358 } 19359 19360 private int getUidTargetSdkVersionLockedLPr(int uid) { 19361 Object obj = mSettings.getUserIdLPr(uid); 19362 if (obj instanceof SharedUserSetting) { 19363 final SharedUserSetting sus = (SharedUserSetting) obj; 19364 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 19365 final Iterator<PackageSetting> it = sus.packages.iterator(); 19366 while (it.hasNext()) { 19367 final PackageSetting ps = it.next(); 19368 if (ps.pkg != null) { 19369 int v = ps.pkg.applicationInfo.targetSdkVersion; 19370 if (v < vers) vers = v; 19371 } 19372 } 19373 return vers; 19374 } else if (obj instanceof PackageSetting) { 19375 final PackageSetting ps = (PackageSetting) obj; 19376 if (ps.pkg != null) { 19377 return ps.pkg.applicationInfo.targetSdkVersion; 19378 } 19379 } 19380 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19381 } 19382 19383 private int getPackageTargetSdkVersionLockedLPr(String packageName) { 19384 final PackageParser.Package p = mPackages.get(packageName); 19385 if (p != null) { 19386 return p.applicationInfo.targetSdkVersion; 19387 } 19388 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19389 } 19390 19391 @Override 19392 public void addPreferredActivity(IntentFilter filter, int match, 19393 ComponentName[] set, ComponentName activity, int userId) { 19394 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19395 "Adding preferred"); 19396 } 19397 19398 private void addPreferredActivityInternal(IntentFilter filter, int match, 19399 ComponentName[] set, ComponentName activity, boolean always, int userId, 19400 String opname) { 19401 // writer 19402 int callingUid = Binder.getCallingUid(); 19403 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19404 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 19405 if (filter.countActions() == 0) { 19406 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19407 return; 19408 } 19409 synchronized (mPackages) { 19410 if (mContext.checkCallingOrSelfPermission( 19411 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19412 != PackageManager.PERMISSION_GRANTED) { 19413 if (getUidTargetSdkVersionLockedLPr(callingUid) 19414 < Build.VERSION_CODES.FROYO) { 19415 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 19416 + callingUid); 19417 return; 19418 } 19419 mContext.enforceCallingOrSelfPermission( 19420 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19421 } 19422 19423 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 19424 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 19425 + userId + ":"); 19426 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19427 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 19428 scheduleWritePackageRestrictionsLocked(userId); 19429 postPreferredActivityChangedBroadcast(userId); 19430 } 19431 } 19432 19433 private void postPreferredActivityChangedBroadcast(int userId) { 19434 mHandler.post(() -> { 19435 final IActivityManager am = ActivityManager.getService(); 19436 if (am == null) { 19437 return; 19438 } 19439 19440 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 19441 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 19442 try { 19443 am.broadcastIntent(null, intent, null, null, 19444 0, null, null, null, android.app.AppOpsManager.OP_NONE, 19445 null, false, false, userId); 19446 } catch (RemoteException e) { 19447 } 19448 }); 19449 } 19450 19451 @Override 19452 public void replacePreferredActivity(IntentFilter filter, int match, 19453 ComponentName[] set, ComponentName activity, int userId) { 19454 if (filter.countActions() != 1) { 19455 throw new IllegalArgumentException( 19456 "replacePreferredActivity expects filter to have only 1 action."); 19457 } 19458 if (filter.countDataAuthorities() != 0 19459 || filter.countDataPaths() != 0 19460 || filter.countDataSchemes() > 1 19461 || filter.countDataTypes() != 0) { 19462 throw new IllegalArgumentException( 19463 "replacePreferredActivity expects filter to have no data authorities, " + 19464 "paths, or types; and at most one scheme."); 19465 } 19466 19467 final int callingUid = Binder.getCallingUid(); 19468 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19469 true /* requireFullPermission */, false /* checkShell */, 19470 "replace preferred activity"); 19471 synchronized (mPackages) { 19472 if (mContext.checkCallingOrSelfPermission( 19473 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19474 != PackageManager.PERMISSION_GRANTED) { 19475 if (getUidTargetSdkVersionLockedLPr(callingUid) 19476 < Build.VERSION_CODES.FROYO) { 19477 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 19478 + Binder.getCallingUid()); 19479 return; 19480 } 19481 mContext.enforceCallingOrSelfPermission( 19482 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19483 } 19484 19485 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19486 if (pir != null) { 19487 // Get all of the existing entries that exactly match this filter. 19488 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 19489 if (existing != null && existing.size() == 1) { 19490 PreferredActivity cur = existing.get(0); 19491 if (DEBUG_PREFERRED) { 19492 Slog.i(TAG, "Checking replace of preferred:"); 19493 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19494 if (!cur.mPref.mAlways) { 19495 Slog.i(TAG, " -- CUR; not mAlways!"); 19496 } else { 19497 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19498 Slog.i(TAG, " -- CUR: mSet=" 19499 + Arrays.toString(cur.mPref.mSetComponents)); 19500 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19501 Slog.i(TAG, " -- NEW: mMatch=" 19502 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19503 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19504 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19505 } 19506 } 19507 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19508 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19509 && cur.mPref.sameSet(set)) { 19510 // Setting the preferred activity to what it happens to be already 19511 if (DEBUG_PREFERRED) { 19512 Slog.i(TAG, "Replacing with same preferred activity " 19513 + cur.mPref.mShortComponent + " for user " 19514 + userId + ":"); 19515 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19516 } 19517 return; 19518 } 19519 } 19520 19521 if (existing != null) { 19522 if (DEBUG_PREFERRED) { 19523 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19524 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19525 } 19526 for (int i = 0; i < existing.size(); i++) { 19527 PreferredActivity pa = existing.get(i); 19528 if (DEBUG_PREFERRED) { 19529 Slog.i(TAG, "Removing existing preferred activity " 19530 + pa.mPref.mComponent + ":"); 19531 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19532 } 19533 pir.removeFilter(pa); 19534 } 19535 } 19536 } 19537 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19538 "Replacing preferred"); 19539 } 19540 } 19541 19542 @Override 19543 public void clearPackagePreferredActivities(String packageName) { 19544 final int callingUid = Binder.getCallingUid(); 19545 if (getInstantAppPackageName(callingUid) != null) { 19546 return; 19547 } 19548 // writer 19549 synchronized (mPackages) { 19550 PackageParser.Package pkg = mPackages.get(packageName); 19551 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 19552 if (mContext.checkCallingOrSelfPermission( 19553 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19554 != PackageManager.PERMISSION_GRANTED) { 19555 if (getUidTargetSdkVersionLockedLPr(callingUid) 19556 < Build.VERSION_CODES.FROYO) { 19557 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19558 + callingUid); 19559 return; 19560 } 19561 mContext.enforceCallingOrSelfPermission( 19562 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19563 } 19564 } 19565 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19566 if (ps != null 19567 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 19568 return; 19569 } 19570 int user = UserHandle.getCallingUserId(); 19571 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19572 scheduleWritePackageRestrictionsLocked(user); 19573 } 19574 } 19575 } 19576 19577 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19578 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19579 ArrayList<PreferredActivity> removed = null; 19580 boolean changed = false; 19581 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19582 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19583 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19584 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19585 continue; 19586 } 19587 Iterator<PreferredActivity> it = pir.filterIterator(); 19588 while (it.hasNext()) { 19589 PreferredActivity pa = it.next(); 19590 // Mark entry for removal only if it matches the package name 19591 // and the entry is of type "always". 19592 if (packageName == null || 19593 (pa.mPref.mComponent.getPackageName().equals(packageName) 19594 && pa.mPref.mAlways)) { 19595 if (removed == null) { 19596 removed = new ArrayList<PreferredActivity>(); 19597 } 19598 removed.add(pa); 19599 } 19600 } 19601 if (removed != null) { 19602 for (int j=0; j<removed.size(); j++) { 19603 PreferredActivity pa = removed.get(j); 19604 pir.removeFilter(pa); 19605 } 19606 changed = true; 19607 } 19608 } 19609 if (changed) { 19610 postPreferredActivityChangedBroadcast(userId); 19611 } 19612 return changed; 19613 } 19614 19615 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19616 private void clearIntentFilterVerificationsLPw(int userId) { 19617 final int packageCount = mPackages.size(); 19618 for (int i = 0; i < packageCount; i++) { 19619 PackageParser.Package pkg = mPackages.valueAt(i); 19620 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19621 } 19622 } 19623 19624 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19625 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19626 if (userId == UserHandle.USER_ALL) { 19627 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19628 sUserManager.getUserIds())) { 19629 for (int oneUserId : sUserManager.getUserIds()) { 19630 scheduleWritePackageRestrictionsLocked(oneUserId); 19631 } 19632 } 19633 } else { 19634 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19635 scheduleWritePackageRestrictionsLocked(userId); 19636 } 19637 } 19638 } 19639 19640 /** Clears state for all users, and touches intent filter verification policy */ 19641 void clearDefaultBrowserIfNeeded(String packageName) { 19642 for (int oneUserId : sUserManager.getUserIds()) { 19643 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19644 } 19645 } 19646 19647 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19648 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19649 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19650 if (packageName.equals(defaultBrowserPackageName)) { 19651 setDefaultBrowserPackageName(null, userId); 19652 } 19653 } 19654 } 19655 19656 @Override 19657 public void resetApplicationPreferences(int userId) { 19658 mContext.enforceCallingOrSelfPermission( 19659 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19660 final long identity = Binder.clearCallingIdentity(); 19661 // writer 19662 try { 19663 synchronized (mPackages) { 19664 clearPackagePreferredActivitiesLPw(null, userId); 19665 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19666 // TODO: We have to reset the default SMS and Phone. This requires 19667 // significant refactoring to keep all default apps in the package 19668 // manager (cleaner but more work) or have the services provide 19669 // callbacks to the package manager to request a default app reset. 19670 applyFactoryDefaultBrowserLPw(userId); 19671 clearIntentFilterVerificationsLPw(userId); 19672 primeDomainVerificationsLPw(userId); 19673 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19674 scheduleWritePackageRestrictionsLocked(userId); 19675 } 19676 resetNetworkPolicies(userId); 19677 } finally { 19678 Binder.restoreCallingIdentity(identity); 19679 } 19680 } 19681 19682 @Override 19683 public int getPreferredActivities(List<IntentFilter> outFilters, 19684 List<ComponentName> outActivities, String packageName) { 19685 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19686 return 0; 19687 } 19688 int num = 0; 19689 final int userId = UserHandle.getCallingUserId(); 19690 // reader 19691 synchronized (mPackages) { 19692 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19693 if (pir != null) { 19694 final Iterator<PreferredActivity> it = pir.filterIterator(); 19695 while (it.hasNext()) { 19696 final PreferredActivity pa = it.next(); 19697 if (packageName == null 19698 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19699 && pa.mPref.mAlways)) { 19700 if (outFilters != null) { 19701 outFilters.add(new IntentFilter(pa)); 19702 } 19703 if (outActivities != null) { 19704 outActivities.add(pa.mPref.mComponent); 19705 } 19706 } 19707 } 19708 } 19709 } 19710 19711 return num; 19712 } 19713 19714 @Override 19715 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19716 int userId) { 19717 int callingUid = Binder.getCallingUid(); 19718 if (callingUid != Process.SYSTEM_UID) { 19719 throw new SecurityException( 19720 "addPersistentPreferredActivity can only be run by the system"); 19721 } 19722 if (filter.countActions() == 0) { 19723 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19724 return; 19725 } 19726 synchronized (mPackages) { 19727 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19728 ":"); 19729 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19730 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19731 new PersistentPreferredActivity(filter, activity)); 19732 scheduleWritePackageRestrictionsLocked(userId); 19733 postPreferredActivityChangedBroadcast(userId); 19734 } 19735 } 19736 19737 @Override 19738 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19739 int callingUid = Binder.getCallingUid(); 19740 if (callingUid != Process.SYSTEM_UID) { 19741 throw new SecurityException( 19742 "clearPackagePersistentPreferredActivities can only be run by the system"); 19743 } 19744 ArrayList<PersistentPreferredActivity> removed = null; 19745 boolean changed = false; 19746 synchronized (mPackages) { 19747 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19748 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19749 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19750 .valueAt(i); 19751 if (userId != thisUserId) { 19752 continue; 19753 } 19754 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19755 while (it.hasNext()) { 19756 PersistentPreferredActivity ppa = it.next(); 19757 // Mark entry for removal only if it matches the package name. 19758 if (ppa.mComponent.getPackageName().equals(packageName)) { 19759 if (removed == null) { 19760 removed = new ArrayList<PersistentPreferredActivity>(); 19761 } 19762 removed.add(ppa); 19763 } 19764 } 19765 if (removed != null) { 19766 for (int j=0; j<removed.size(); j++) { 19767 PersistentPreferredActivity ppa = removed.get(j); 19768 ppir.removeFilter(ppa); 19769 } 19770 changed = true; 19771 } 19772 } 19773 19774 if (changed) { 19775 scheduleWritePackageRestrictionsLocked(userId); 19776 postPreferredActivityChangedBroadcast(userId); 19777 } 19778 } 19779 } 19780 19781 /** 19782 * Common machinery for picking apart a restored XML blob and passing 19783 * it to a caller-supplied functor to be applied to the running system. 19784 */ 19785 private void restoreFromXml(XmlPullParser parser, int userId, 19786 String expectedStartTag, BlobXmlRestorer functor) 19787 throws IOException, XmlPullParserException { 19788 int type; 19789 while ((type = parser.next()) != XmlPullParser.START_TAG 19790 && type != XmlPullParser.END_DOCUMENT) { 19791 } 19792 if (type != XmlPullParser.START_TAG) { 19793 // oops didn't find a start tag?! 19794 if (DEBUG_BACKUP) { 19795 Slog.e(TAG, "Didn't find start tag during restore"); 19796 } 19797 return; 19798 } 19799Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19800 // this is supposed to be TAG_PREFERRED_BACKUP 19801 if (!expectedStartTag.equals(parser.getName())) { 19802 if (DEBUG_BACKUP) { 19803 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19804 } 19805 return; 19806 } 19807 19808 // skip interfering stuff, then we're aligned with the backing implementation 19809 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19810Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19811 functor.apply(parser, userId); 19812 } 19813 19814 private interface BlobXmlRestorer { 19815 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19816 } 19817 19818 /** 19819 * Non-Binder method, support for the backup/restore mechanism: write the 19820 * full set of preferred activities in its canonical XML format. Returns the 19821 * XML output as a byte array, or null if there is none. 19822 */ 19823 @Override 19824 public byte[] getPreferredActivityBackup(int userId) { 19825 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19826 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19827 } 19828 19829 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19830 try { 19831 final XmlSerializer serializer = new FastXmlSerializer(); 19832 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19833 serializer.startDocument(null, true); 19834 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19835 19836 synchronized (mPackages) { 19837 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19838 } 19839 19840 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19841 serializer.endDocument(); 19842 serializer.flush(); 19843 } catch (Exception e) { 19844 if (DEBUG_BACKUP) { 19845 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19846 } 19847 return null; 19848 } 19849 19850 return dataStream.toByteArray(); 19851 } 19852 19853 @Override 19854 public void restorePreferredActivities(byte[] backup, int userId) { 19855 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19856 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19857 } 19858 19859 try { 19860 final XmlPullParser parser = Xml.newPullParser(); 19861 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19862 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19863 new BlobXmlRestorer() { 19864 @Override 19865 public void apply(XmlPullParser parser, int userId) 19866 throws XmlPullParserException, IOException { 19867 synchronized (mPackages) { 19868 mSettings.readPreferredActivitiesLPw(parser, userId); 19869 } 19870 } 19871 } ); 19872 } catch (Exception e) { 19873 if (DEBUG_BACKUP) { 19874 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19875 } 19876 } 19877 } 19878 19879 /** 19880 * Non-Binder method, support for the backup/restore mechanism: write the 19881 * default browser (etc) settings in its canonical XML format. Returns the default 19882 * browser XML representation as a byte array, or null if there is none. 19883 */ 19884 @Override 19885 public byte[] getDefaultAppsBackup(int userId) { 19886 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19887 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19888 } 19889 19890 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19891 try { 19892 final XmlSerializer serializer = new FastXmlSerializer(); 19893 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19894 serializer.startDocument(null, true); 19895 serializer.startTag(null, TAG_DEFAULT_APPS); 19896 19897 synchronized (mPackages) { 19898 mSettings.writeDefaultAppsLPr(serializer, userId); 19899 } 19900 19901 serializer.endTag(null, TAG_DEFAULT_APPS); 19902 serializer.endDocument(); 19903 serializer.flush(); 19904 } catch (Exception e) { 19905 if (DEBUG_BACKUP) { 19906 Slog.e(TAG, "Unable to write default apps for backup", e); 19907 } 19908 return null; 19909 } 19910 19911 return dataStream.toByteArray(); 19912 } 19913 19914 @Override 19915 public void restoreDefaultApps(byte[] backup, int userId) { 19916 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19917 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19918 } 19919 19920 try { 19921 final XmlPullParser parser = Xml.newPullParser(); 19922 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19923 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19924 new BlobXmlRestorer() { 19925 @Override 19926 public void apply(XmlPullParser parser, int userId) 19927 throws XmlPullParserException, IOException { 19928 synchronized (mPackages) { 19929 mSettings.readDefaultAppsLPw(parser, userId); 19930 } 19931 } 19932 } ); 19933 } catch (Exception e) { 19934 if (DEBUG_BACKUP) { 19935 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19936 } 19937 } 19938 } 19939 19940 @Override 19941 public byte[] getIntentFilterVerificationBackup(int userId) { 19942 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19943 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19944 } 19945 19946 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19947 try { 19948 final XmlSerializer serializer = new FastXmlSerializer(); 19949 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19950 serializer.startDocument(null, true); 19951 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19952 19953 synchronized (mPackages) { 19954 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19955 } 19956 19957 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19958 serializer.endDocument(); 19959 serializer.flush(); 19960 } catch (Exception e) { 19961 if (DEBUG_BACKUP) { 19962 Slog.e(TAG, "Unable to write default apps for backup", e); 19963 } 19964 return null; 19965 } 19966 19967 return dataStream.toByteArray(); 19968 } 19969 19970 @Override 19971 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19972 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19973 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19974 } 19975 19976 try { 19977 final XmlPullParser parser = Xml.newPullParser(); 19978 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19979 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19980 new BlobXmlRestorer() { 19981 @Override 19982 public void apply(XmlPullParser parser, int userId) 19983 throws XmlPullParserException, IOException { 19984 synchronized (mPackages) { 19985 mSettings.readAllDomainVerificationsLPr(parser, userId); 19986 mSettings.writeLPr(); 19987 } 19988 } 19989 } ); 19990 } catch (Exception e) { 19991 if (DEBUG_BACKUP) { 19992 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19993 } 19994 } 19995 } 19996 19997 @Override 19998 public byte[] getPermissionGrantBackup(int userId) { 19999 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20000 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 20001 } 20002 20003 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20004 try { 20005 final XmlSerializer serializer = new FastXmlSerializer(); 20006 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20007 serializer.startDocument(null, true); 20008 serializer.startTag(null, TAG_PERMISSION_BACKUP); 20009 20010 synchronized (mPackages) { 20011 serializeRuntimePermissionGrantsLPr(serializer, userId); 20012 } 20013 20014 serializer.endTag(null, TAG_PERMISSION_BACKUP); 20015 serializer.endDocument(); 20016 serializer.flush(); 20017 } catch (Exception e) { 20018 if (DEBUG_BACKUP) { 20019 Slog.e(TAG, "Unable to write default apps for backup", e); 20020 } 20021 return null; 20022 } 20023 20024 return dataStream.toByteArray(); 20025 } 20026 20027 @Override 20028 public void restorePermissionGrants(byte[] backup, int userId) { 20029 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20030 throw new SecurityException("Only the system may call restorePermissionGrants()"); 20031 } 20032 20033 try { 20034 final XmlPullParser parser = Xml.newPullParser(); 20035 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20036 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 20037 new BlobXmlRestorer() { 20038 @Override 20039 public void apply(XmlPullParser parser, int userId) 20040 throws XmlPullParserException, IOException { 20041 synchronized (mPackages) { 20042 processRestoredPermissionGrantsLPr(parser, userId); 20043 } 20044 } 20045 } ); 20046 } catch (Exception e) { 20047 if (DEBUG_BACKUP) { 20048 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 20049 } 20050 } 20051 } 20052 20053 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 20054 throws IOException { 20055 serializer.startTag(null, TAG_ALL_GRANTS); 20056 20057 final int N = mSettings.mPackages.size(); 20058 for (int i = 0; i < N; i++) { 20059 final PackageSetting ps = mSettings.mPackages.valueAt(i); 20060 boolean pkgGrantsKnown = false; 20061 20062 PermissionsState packagePerms = ps.getPermissionsState(); 20063 20064 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 20065 final int grantFlags = state.getFlags(); 20066 // only look at grants that are not system/policy fixed 20067 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 20068 final boolean isGranted = state.isGranted(); 20069 // And only back up the user-twiddled state bits 20070 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 20071 final String packageName = mSettings.mPackages.keyAt(i); 20072 if (!pkgGrantsKnown) { 20073 serializer.startTag(null, TAG_GRANT); 20074 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 20075 pkgGrantsKnown = true; 20076 } 20077 20078 final boolean userSet = 20079 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 20080 final boolean userFixed = 20081 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 20082 final boolean revoke = 20083 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 20084 20085 serializer.startTag(null, TAG_PERMISSION); 20086 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 20087 if (isGranted) { 20088 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 20089 } 20090 if (userSet) { 20091 serializer.attribute(null, ATTR_USER_SET, "true"); 20092 } 20093 if (userFixed) { 20094 serializer.attribute(null, ATTR_USER_FIXED, "true"); 20095 } 20096 if (revoke) { 20097 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 20098 } 20099 serializer.endTag(null, TAG_PERMISSION); 20100 } 20101 } 20102 } 20103 20104 if (pkgGrantsKnown) { 20105 serializer.endTag(null, TAG_GRANT); 20106 } 20107 } 20108 20109 serializer.endTag(null, TAG_ALL_GRANTS); 20110 } 20111 20112 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 20113 throws XmlPullParserException, IOException { 20114 String pkgName = null; 20115 int outerDepth = parser.getDepth(); 20116 int type; 20117 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 20118 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 20119 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 20120 continue; 20121 } 20122 20123 final String tagName = parser.getName(); 20124 if (tagName.equals(TAG_GRANT)) { 20125 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 20126 if (DEBUG_BACKUP) { 20127 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 20128 } 20129 } else if (tagName.equals(TAG_PERMISSION)) { 20130 20131 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 20132 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 20133 20134 int newFlagSet = 0; 20135 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 20136 newFlagSet |= FLAG_PERMISSION_USER_SET; 20137 } 20138 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 20139 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 20140 } 20141 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 20142 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 20143 } 20144 if (DEBUG_BACKUP) { 20145 Slog.v(TAG, " + Restoring grant:" 20146 + " pkg=" + pkgName 20147 + " perm=" + permName 20148 + " granted=" + isGranted 20149 + " bits=0x" + Integer.toHexString(newFlagSet)); 20150 } 20151 final PackageSetting ps = mSettings.mPackages.get(pkgName); 20152 if (ps != null) { 20153 // Already installed so we apply the grant immediately 20154 if (DEBUG_BACKUP) { 20155 Slog.v(TAG, " + already installed; applying"); 20156 } 20157 PermissionsState perms = ps.getPermissionsState(); 20158 BasePermission bp = 20159 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 20160 if (bp != null) { 20161 if (isGranted) { 20162 perms.grantRuntimePermission(bp, userId); 20163 } 20164 if (newFlagSet != 0) { 20165 perms.updatePermissionFlags( 20166 bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 20167 } 20168 } 20169 } else { 20170 // Need to wait for post-restore install to apply the grant 20171 if (DEBUG_BACKUP) { 20172 Slog.v(TAG, " - not yet installed; saving for later"); 20173 } 20174 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 20175 isGranted, newFlagSet, userId); 20176 } 20177 } else { 20178 PackageManagerService.reportSettingsProblem(Log.WARN, 20179 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 20180 XmlUtils.skipCurrentTag(parser); 20181 } 20182 } 20183 20184 scheduleWriteSettingsLocked(); 20185 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 20186 } 20187 20188 @Override 20189 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 20190 int sourceUserId, int targetUserId, int flags) { 20191 mContext.enforceCallingOrSelfPermission( 20192 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20193 int callingUid = Binder.getCallingUid(); 20194 enforceOwnerRights(ownerPackage, callingUid); 20195 PackageManagerServiceUtils.enforceShellRestriction( 20196 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20197 if (intentFilter.countActions() == 0) { 20198 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 20199 return; 20200 } 20201 synchronized (mPackages) { 20202 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 20203 ownerPackage, targetUserId, flags); 20204 CrossProfileIntentResolver resolver = 20205 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20206 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 20207 // We have all those whose filter is equal. Now checking if the rest is equal as well. 20208 if (existing != null) { 20209 int size = existing.size(); 20210 for (int i = 0; i < size; i++) { 20211 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 20212 return; 20213 } 20214 } 20215 } 20216 resolver.addFilter(newFilter); 20217 scheduleWritePackageRestrictionsLocked(sourceUserId); 20218 } 20219 } 20220 20221 @Override 20222 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 20223 mContext.enforceCallingOrSelfPermission( 20224 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20225 final int callingUid = Binder.getCallingUid(); 20226 enforceOwnerRights(ownerPackage, callingUid); 20227 PackageManagerServiceUtils.enforceShellRestriction( 20228 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20229 synchronized (mPackages) { 20230 CrossProfileIntentResolver resolver = 20231 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20232 ArraySet<CrossProfileIntentFilter> set = 20233 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 20234 for (CrossProfileIntentFilter filter : set) { 20235 if (filter.getOwnerPackage().equals(ownerPackage)) { 20236 resolver.removeFilter(filter); 20237 } 20238 } 20239 scheduleWritePackageRestrictionsLocked(sourceUserId); 20240 } 20241 } 20242 20243 // Enforcing that callingUid is owning pkg on userId 20244 private void enforceOwnerRights(String pkg, int callingUid) { 20245 // The system owns everything. 20246 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 20247 return; 20248 } 20249 final int callingUserId = UserHandle.getUserId(callingUid); 20250 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 20251 if (pi == null) { 20252 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 20253 + callingUserId); 20254 } 20255 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 20256 throw new SecurityException("Calling uid " + callingUid 20257 + " does not own package " + pkg); 20258 } 20259 } 20260 20261 @Override 20262 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 20263 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20264 return null; 20265 } 20266 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 20267 } 20268 20269 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 20270 UserManagerService ums = UserManagerService.getInstance(); 20271 if (ums != null) { 20272 final UserInfo parent = ums.getProfileParent(userId); 20273 final int launcherUid = (parent != null) ? parent.id : userId; 20274 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 20275 if (launcherComponent != null) { 20276 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 20277 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 20278 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 20279 .setPackage(launcherComponent.getPackageName()); 20280 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 20281 } 20282 } 20283 } 20284 20285 /** 20286 * Report the 'Home' activity which is currently set as "always use this one". If non is set 20287 * then reports the most likely home activity or null if there are more than one. 20288 */ 20289 private ComponentName getDefaultHomeActivity(int userId) { 20290 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 20291 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 20292 if (cn != null) { 20293 return cn; 20294 } 20295 20296 // Find the launcher with the highest priority and return that component if there are no 20297 // other home activity with the same priority. 20298 int lastPriority = Integer.MIN_VALUE; 20299 ComponentName lastComponent = null; 20300 final int size = allHomeCandidates.size(); 20301 for (int i = 0; i < size; i++) { 20302 final ResolveInfo ri = allHomeCandidates.get(i); 20303 if (ri.priority > lastPriority) { 20304 lastComponent = ri.activityInfo.getComponentName(); 20305 lastPriority = ri.priority; 20306 } else if (ri.priority == lastPriority) { 20307 // Two components found with same priority. 20308 lastComponent = null; 20309 } 20310 } 20311 return lastComponent; 20312 } 20313 20314 private Intent getHomeIntent() { 20315 Intent intent = new Intent(Intent.ACTION_MAIN); 20316 intent.addCategory(Intent.CATEGORY_HOME); 20317 intent.addCategory(Intent.CATEGORY_DEFAULT); 20318 return intent; 20319 } 20320 20321 private IntentFilter getHomeFilter() { 20322 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 20323 filter.addCategory(Intent.CATEGORY_HOME); 20324 filter.addCategory(Intent.CATEGORY_DEFAULT); 20325 return filter; 20326 } 20327 20328 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20329 int userId) { 20330 Intent intent = getHomeIntent(); 20331 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 20332 PackageManager.GET_META_DATA, userId); 20333 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 20334 true, false, false, userId); 20335 20336 allHomeCandidates.clear(); 20337 if (list != null) { 20338 for (ResolveInfo ri : list) { 20339 allHomeCandidates.add(ri); 20340 } 20341 } 20342 return (preferred == null || preferred.activityInfo == null) 20343 ? null 20344 : new ComponentName(preferred.activityInfo.packageName, 20345 preferred.activityInfo.name); 20346 } 20347 20348 @Override 20349 public void setHomeActivity(ComponentName comp, int userId) { 20350 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20351 return; 20352 } 20353 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 20354 getHomeActivitiesAsUser(homeActivities, userId); 20355 20356 boolean found = false; 20357 20358 final int size = homeActivities.size(); 20359 final ComponentName[] set = new ComponentName[size]; 20360 for (int i = 0; i < size; i++) { 20361 final ResolveInfo candidate = homeActivities.get(i); 20362 final ActivityInfo info = candidate.activityInfo; 20363 final ComponentName activityName = new ComponentName(info.packageName, info.name); 20364 set[i] = activityName; 20365 if (!found && activityName.equals(comp)) { 20366 found = true; 20367 } 20368 } 20369 if (!found) { 20370 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 20371 + userId); 20372 } 20373 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 20374 set, comp, userId); 20375 } 20376 20377 private @Nullable String getSetupWizardPackageName() { 20378 final Intent intent = new Intent(Intent.ACTION_MAIN); 20379 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 20380 20381 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20382 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20383 | MATCH_DISABLED_COMPONENTS, 20384 UserHandle.myUserId()); 20385 if (matches.size() == 1) { 20386 return matches.get(0).getComponentInfo().packageName; 20387 } else { 20388 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 20389 + ": matches=" + matches); 20390 return null; 20391 } 20392 } 20393 20394 private @Nullable String getStorageManagerPackageName() { 20395 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 20396 20397 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20398 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20399 | MATCH_DISABLED_COMPONENTS, 20400 UserHandle.myUserId()); 20401 if (matches.size() == 1) { 20402 return matches.get(0).getComponentInfo().packageName; 20403 } else { 20404 Slog.e(TAG, "There should probably be exactly one storage manager; found " 20405 + matches.size() + ": matches=" + matches); 20406 return null; 20407 } 20408 } 20409 20410 @Override 20411 public String getSystemTextClassifierPackageName() { 20412 return mContext.getString(R.string.config_defaultTextClassifierPackage); 20413 } 20414 20415 @Override 20416 public void setApplicationEnabledSetting(String appPackageName, 20417 int newState, int flags, int userId, String callingPackage) { 20418 if (!sUserManager.exists(userId)) return; 20419 if (callingPackage == null) { 20420 callingPackage = Integer.toString(Binder.getCallingUid()); 20421 } 20422 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 20423 } 20424 20425 @Override 20426 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 20427 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 20428 synchronized (mPackages) { 20429 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 20430 if (pkgSetting != null) { 20431 pkgSetting.setUpdateAvailable(updateAvailable); 20432 } 20433 } 20434 } 20435 20436 @Override 20437 public void setComponentEnabledSetting(ComponentName componentName, 20438 int newState, int flags, int userId) { 20439 if (!sUserManager.exists(userId)) return; 20440 setEnabledSetting(componentName.getPackageName(), 20441 componentName.getClassName(), newState, flags, userId, null); 20442 } 20443 20444 private void setEnabledSetting(final String packageName, String className, int newState, 20445 final int flags, int userId, String callingPackage) { 20446 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 20447 || newState == COMPONENT_ENABLED_STATE_ENABLED 20448 || newState == COMPONENT_ENABLED_STATE_DISABLED 20449 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20450 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 20451 throw new IllegalArgumentException("Invalid new component state: " 20452 + newState); 20453 } 20454 PackageSetting pkgSetting; 20455 final int callingUid = Binder.getCallingUid(); 20456 final int permission; 20457 if (callingUid == Process.SYSTEM_UID) { 20458 permission = PackageManager.PERMISSION_GRANTED; 20459 } else { 20460 permission = mContext.checkCallingOrSelfPermission( 20461 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20462 } 20463 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20464 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 20465 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20466 boolean sendNow = false; 20467 boolean isApp = (className == null); 20468 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 20469 String componentName = isApp ? packageName : className; 20470 int packageUid = -1; 20471 ArrayList<String> components; 20472 20473 // reader 20474 synchronized (mPackages) { 20475 pkgSetting = mSettings.mPackages.get(packageName); 20476 if (pkgSetting == null) { 20477 if (!isCallerInstantApp) { 20478 if (className == null) { 20479 throw new IllegalArgumentException("Unknown package: " + packageName); 20480 } 20481 throw new IllegalArgumentException( 20482 "Unknown component: " + packageName + "/" + className); 20483 } else { 20484 // throw SecurityException to prevent leaking package information 20485 throw new SecurityException( 20486 "Attempt to change component state; " 20487 + "pid=" + Binder.getCallingPid() 20488 + ", uid=" + callingUid 20489 + (className == null 20490 ? ", package=" + packageName 20491 : ", component=" + packageName + "/" + className)); 20492 } 20493 } 20494 } 20495 20496 // Limit who can change which apps 20497 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 20498 // Don't allow apps that don't have permission to modify other apps 20499 if (!allowedByPermission 20500 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 20501 throw new SecurityException( 20502 "Attempt to change component state; " 20503 + "pid=" + Binder.getCallingPid() 20504 + ", uid=" + callingUid 20505 + (className == null 20506 ? ", package=" + packageName 20507 : ", component=" + packageName + "/" + className)); 20508 } 20509 // Don't allow changing protected packages. 20510 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 20511 throw new SecurityException("Cannot disable a protected package: " + packageName); 20512 } 20513 } 20514 20515 synchronized (mPackages) { 20516 if (callingUid == Process.SHELL_UID 20517 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 20518 // Shell can only change whole packages between ENABLED and DISABLED_USER states 20519 // unless it is a test package. 20520 int oldState = pkgSetting.getEnabled(userId); 20521 if (className == null 20522 && 20523 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 20524 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 20525 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 20526 && 20527 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20528 || newState == COMPONENT_ENABLED_STATE_DEFAULT 20529 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 20530 // ok 20531 } else { 20532 throw new SecurityException( 20533 "Shell cannot change component state for " + packageName + "/" 20534 + className + " to " + newState); 20535 } 20536 } 20537 } 20538 if (className == null) { 20539 // We're dealing with an application/package level state change 20540 synchronized (mPackages) { 20541 if (pkgSetting.getEnabled(userId) == newState) { 20542 // Nothing to do 20543 return; 20544 } 20545 } 20546 // If we're enabling a system stub, there's a little more work to do. 20547 // Prior to enabling the package, we need to decompress the APK(s) to the 20548 // data partition and then replace the version on the system partition. 20549 final PackageParser.Package deletedPkg = pkgSetting.pkg; 20550 final boolean isSystemStub = deletedPkg.isStub 20551 && deletedPkg.isSystem(); 20552 if (isSystemStub 20553 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20554 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 20555 final File codePath = decompressPackage(deletedPkg); 20556 if (codePath == null) { 20557 Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name); 20558 return; 20559 } 20560 // TODO remove direct parsing of the package object during internal cleanup 20561 // of scan package 20562 // We need to call parse directly here for no other reason than we need 20563 // the new package in order to disable the old one [we use the information 20564 // for some internal optimization to optionally create a new package setting 20565 // object on replace]. However, we can't get the package from the scan 20566 // because the scan modifies live structures and we need to remove the 20567 // old [system] package from the system before a scan can be attempted. 20568 // Once scan is indempotent we can remove this parse and use the package 20569 // object we scanned, prior to adding it to package settings. 20570 final PackageParser pp = new PackageParser(); 20571 pp.setSeparateProcesses(mSeparateProcesses); 20572 pp.setDisplayMetrics(mMetrics); 20573 pp.setCallback(mPackageParserCallback); 20574 final PackageParser.Package tmpPkg; 20575 try { 20576 final @ParseFlags int parseFlags = mDefParseFlags 20577 | PackageParser.PARSE_MUST_BE_APK 20578 | PackageParser.PARSE_IS_SYSTEM_DIR; 20579 tmpPkg = pp.parsePackage(codePath, parseFlags); 20580 } catch (PackageParserException e) { 20581 Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e); 20582 return; 20583 } 20584 synchronized (mInstallLock) { 20585 // Disable the stub and remove any package entries 20586 removePackageLI(deletedPkg, true); 20587 synchronized (mPackages) { 20588 disableSystemPackageLPw(deletedPkg, tmpPkg); 20589 } 20590 final PackageParser.Package pkg; 20591 try (PackageFreezer freezer = 20592 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20593 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 20594 | PackageParser.PARSE_ENFORCE_CODE; 20595 pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 20596 0 /*currentTime*/, null /*user*/); 20597 prepareAppDataAfterInstallLIF(pkg); 20598 synchronized (mPackages) { 20599 try { 20600 updateSharedLibrariesLPr(pkg, null); 20601 } catch (PackageManagerException e) { 20602 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 20603 } 20604 mPermissionManager.updatePermissions( 20605 pkg.packageName, pkg, true, mPackages.values(), 20606 mPermissionCallback); 20607 mSettings.writeLPr(); 20608 } 20609 } catch (PackageManagerException e) { 20610 // Whoops! Something went wrong; try to roll back to the stub 20611 Slog.w(TAG, "Failed to install compressed system package:" 20612 + pkgSetting.name, e); 20613 // Remove the failed install 20614 removeCodePathLI(codePath); 20615 20616 // Install the system package 20617 try (PackageFreezer freezer = 20618 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20619 synchronized (mPackages) { 20620 // NOTE: The system package always needs to be enabled; even 20621 // if it's for a compressed stub. If we don't, installing the 20622 // system package fails during scan [scanning checks the disabled 20623 // packages]. We will reverse this later, after we've "installed" 20624 // the stub. 20625 // This leaves us in a fragile state; the stub should never be 20626 // enabled, so, cross your fingers and hope nothing goes wrong 20627 // until we can disable the package later. 20628 enableSystemPackageLPw(deletedPkg); 20629 } 20630 installPackageFromSystemLIF(deletedPkg.codePath, 20631 false /*isPrivileged*/, null /*allUserHandles*/, 20632 null /*origUserHandles*/, null /*origPermissionsState*/, 20633 true /*writeSettings*/); 20634 } catch (PackageManagerException pme) { 20635 Slog.w(TAG, "Failed to restore system package:" 20636 + deletedPkg.packageName, pme); 20637 } finally { 20638 synchronized (mPackages) { 20639 mSettings.disableSystemPackageLPw( 20640 deletedPkg.packageName, true /*replaced*/); 20641 mSettings.writeLPr(); 20642 } 20643 } 20644 return; 20645 } 20646 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE 20647 | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20648 mDexManager.notifyPackageUpdated(pkg.packageName, 20649 pkg.baseCodePath, pkg.splitCodePaths); 20650 } 20651 } 20652 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20653 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20654 // Don't care about who enables an app. 20655 callingPackage = null; 20656 } 20657 synchronized (mPackages) { 20658 pkgSetting.setEnabled(newState, userId, callingPackage); 20659 } 20660 } else { 20661 synchronized (mPackages) { 20662 // We're dealing with a component level state change 20663 // First, verify that this is a valid class name. 20664 PackageParser.Package pkg = pkgSetting.pkg; 20665 if (pkg == null || !pkg.hasComponentClassName(className)) { 20666 if (pkg != null && 20667 pkg.applicationInfo.targetSdkVersion >= 20668 Build.VERSION_CODES.JELLY_BEAN) { 20669 throw new IllegalArgumentException("Component class " + className 20670 + " does not exist in " + packageName); 20671 } else { 20672 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20673 + className + " does not exist in " + packageName); 20674 } 20675 } 20676 switch (newState) { 20677 case COMPONENT_ENABLED_STATE_ENABLED: 20678 if (!pkgSetting.enableComponentLPw(className, userId)) { 20679 return; 20680 } 20681 break; 20682 case COMPONENT_ENABLED_STATE_DISABLED: 20683 if (!pkgSetting.disableComponentLPw(className, userId)) { 20684 return; 20685 } 20686 break; 20687 case COMPONENT_ENABLED_STATE_DEFAULT: 20688 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20689 return; 20690 } 20691 break; 20692 default: 20693 Slog.e(TAG, "Invalid new component state: " + newState); 20694 return; 20695 } 20696 } 20697 } 20698 synchronized (mPackages) { 20699 scheduleWritePackageRestrictionsLocked(userId); 20700 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 20701 final long callingId = Binder.clearCallingIdentity(); 20702 try { 20703 updateInstantAppInstallerLocked(packageName); 20704 } finally { 20705 Binder.restoreCallingIdentity(callingId); 20706 } 20707 components = mPendingBroadcasts.get(userId, packageName); 20708 final boolean newPackage = components == null; 20709 if (newPackage) { 20710 components = new ArrayList<String>(); 20711 } 20712 if (!components.contains(componentName)) { 20713 components.add(componentName); 20714 } 20715 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20716 sendNow = true; 20717 // Purge entry from pending broadcast list if another one exists already 20718 // since we are sending one right away. 20719 mPendingBroadcasts.remove(userId, packageName); 20720 } else { 20721 if (newPackage) { 20722 mPendingBroadcasts.put(userId, packageName, components); 20723 } 20724 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20725 // Schedule a message 20726 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20727 } 20728 } 20729 } 20730 20731 long callingId = Binder.clearCallingIdentity(); 20732 try { 20733 if (sendNow) { 20734 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20735 sendPackageChangedBroadcast(packageName, 20736 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20737 } 20738 } finally { 20739 Binder.restoreCallingIdentity(callingId); 20740 } 20741 } 20742 20743 @Override 20744 public void flushPackageRestrictionsAsUser(int userId) { 20745 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20746 return; 20747 } 20748 if (!sUserManager.exists(userId)) { 20749 return; 20750 } 20751 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20752 false /* checkShell */, "flushPackageRestrictions"); 20753 synchronized (mPackages) { 20754 mSettings.writePackageRestrictionsLPr(userId); 20755 mDirtyUsers.remove(userId); 20756 if (mDirtyUsers.isEmpty()) { 20757 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20758 } 20759 } 20760 } 20761 20762 private void sendPackageChangedBroadcast(String packageName, 20763 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20764 if (DEBUG_INSTALL) 20765 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20766 + componentNames); 20767 Bundle extras = new Bundle(4); 20768 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20769 String nameList[] = new String[componentNames.size()]; 20770 componentNames.toArray(nameList); 20771 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20772 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20773 extras.putInt(Intent.EXTRA_UID, packageUid); 20774 // If this is not reporting a change of the overall package, then only send it 20775 // to registered receivers. We don't want to launch a swath of apps for every 20776 // little component state change. 20777 final int flags = !componentNames.contains(packageName) 20778 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20779 final int userId = UserHandle.getUserId(packageUid); 20780 final boolean isInstantApp = isInstantApp(packageName, userId); 20781 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 20782 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 20783 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20784 userIds, instantUserIds); 20785 } 20786 20787 @Override 20788 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20789 if (!sUserManager.exists(userId)) return; 20790 final int callingUid = Binder.getCallingUid(); 20791 if (getInstantAppPackageName(callingUid) != null) { 20792 return; 20793 } 20794 final int permission = mContext.checkCallingOrSelfPermission( 20795 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20796 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20797 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20798 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20799 // writer 20800 synchronized (mPackages) { 20801 final PackageSetting ps = mSettings.mPackages.get(packageName); 20802 if (!filterAppAccessLPr(ps, callingUid, userId) 20803 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20804 allowedByPermission, callingUid, userId)) { 20805 scheduleWritePackageRestrictionsLocked(userId); 20806 } 20807 } 20808 } 20809 20810 @Override 20811 public String getInstallerPackageName(String packageName) { 20812 final int callingUid = Binder.getCallingUid(); 20813 synchronized (mPackages) { 20814 final PackageSetting ps = mSettings.mPackages.get(packageName); 20815 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20816 return null; 20817 } 20818 return mSettings.getInstallerPackageNameLPr(packageName); 20819 } 20820 } 20821 20822 public boolean isOrphaned(String packageName) { 20823 // reader 20824 synchronized (mPackages) { 20825 return mSettings.isOrphaned(packageName); 20826 } 20827 } 20828 20829 @Override 20830 public int getApplicationEnabledSetting(String packageName, int userId) { 20831 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20832 int callingUid = Binder.getCallingUid(); 20833 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20834 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20835 // reader 20836 synchronized (mPackages) { 20837 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 20838 return COMPONENT_ENABLED_STATE_DISABLED; 20839 } 20840 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20841 } 20842 } 20843 20844 @Override 20845 public int getComponentEnabledSetting(ComponentName component, int userId) { 20846 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20847 int callingUid = Binder.getCallingUid(); 20848 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20849 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 20850 synchronized (mPackages) { 20851 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 20852 component, TYPE_UNKNOWN, userId)) { 20853 return COMPONENT_ENABLED_STATE_DISABLED; 20854 } 20855 return mSettings.getComponentEnabledSettingLPr(component, userId); 20856 } 20857 } 20858 20859 @Override 20860 public void enterSafeMode() { 20861 enforceSystemOrRoot("Only the system can request entering safe mode"); 20862 20863 if (!mSystemReady) { 20864 mSafeMode = true; 20865 } 20866 } 20867 20868 @Override 20869 public void systemReady() { 20870 enforceSystemOrRoot("Only the system can claim the system is ready"); 20871 20872 mSystemReady = true; 20873 final ContentResolver resolver = mContext.getContentResolver(); 20874 ContentObserver co = new ContentObserver(mHandler) { 20875 @Override 20876 public void onChange(boolean selfChange) { 20877 mWebInstantAppsDisabled = 20878 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20879 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20880 } 20881 }; 20882 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20883 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20884 false, co, UserHandle.USER_SYSTEM); 20885 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure 20886 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20887 co.onChange(true); 20888 20889 // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to 20890 // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once 20891 // it is done. 20892 ContentObserver privAppOobObserver = new ContentObserver(mHandler) { 20893 @Override 20894 public void onChange(boolean selfChange) { 20895 int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0); 20896 SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, 20897 oobEnabled == 1 ? "true" : "false"); 20898 } 20899 }; 20900 mContext.getContentResolver().registerContentObserver( 20901 Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver, 20902 UserHandle.USER_SYSTEM); 20903 // At boot, restore the value from the setting, which persists across reboot. 20904 privAppOobObserver.onChange(true); 20905 20906 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20907 // disabled after already being started. 20908 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20909 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20910 20911 // Read the compatibilty setting when the system is ready. 20912 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20913 mContext.getContentResolver(), 20914 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20915 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20916 if (DEBUG_SETTINGS) { 20917 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20918 } 20919 20920 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20921 20922 synchronized (mPackages) { 20923 // Verify that all of the preferred activity components actually 20924 // exist. It is possible for applications to be updated and at 20925 // that point remove a previously declared activity component that 20926 // had been set as a preferred activity. We try to clean this up 20927 // the next time we encounter that preferred activity, but it is 20928 // possible for the user flow to never be able to return to that 20929 // situation so here we do a sanity check to make sure we haven't 20930 // left any junk around. 20931 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20932 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20933 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20934 removed.clear(); 20935 for (PreferredActivity pa : pir.filterSet()) { 20936 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20937 removed.add(pa); 20938 } 20939 } 20940 if (removed.size() > 0) { 20941 for (int r=0; r<removed.size(); r++) { 20942 PreferredActivity pa = removed.get(r); 20943 Slog.w(TAG, "Removing dangling preferred activity: " 20944 + pa.mPref.mComponent); 20945 pir.removeFilter(pa); 20946 } 20947 mSettings.writePackageRestrictionsLPr( 20948 mSettings.mPreferredActivities.keyAt(i)); 20949 } 20950 } 20951 20952 for (int userId : UserManagerService.getInstance().getUserIds()) { 20953 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20954 grantPermissionsUserIds = ArrayUtils.appendInt( 20955 grantPermissionsUserIds, userId); 20956 } 20957 } 20958 } 20959 sUserManager.systemReady(); 20960 // If we upgraded grant all default permissions before kicking off. 20961 for (int userId : grantPermissionsUserIds) { 20962 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20963 } 20964 20965 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20966 // If we did not grant default permissions, we preload from this the 20967 // default permission exceptions lazily to ensure we don't hit the 20968 // disk on a new user creation. 20969 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20970 } 20971 20972 // Now that we've scanned all packages, and granted any default 20973 // permissions, ensure permissions are updated. Beware of dragons if you 20974 // try optimizing this. 20975 synchronized (mPackages) { 20976 mPermissionManager.updateAllPermissions( 20977 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 20978 mPermissionCallback); 20979 } 20980 20981 // Kick off any messages waiting for system ready 20982 if (mPostSystemReadyMessages != null) { 20983 for (Message msg : mPostSystemReadyMessages) { 20984 msg.sendToTarget(); 20985 } 20986 mPostSystemReadyMessages = null; 20987 } 20988 20989 // Watch for external volumes that come and go over time 20990 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20991 storage.registerListener(mStorageListener); 20992 20993 mInstallerService.systemReady(); 20994 mPackageDexOptimizer.systemReady(); 20995 20996 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20997 StorageManagerInternal.class); 20998 StorageManagerInternal.addExternalStoragePolicy( 20999 new StorageManagerInternal.ExternalStorageMountPolicy() { 21000 @Override 21001 public int getMountMode(int uid, String packageName) { 21002 if (Process.isIsolated(uid)) { 21003 return Zygote.MOUNT_EXTERNAL_NONE; 21004 } 21005 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 21006 return Zygote.MOUNT_EXTERNAL_DEFAULT; 21007 } 21008 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 21009 return Zygote.MOUNT_EXTERNAL_READ; 21010 } 21011 return Zygote.MOUNT_EXTERNAL_WRITE; 21012 } 21013 21014 @Override 21015 public boolean hasExternalStorage(int uid, String packageName) { 21016 return true; 21017 } 21018 }); 21019 21020 // Now that we're mostly running, clean up stale users and apps 21021 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 21022 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 21023 21024 mPermissionManager.systemReady(); 21025 21026 if (mInstantAppResolverConnection != null) { 21027 mContext.registerReceiver(new BroadcastReceiver() { 21028 @Override 21029 public void onReceive(Context context, Intent intent) { 21030 mInstantAppResolverConnection.optimisticBind(); 21031 mContext.unregisterReceiver(this); 21032 } 21033 }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED)); 21034 } 21035 } 21036 21037 public void waitForAppDataPrepared() { 21038 if (mPrepareAppDataFuture == null) { 21039 return; 21040 } 21041 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 21042 mPrepareAppDataFuture = null; 21043 } 21044 21045 @Override 21046 public boolean isSafeMode() { 21047 // allow instant applications 21048 return mSafeMode; 21049 } 21050 21051 @Override 21052 public boolean hasSystemUidErrors() { 21053 // allow instant applications 21054 return mHasSystemUidErrors; 21055 } 21056 21057 static String arrayToString(int[] array) { 21058 StringBuffer buf = new StringBuffer(128); 21059 buf.append('['); 21060 if (array != null) { 21061 for (int i=0; i<array.length; i++) { 21062 if (i > 0) buf.append(", "); 21063 buf.append(array[i]); 21064 } 21065 } 21066 buf.append(']'); 21067 return buf.toString(); 21068 } 21069 21070 @Override 21071 public void onShellCommand(FileDescriptor in, FileDescriptor out, 21072 FileDescriptor err, String[] args, ShellCallback callback, 21073 ResultReceiver resultReceiver) { 21074 (new PackageManagerShellCommand(this)).exec( 21075 this, in, out, err, args, callback, resultReceiver); 21076 } 21077 21078 @Override 21079 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 21080 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 21081 21082 DumpState dumpState = new DumpState(); 21083 boolean fullPreferred = false; 21084 boolean checkin = false; 21085 21086 String packageName = null; 21087 ArraySet<String> permissionNames = null; 21088 21089 int opti = 0; 21090 while (opti < args.length) { 21091 String opt = args[opti]; 21092 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 21093 break; 21094 } 21095 opti++; 21096 21097 if ("-a".equals(opt)) { 21098 // Right now we only know how to print all. 21099 } else if ("-h".equals(opt)) { 21100 pw.println("Package manager dump options:"); 21101 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 21102 pw.println(" --checkin: dump for a checkin"); 21103 pw.println(" -f: print details of intent filters"); 21104 pw.println(" -h: print this help"); 21105 pw.println(" cmd may be one of:"); 21106 pw.println(" l[ibraries]: list known shared libraries"); 21107 pw.println(" f[eatures]: list device features"); 21108 pw.println(" k[eysets]: print known keysets"); 21109 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 21110 pw.println(" perm[issions]: dump permissions"); 21111 pw.println(" permission [name ...]: dump declaration and use of given permission"); 21112 pw.println(" pref[erred]: print preferred package settings"); 21113 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 21114 pw.println(" prov[iders]: dump content providers"); 21115 pw.println(" p[ackages]: dump installed packages"); 21116 pw.println(" s[hared-users]: dump shared user IDs"); 21117 pw.println(" m[essages]: print collected runtime messages"); 21118 pw.println(" v[erifiers]: print package verifier info"); 21119 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 21120 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 21121 pw.println(" version: print database version info"); 21122 pw.println(" write: write current settings now"); 21123 pw.println(" installs: details about install sessions"); 21124 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 21125 pw.println(" dexopt: dump dexopt state"); 21126 pw.println(" compiler-stats: dump compiler statistics"); 21127 pw.println(" service-permissions: dump permissions required by services"); 21128 pw.println(" <package.name>: info about given package"); 21129 return; 21130 } else if ("--checkin".equals(opt)) { 21131 checkin = true; 21132 } else if ("-f".equals(opt)) { 21133 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21134 } else if ("--proto".equals(opt)) { 21135 dumpProto(fd); 21136 return; 21137 } else { 21138 pw.println("Unknown argument: " + opt + "; use -h for help"); 21139 } 21140 } 21141 21142 // Is the caller requesting to dump a particular piece of data? 21143 if (opti < args.length) { 21144 String cmd = args[opti]; 21145 opti++; 21146 // Is this a package name? 21147 if ("android".equals(cmd) || cmd.contains(".")) { 21148 packageName = cmd; 21149 // When dumping a single package, we always dump all of its 21150 // filter information since the amount of data will be reasonable. 21151 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21152 } else if ("check-permission".equals(cmd)) { 21153 if (opti >= args.length) { 21154 pw.println("Error: check-permission missing permission argument"); 21155 return; 21156 } 21157 String perm = args[opti]; 21158 opti++; 21159 if (opti >= args.length) { 21160 pw.println("Error: check-permission missing package argument"); 21161 return; 21162 } 21163 21164 String pkg = args[opti]; 21165 opti++; 21166 int user = UserHandle.getUserId(Binder.getCallingUid()); 21167 if (opti < args.length) { 21168 try { 21169 user = Integer.parseInt(args[opti]); 21170 } catch (NumberFormatException e) { 21171 pw.println("Error: check-permission user argument is not a number: " 21172 + args[opti]); 21173 return; 21174 } 21175 } 21176 21177 // Normalize package name to handle renamed packages and static libs 21178 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 21179 21180 pw.println(checkPermission(perm, pkg, user)); 21181 return; 21182 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 21183 dumpState.setDump(DumpState.DUMP_LIBS); 21184 } else if ("f".equals(cmd) || "features".equals(cmd)) { 21185 dumpState.setDump(DumpState.DUMP_FEATURES); 21186 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 21187 if (opti >= args.length) { 21188 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 21189 | DumpState.DUMP_SERVICE_RESOLVERS 21190 | DumpState.DUMP_RECEIVER_RESOLVERS 21191 | DumpState.DUMP_CONTENT_RESOLVERS); 21192 } else { 21193 while (opti < args.length) { 21194 String name = args[opti]; 21195 if ("a".equals(name) || "activity".equals(name)) { 21196 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 21197 } else if ("s".equals(name) || "service".equals(name)) { 21198 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 21199 } else if ("r".equals(name) || "receiver".equals(name)) { 21200 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 21201 } else if ("c".equals(name) || "content".equals(name)) { 21202 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 21203 } else { 21204 pw.println("Error: unknown resolver table type: " + name); 21205 return; 21206 } 21207 opti++; 21208 } 21209 } 21210 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 21211 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 21212 } else if ("permission".equals(cmd)) { 21213 if (opti >= args.length) { 21214 pw.println("Error: permission requires permission name"); 21215 return; 21216 } 21217 permissionNames = new ArraySet<>(); 21218 while (opti < args.length) { 21219 permissionNames.add(args[opti]); 21220 opti++; 21221 } 21222 dumpState.setDump(DumpState.DUMP_PERMISSIONS 21223 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 21224 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 21225 dumpState.setDump(DumpState.DUMP_PREFERRED); 21226 } else if ("preferred-xml".equals(cmd)) { 21227 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 21228 if (opti < args.length && "--full".equals(args[opti])) { 21229 fullPreferred = true; 21230 opti++; 21231 } 21232 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 21233 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 21234 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 21235 dumpState.setDump(DumpState.DUMP_PACKAGES); 21236 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 21237 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 21238 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 21239 dumpState.setDump(DumpState.DUMP_PROVIDERS); 21240 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 21241 dumpState.setDump(DumpState.DUMP_MESSAGES); 21242 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 21243 dumpState.setDump(DumpState.DUMP_VERIFIERS); 21244 } else if ("i".equals(cmd) || "ifv".equals(cmd) 21245 || "intent-filter-verifiers".equals(cmd)) { 21246 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 21247 } else if ("version".equals(cmd)) { 21248 dumpState.setDump(DumpState.DUMP_VERSION); 21249 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 21250 dumpState.setDump(DumpState.DUMP_KEYSETS); 21251 } else if ("installs".equals(cmd)) { 21252 dumpState.setDump(DumpState.DUMP_INSTALLS); 21253 } else if ("frozen".equals(cmd)) { 21254 dumpState.setDump(DumpState.DUMP_FROZEN); 21255 } else if ("volumes".equals(cmd)) { 21256 dumpState.setDump(DumpState.DUMP_VOLUMES); 21257 } else if ("dexopt".equals(cmd)) { 21258 dumpState.setDump(DumpState.DUMP_DEXOPT); 21259 } else if ("compiler-stats".equals(cmd)) { 21260 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 21261 } else if ("changes".equals(cmd)) { 21262 dumpState.setDump(DumpState.DUMP_CHANGES); 21263 } else if ("service-permissions".equals(cmd)) { 21264 dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS); 21265 } else if ("write".equals(cmd)) { 21266 synchronized (mPackages) { 21267 mSettings.writeLPr(); 21268 pw.println("Settings written."); 21269 return; 21270 } 21271 } 21272 } 21273 21274 if (checkin) { 21275 pw.println("vers,1"); 21276 } 21277 21278 // reader 21279 synchronized (mPackages) { 21280 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 21281 if (!checkin) { 21282 if (dumpState.onTitlePrinted()) 21283 pw.println(); 21284 pw.println("Database versions:"); 21285 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 21286 } 21287 } 21288 21289 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 21290 if (!checkin) { 21291 if (dumpState.onTitlePrinted()) 21292 pw.println(); 21293 pw.println("Verifiers:"); 21294 pw.print(" Required: "); 21295 pw.print(mRequiredVerifierPackage); 21296 pw.print(" (uid="); 21297 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21298 UserHandle.USER_SYSTEM)); 21299 pw.println(")"); 21300 } else if (mRequiredVerifierPackage != null) { 21301 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 21302 pw.print(","); 21303 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21304 UserHandle.USER_SYSTEM)); 21305 } 21306 } 21307 21308 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 21309 packageName == null) { 21310 if (mIntentFilterVerifierComponent != null) { 21311 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21312 if (!checkin) { 21313 if (dumpState.onTitlePrinted()) 21314 pw.println(); 21315 pw.println("Intent Filter Verifier:"); 21316 pw.print(" Using: "); 21317 pw.print(verifierPackageName); 21318 pw.print(" (uid="); 21319 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21320 UserHandle.USER_SYSTEM)); 21321 pw.println(")"); 21322 } else if (verifierPackageName != null) { 21323 pw.print("ifv,"); pw.print(verifierPackageName); 21324 pw.print(","); 21325 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21326 UserHandle.USER_SYSTEM)); 21327 } 21328 } else { 21329 pw.println(); 21330 pw.println("No Intent Filter Verifier available!"); 21331 } 21332 } 21333 21334 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 21335 boolean printedHeader = false; 21336 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 21337 while (it.hasNext()) { 21338 String libName = it.next(); 21339 LongSparseArray<SharedLibraryEntry> versionedLib 21340 = mSharedLibraries.get(libName); 21341 if (versionedLib == null) { 21342 continue; 21343 } 21344 final int versionCount = versionedLib.size(); 21345 for (int i = 0; i < versionCount; i++) { 21346 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 21347 if (!checkin) { 21348 if (!printedHeader) { 21349 if (dumpState.onTitlePrinted()) 21350 pw.println(); 21351 pw.println("Libraries:"); 21352 printedHeader = true; 21353 } 21354 pw.print(" "); 21355 } else { 21356 pw.print("lib,"); 21357 } 21358 pw.print(libEntry.info.getName()); 21359 if (libEntry.info.isStatic()) { 21360 pw.print(" version=" + libEntry.info.getLongVersion()); 21361 } 21362 if (!checkin) { 21363 pw.print(" -> "); 21364 } 21365 if (libEntry.path != null) { 21366 pw.print(" (jar) "); 21367 pw.print(libEntry.path); 21368 } else { 21369 pw.print(" (apk) "); 21370 pw.print(libEntry.apk); 21371 } 21372 pw.println(); 21373 } 21374 } 21375 } 21376 21377 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 21378 if (dumpState.onTitlePrinted()) 21379 pw.println(); 21380 if (!checkin) { 21381 pw.println("Features:"); 21382 } 21383 21384 synchronized (mAvailableFeatures) { 21385 for (FeatureInfo feat : mAvailableFeatures.values()) { 21386 if (checkin) { 21387 pw.print("feat,"); 21388 pw.print(feat.name); 21389 pw.print(","); 21390 pw.println(feat.version); 21391 } else { 21392 pw.print(" "); 21393 pw.print(feat.name); 21394 if (feat.version > 0) { 21395 pw.print(" version="); 21396 pw.print(feat.version); 21397 } 21398 pw.println(); 21399 } 21400 } 21401 } 21402 } 21403 21404 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 21405 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 21406 : "Activity Resolver Table:", " ", packageName, 21407 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21408 dumpState.setTitlePrinted(true); 21409 } 21410 } 21411 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 21412 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 21413 : "Receiver Resolver Table:", " ", packageName, 21414 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21415 dumpState.setTitlePrinted(true); 21416 } 21417 } 21418 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 21419 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 21420 : "Service Resolver Table:", " ", packageName, 21421 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21422 dumpState.setTitlePrinted(true); 21423 } 21424 } 21425 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 21426 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 21427 : "Provider Resolver Table:", " ", packageName, 21428 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21429 dumpState.setTitlePrinted(true); 21430 } 21431 } 21432 21433 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 21434 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21435 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21436 int user = mSettings.mPreferredActivities.keyAt(i); 21437 if (pir.dump(pw, 21438 dumpState.getTitlePrinted() 21439 ? "\nPreferred Activities User " + user + ":" 21440 : "Preferred Activities User " + user + ":", " ", 21441 packageName, true, false)) { 21442 dumpState.setTitlePrinted(true); 21443 } 21444 } 21445 } 21446 21447 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 21448 pw.flush(); 21449 FileOutputStream fout = new FileOutputStream(fd); 21450 BufferedOutputStream str = new BufferedOutputStream(fout); 21451 XmlSerializer serializer = new FastXmlSerializer(); 21452 try { 21453 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 21454 serializer.startDocument(null, true); 21455 serializer.setFeature( 21456 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 21457 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 21458 serializer.endDocument(); 21459 serializer.flush(); 21460 } catch (IllegalArgumentException e) { 21461 pw.println("Failed writing: " + e); 21462 } catch (IllegalStateException e) { 21463 pw.println("Failed writing: " + e); 21464 } catch (IOException e) { 21465 pw.println("Failed writing: " + e); 21466 } 21467 } 21468 21469 if (!checkin 21470 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 21471 && packageName == null) { 21472 pw.println(); 21473 int count = mSettings.mPackages.size(); 21474 if (count == 0) { 21475 pw.println("No applications!"); 21476 pw.println(); 21477 } else { 21478 final String prefix = " "; 21479 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 21480 if (allPackageSettings.size() == 0) { 21481 pw.println("No domain preferred apps!"); 21482 pw.println(); 21483 } else { 21484 pw.println("App verification status:"); 21485 pw.println(); 21486 count = 0; 21487 for (PackageSetting ps : allPackageSettings) { 21488 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 21489 if (ivi == null || ivi.getPackageName() == null) continue; 21490 pw.println(prefix + "Package: " + ivi.getPackageName()); 21491 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 21492 pw.println(prefix + "Status: " + ivi.getStatusString()); 21493 pw.println(); 21494 count++; 21495 } 21496 if (count == 0) { 21497 pw.println(prefix + "No app verification established."); 21498 pw.println(); 21499 } 21500 for (int userId : sUserManager.getUserIds()) { 21501 pw.println("App linkages for user " + userId + ":"); 21502 pw.println(); 21503 count = 0; 21504 for (PackageSetting ps : allPackageSettings) { 21505 final long status = ps.getDomainVerificationStatusForUser(userId); 21506 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 21507 && !DEBUG_DOMAIN_VERIFICATION) { 21508 continue; 21509 } 21510 pw.println(prefix + "Package: " + ps.name); 21511 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 21512 String statusStr = IntentFilterVerificationInfo. 21513 getStatusStringFromValue(status); 21514 pw.println(prefix + "Status: " + statusStr); 21515 pw.println(); 21516 count++; 21517 } 21518 if (count == 0) { 21519 pw.println(prefix + "No configured app linkages."); 21520 pw.println(); 21521 } 21522 } 21523 } 21524 } 21525 } 21526 21527 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 21528 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 21529 } 21530 21531 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 21532 boolean printedSomething = false; 21533 for (PackageParser.Provider p : mProviders.mProviders.values()) { 21534 if (packageName != null && !packageName.equals(p.info.packageName)) { 21535 continue; 21536 } 21537 if (!printedSomething) { 21538 if (dumpState.onTitlePrinted()) 21539 pw.println(); 21540 pw.println("Registered ContentProviders:"); 21541 printedSomething = true; 21542 } 21543 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 21544 pw.print(" "); pw.println(p.toString()); 21545 } 21546 printedSomething = false; 21547 for (Map.Entry<String, PackageParser.Provider> entry : 21548 mProvidersByAuthority.entrySet()) { 21549 PackageParser.Provider p = entry.getValue(); 21550 if (packageName != null && !packageName.equals(p.info.packageName)) { 21551 continue; 21552 } 21553 if (!printedSomething) { 21554 if (dumpState.onTitlePrinted()) 21555 pw.println(); 21556 pw.println("ContentProvider Authorities:"); 21557 printedSomething = true; 21558 } 21559 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 21560 pw.print(" "); pw.println(p.toString()); 21561 if (p.info != null && p.info.applicationInfo != null) { 21562 final String appInfo = p.info.applicationInfo.toString(); 21563 pw.print(" applicationInfo="); pw.println(appInfo); 21564 } 21565 } 21566 } 21567 21568 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 21569 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 21570 } 21571 21572 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 21573 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 21574 } 21575 21576 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 21577 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 21578 } 21579 21580 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 21581 if (dumpState.onTitlePrinted()) pw.println(); 21582 pw.println("Package Changes:"); 21583 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 21584 final int K = mChangedPackages.size(); 21585 for (int i = 0; i < K; i++) { 21586 final SparseArray<String> changes = mChangedPackages.valueAt(i); 21587 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 21588 final int N = changes.size(); 21589 if (N == 0) { 21590 pw.print(" "); pw.println("No packages changed"); 21591 } else { 21592 for (int j = 0; j < N; j++) { 21593 final String pkgName = changes.valueAt(j); 21594 final int sequenceNumber = changes.keyAt(j); 21595 pw.print(" "); 21596 pw.print("seq="); 21597 pw.print(sequenceNumber); 21598 pw.print(", package="); 21599 pw.println(pkgName); 21600 } 21601 } 21602 } 21603 } 21604 21605 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 21606 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 21607 } 21608 21609 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21610 // XXX should handle packageName != null by dumping only install data that 21611 // the given package is involved with. 21612 if (dumpState.onTitlePrinted()) pw.println(); 21613 21614 try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120)) { 21615 ipw.println(); 21616 ipw.println("Frozen packages:"); 21617 ipw.increaseIndent(); 21618 if (mFrozenPackages.size() == 0) { 21619 ipw.println("(none)"); 21620 } else { 21621 for (int i = 0; i < mFrozenPackages.size(); i++) { 21622 ipw.println(mFrozenPackages.valueAt(i)); 21623 } 21624 } 21625 ipw.decreaseIndent(); 21626 } 21627 } 21628 21629 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 21630 if (dumpState.onTitlePrinted()) pw.println(); 21631 21632 try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120)) { 21633 ipw.println(); 21634 ipw.println("Loaded volumes:"); 21635 ipw.increaseIndent(); 21636 if (mLoadedVolumes.size() == 0) { 21637 ipw.println("(none)"); 21638 } else { 21639 for (int i = 0; i < mLoadedVolumes.size(); i++) { 21640 ipw.println(mLoadedVolumes.valueAt(i)); 21641 } 21642 } 21643 ipw.decreaseIndent(); 21644 } 21645 } 21646 21647 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS) 21648 && packageName == null) { 21649 if (dumpState.onTitlePrinted()) pw.println(); 21650 pw.println("Service permissions:"); 21651 21652 final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator(); 21653 while (filterIterator.hasNext()) { 21654 final ServiceIntentInfo info = filterIterator.next(); 21655 final ServiceInfo serviceInfo = info.service.info; 21656 final String permission = serviceInfo.permission; 21657 if (permission != null) { 21658 pw.print(" "); 21659 pw.print(serviceInfo.getComponentName().flattenToShortString()); 21660 pw.print(": "); 21661 pw.println(permission); 21662 } 21663 } 21664 } 21665 21666 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21667 if (dumpState.onTitlePrinted()) pw.println(); 21668 dumpDexoptStateLPr(pw, packageName); 21669 } 21670 21671 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21672 if (dumpState.onTitlePrinted()) pw.println(); 21673 dumpCompilerStatsLPr(pw, packageName); 21674 } 21675 21676 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21677 if (dumpState.onTitlePrinted()) pw.println(); 21678 mSettings.dumpReadMessagesLPr(pw, dumpState); 21679 21680 pw.println(); 21681 pw.println("Package warning messages:"); 21682 dumpCriticalInfo(pw, null); 21683 } 21684 21685 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21686 dumpCriticalInfo(pw, "msg,"); 21687 } 21688 } 21689 21690 // PackageInstaller should be called outside of mPackages lock 21691 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21692 // XXX should handle packageName != null by dumping only install data that 21693 // the given package is involved with. 21694 if (dumpState.onTitlePrinted()) pw.println(); 21695 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21696 } 21697 } 21698 21699 private void dumpProto(FileDescriptor fd) { 21700 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21701 21702 synchronized (mPackages) { 21703 final long requiredVerifierPackageToken = 21704 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21705 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21706 proto.write( 21707 PackageServiceDumpProto.PackageShortProto.UID, 21708 getPackageUid( 21709 mRequiredVerifierPackage, 21710 MATCH_DEBUG_TRIAGED_MISSING, 21711 UserHandle.USER_SYSTEM)); 21712 proto.end(requiredVerifierPackageToken); 21713 21714 if (mIntentFilterVerifierComponent != null) { 21715 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21716 final long verifierPackageToken = 21717 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21718 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21719 proto.write( 21720 PackageServiceDumpProto.PackageShortProto.UID, 21721 getPackageUid( 21722 verifierPackageName, 21723 MATCH_DEBUG_TRIAGED_MISSING, 21724 UserHandle.USER_SYSTEM)); 21725 proto.end(verifierPackageToken); 21726 } 21727 21728 dumpSharedLibrariesProto(proto); 21729 dumpFeaturesProto(proto); 21730 mSettings.dumpPackagesProto(proto); 21731 mSettings.dumpSharedUsersProto(proto); 21732 dumpCriticalInfo(proto); 21733 } 21734 proto.flush(); 21735 } 21736 21737 private void dumpFeaturesProto(ProtoOutputStream proto) { 21738 synchronized (mAvailableFeatures) { 21739 final int count = mAvailableFeatures.size(); 21740 for (int i = 0; i < count; i++) { 21741 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES); 21742 } 21743 } 21744 } 21745 21746 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21747 final int count = mSharedLibraries.size(); 21748 for (int i = 0; i < count; i++) { 21749 final String libName = mSharedLibraries.keyAt(i); 21750 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21751 if (versionedLib == null) { 21752 continue; 21753 } 21754 final int versionCount = versionedLib.size(); 21755 for (int j = 0; j < versionCount; j++) { 21756 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21757 final long sharedLibraryToken = 21758 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21759 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21760 final boolean isJar = (libEntry.path != null); 21761 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21762 if (isJar) { 21763 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21764 } else { 21765 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21766 } 21767 proto.end(sharedLibraryToken); 21768 } 21769 } 21770 } 21771 21772 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21773 try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ")) { 21774 ipw.println(); 21775 ipw.println("Dexopt state:"); 21776 ipw.increaseIndent(); 21777 Collection<PackageParser.Package> packages = null; 21778 if (packageName != null) { 21779 PackageParser.Package targetPackage = mPackages.get(packageName); 21780 if (targetPackage != null) { 21781 packages = Collections.singletonList(targetPackage); 21782 } else { 21783 ipw.println("Unable to find package: " + packageName); 21784 return; 21785 } 21786 } else { 21787 packages = mPackages.values(); 21788 } 21789 21790 for (PackageParser.Package pkg : packages) { 21791 ipw.println("[" + pkg.packageName + "]"); 21792 ipw.increaseIndent(); 21793 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 21794 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 21795 ipw.decreaseIndent(); 21796 } 21797 } 21798 } 21799 21800 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21801 try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ")) { 21802 ipw.println(); 21803 ipw.println("Compiler stats:"); 21804 ipw.increaseIndent(); 21805 Collection<PackageParser.Package> packages = null; 21806 if (packageName != null) { 21807 PackageParser.Package targetPackage = mPackages.get(packageName); 21808 if (targetPackage != null) { 21809 packages = Collections.singletonList(targetPackage); 21810 } else { 21811 ipw.println("Unable to find package: " + packageName); 21812 return; 21813 } 21814 } else { 21815 packages = mPackages.values(); 21816 } 21817 21818 for (PackageParser.Package pkg : packages) { 21819 ipw.println("[" + pkg.packageName + "]"); 21820 ipw.increaseIndent(); 21821 21822 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21823 if (stats == null) { 21824 ipw.println("(No recorded stats)"); 21825 } else { 21826 stats.dump(ipw); 21827 } 21828 ipw.decreaseIndent(); 21829 } 21830 } 21831 } 21832 21833 private String dumpDomainString(String packageName) { 21834 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21835 .getList(); 21836 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21837 21838 ArraySet<String> result = new ArraySet<>(); 21839 if (iviList.size() > 0) { 21840 for (IntentFilterVerificationInfo ivi : iviList) { 21841 for (String host : ivi.getDomains()) { 21842 result.add(host); 21843 } 21844 } 21845 } 21846 if (filters != null && filters.size() > 0) { 21847 for (IntentFilter filter : filters) { 21848 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21849 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21850 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21851 result.addAll(filter.getHostsList()); 21852 } 21853 } 21854 } 21855 21856 StringBuilder sb = new StringBuilder(result.size() * 16); 21857 for (String domain : result) { 21858 if (sb.length() > 0) sb.append(" "); 21859 sb.append(domain); 21860 } 21861 return sb.toString(); 21862 } 21863 21864 // ------- apps on sdcard specific code ------- 21865 static final boolean DEBUG_SD_INSTALL = false; 21866 21867 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21868 21869 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21870 21871 private boolean mMediaMounted = false; 21872 21873 static String getEncryptKey() { 21874 try { 21875 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21876 SD_ENCRYPTION_KEYSTORE_NAME); 21877 if (sdEncKey == null) { 21878 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21879 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21880 if (sdEncKey == null) { 21881 Slog.e(TAG, "Failed to create encryption keys"); 21882 return null; 21883 } 21884 } 21885 return sdEncKey; 21886 } catch (NoSuchAlgorithmException nsae) { 21887 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21888 return null; 21889 } catch (IOException ioe) { 21890 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21891 return null; 21892 } 21893 } 21894 21895 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21896 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21897 final int size = infos.size(); 21898 final String[] packageNames = new String[size]; 21899 final int[] packageUids = new int[size]; 21900 for (int i = 0; i < size; i++) { 21901 final ApplicationInfo info = infos.get(i); 21902 packageNames[i] = info.packageName; 21903 packageUids[i] = info.uid; 21904 } 21905 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21906 finishedReceiver); 21907 } 21908 21909 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21910 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21911 sendResourcesChangedBroadcast(mediaStatus, replacing, 21912 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21913 } 21914 21915 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21916 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21917 int size = pkgList.length; 21918 if (size > 0) { 21919 // Send broadcasts here 21920 Bundle extras = new Bundle(); 21921 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21922 if (uidArr != null) { 21923 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21924 } 21925 if (replacing) { 21926 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21927 } 21928 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21929 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21930 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null); 21931 } 21932 } 21933 21934 private void loadPrivatePackages(final VolumeInfo vol) { 21935 mHandler.post(new Runnable() { 21936 @Override 21937 public void run() { 21938 loadPrivatePackagesInner(vol); 21939 } 21940 }); 21941 } 21942 21943 private void loadPrivatePackagesInner(VolumeInfo vol) { 21944 final String volumeUuid = vol.fsUuid; 21945 if (TextUtils.isEmpty(volumeUuid)) { 21946 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21947 return; 21948 } 21949 21950 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21951 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21952 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21953 21954 final VersionInfo ver; 21955 final List<PackageSetting> packages; 21956 synchronized (mPackages) { 21957 ver = mSettings.findOrCreateVersion(volumeUuid); 21958 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21959 } 21960 21961 for (PackageSetting ps : packages) { 21962 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21963 synchronized (mInstallLock) { 21964 final PackageParser.Package pkg; 21965 try { 21966 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21967 loaded.add(pkg.applicationInfo); 21968 21969 } catch (PackageManagerException e) { 21970 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21971 } 21972 21973 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21974 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21975 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21976 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21977 } 21978 } 21979 } 21980 21981 // Reconcile app data for all started/unlocked users 21982 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21983 final UserManager um = mContext.getSystemService(UserManager.class); 21984 UserManagerInternal umInternal = getUserManagerInternal(); 21985 for (UserInfo user : um.getUsers()) { 21986 final int flags; 21987 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21988 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21989 } else if (umInternal.isUserRunning(user.id)) { 21990 flags = StorageManager.FLAG_STORAGE_DE; 21991 } else { 21992 continue; 21993 } 21994 21995 try { 21996 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21997 synchronized (mInstallLock) { 21998 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21999 } 22000 } catch (IllegalStateException e) { 22001 // Device was probably ejected, and we'll process that event momentarily 22002 Slog.w(TAG, "Failed to prepare storage: " + e); 22003 } 22004 } 22005 22006 synchronized (mPackages) { 22007 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 22008 if (sdkUpdated) { 22009 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 22010 + mSdkVersion + "; regranting permissions for " + volumeUuid); 22011 } 22012 mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(), 22013 mPermissionCallback); 22014 22015 // Yay, everything is now upgraded 22016 ver.forceCurrent(); 22017 22018 mSettings.writeLPr(); 22019 } 22020 22021 for (PackageFreezer freezer : freezers) { 22022 freezer.close(); 22023 } 22024 22025 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 22026 sendResourcesChangedBroadcast(true, false, loaded, null); 22027 mLoadedVolumes.add(vol.getId()); 22028 } 22029 22030 private void unloadPrivatePackages(final VolumeInfo vol) { 22031 mHandler.post(new Runnable() { 22032 @Override 22033 public void run() { 22034 unloadPrivatePackagesInner(vol); 22035 } 22036 }); 22037 } 22038 22039 private void unloadPrivatePackagesInner(VolumeInfo vol) { 22040 final String volumeUuid = vol.fsUuid; 22041 if (TextUtils.isEmpty(volumeUuid)) { 22042 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 22043 return; 22044 } 22045 22046 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 22047 synchronized (mInstallLock) { 22048 synchronized (mPackages) { 22049 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 22050 for (PackageSetting ps : packages) { 22051 if (ps.pkg == null) continue; 22052 22053 final ApplicationInfo info = ps.pkg.applicationInfo; 22054 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 22055 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 22056 22057 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 22058 "unloadPrivatePackagesInner")) { 22059 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 22060 false, null)) { 22061 unloaded.add(info); 22062 } else { 22063 Slog.w(TAG, "Failed to unload " + ps.codePath); 22064 } 22065 } 22066 22067 // Try very hard to release any references to this package 22068 // so we don't risk the system server being killed due to 22069 // open FDs 22070 AttributeCache.instance().removePackage(ps.name); 22071 } 22072 22073 mSettings.writeLPr(); 22074 } 22075 } 22076 22077 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 22078 sendResourcesChangedBroadcast(false, false, unloaded, null); 22079 mLoadedVolumes.remove(vol.getId()); 22080 22081 // Try very hard to release any references to this path so we don't risk 22082 // the system server being killed due to open FDs 22083 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 22084 22085 for (int i = 0; i < 3; i++) { 22086 System.gc(); 22087 System.runFinalization(); 22088 } 22089 } 22090 22091 private void assertPackageKnown(String volumeUuid, String packageName) 22092 throws PackageManagerException { 22093 synchronized (mPackages) { 22094 // Normalize package name to handle renamed packages 22095 packageName = normalizePackageNameLPr(packageName); 22096 22097 final PackageSetting ps = mSettings.mPackages.get(packageName); 22098 if (ps == null) { 22099 throw new PackageManagerException("Package " + packageName + " is unknown"); 22100 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 22101 throw new PackageManagerException( 22102 "Package " + packageName + " found on unknown volume " + volumeUuid 22103 + "; expected volume " + ps.volumeUuid); 22104 } 22105 } 22106 } 22107 22108 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 22109 throws PackageManagerException { 22110 synchronized (mPackages) { 22111 // Normalize package name to handle renamed packages 22112 packageName = normalizePackageNameLPr(packageName); 22113 22114 final PackageSetting ps = mSettings.mPackages.get(packageName); 22115 if (ps == null) { 22116 throw new PackageManagerException("Package " + packageName + " is unknown"); 22117 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 22118 throw new PackageManagerException( 22119 "Package " + packageName + " found on unknown volume " + volumeUuid 22120 + "; expected volume " + ps.volumeUuid); 22121 } else if (!ps.getInstalled(userId)) { 22122 throw new PackageManagerException( 22123 "Package " + packageName + " not installed for user " + userId); 22124 } 22125 } 22126 } 22127 22128 private List<String> collectAbsoluteCodePaths() { 22129 synchronized (mPackages) { 22130 List<String> codePaths = new ArrayList<>(); 22131 final int packageCount = mSettings.mPackages.size(); 22132 for (int i = 0; i < packageCount; i++) { 22133 final PackageSetting ps = mSettings.mPackages.valueAt(i); 22134 codePaths.add(ps.codePath.getAbsolutePath()); 22135 } 22136 return codePaths; 22137 } 22138 } 22139 22140 /** 22141 * Examine all apps present on given mounted volume, and destroy apps that 22142 * aren't expected, either due to uninstallation or reinstallation on 22143 * another volume. 22144 */ 22145 private void reconcileApps(String volumeUuid) { 22146 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 22147 List<File> filesToDelete = null; 22148 22149 final File[] files = FileUtils.listFilesOrEmpty( 22150 Environment.getDataAppDirectory(volumeUuid)); 22151 for (File file : files) { 22152 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 22153 && !PackageInstallerService.isStageName(file.getName()); 22154 if (!isPackage) { 22155 // Ignore entries which are not packages 22156 continue; 22157 } 22158 22159 String absolutePath = file.getAbsolutePath(); 22160 22161 boolean pathValid = false; 22162 final int absoluteCodePathCount = absoluteCodePaths.size(); 22163 for (int i = 0; i < absoluteCodePathCount; i++) { 22164 String absoluteCodePath = absoluteCodePaths.get(i); 22165 if (absolutePath.startsWith(absoluteCodePath)) { 22166 pathValid = true; 22167 break; 22168 } 22169 } 22170 22171 if (!pathValid) { 22172 if (filesToDelete == null) { 22173 filesToDelete = new ArrayList<>(); 22174 } 22175 filesToDelete.add(file); 22176 } 22177 } 22178 22179 if (filesToDelete != null) { 22180 final int fileToDeleteCount = filesToDelete.size(); 22181 for (int i = 0; i < fileToDeleteCount; i++) { 22182 File fileToDelete = filesToDelete.get(i); 22183 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 22184 synchronized (mInstallLock) { 22185 removeCodePathLI(fileToDelete); 22186 } 22187 } 22188 } 22189 } 22190 22191 /** 22192 * Reconcile all app data for the given user. 22193 * <p> 22194 * Verifies that directories exist and that ownership and labeling is 22195 * correct for all installed apps on all mounted volumes. 22196 */ 22197 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 22198 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22199 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 22200 final String volumeUuid = vol.getFsUuid(); 22201 synchronized (mInstallLock) { 22202 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 22203 } 22204 } 22205 } 22206 22207 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22208 boolean migrateAppData) { 22209 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 22210 } 22211 22212 /** 22213 * Reconcile all app data on given mounted volume. 22214 * <p> 22215 * Destroys app data that isn't expected, either due to uninstallation or 22216 * reinstallation on another volume. 22217 * <p> 22218 * Verifies that directories exist and that ownership and labeling is 22219 * correct for all installed apps. 22220 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 22221 */ 22222 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22223 boolean migrateAppData, boolean onlyCoreApps) { 22224 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 22225 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 22226 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 22227 22228 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 22229 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 22230 22231 // First look for stale data that doesn't belong, and check if things 22232 // have changed since we did our last restorecon 22233 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22234 if (StorageManager.isFileEncryptedNativeOrEmulated() 22235 && !StorageManager.isUserKeyUnlocked(userId)) { 22236 throw new RuntimeException( 22237 "Yikes, someone asked us to reconcile CE storage while " + userId 22238 + " was still locked; this would have caused massive data loss!"); 22239 } 22240 22241 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 22242 for (File file : files) { 22243 final String packageName = file.getName(); 22244 try { 22245 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22246 } catch (PackageManagerException e) { 22247 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22248 try { 22249 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22250 StorageManager.FLAG_STORAGE_CE, 0); 22251 } catch (InstallerException e2) { 22252 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22253 } 22254 } 22255 } 22256 } 22257 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 22258 final File[] files = FileUtils.listFilesOrEmpty(deDir); 22259 for (File file : files) { 22260 final String packageName = file.getName(); 22261 try { 22262 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22263 } catch (PackageManagerException e) { 22264 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22265 try { 22266 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22267 StorageManager.FLAG_STORAGE_DE, 0); 22268 } catch (InstallerException e2) { 22269 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22270 } 22271 } 22272 } 22273 } 22274 22275 // Ensure that data directories are ready to roll for all packages 22276 // installed for this volume and user 22277 final List<PackageSetting> packages; 22278 synchronized (mPackages) { 22279 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22280 } 22281 int preparedCount = 0; 22282 for (PackageSetting ps : packages) { 22283 final String packageName = ps.name; 22284 if (ps.pkg == null) { 22285 Slog.w(TAG, "Odd, missing scanned package " + packageName); 22286 // TODO: might be due to legacy ASEC apps; we should circle back 22287 // and reconcile again once they're scanned 22288 continue; 22289 } 22290 // Skip non-core apps if requested 22291 if (onlyCoreApps && !ps.pkg.coreApp) { 22292 result.add(packageName); 22293 continue; 22294 } 22295 22296 if (ps.getInstalled(userId)) { 22297 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 22298 preparedCount++; 22299 } 22300 } 22301 22302 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 22303 return result; 22304 } 22305 22306 /** 22307 * Prepare app data for the given app just after it was installed or 22308 * upgraded. This method carefully only touches users that it's installed 22309 * for, and it forces a restorecon to handle any seinfo changes. 22310 * <p> 22311 * Verifies that directories exist and that ownership and labeling is 22312 * correct for all installed apps. If there is an ownership mismatch, it 22313 * will try recovering system apps by wiping data; third-party app data is 22314 * left intact. 22315 * <p> 22316 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 22317 */ 22318 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 22319 final PackageSetting ps; 22320 synchronized (mPackages) { 22321 ps = mSettings.mPackages.get(pkg.packageName); 22322 mSettings.writeKernelMappingLPr(ps); 22323 } 22324 22325 final UserManager um = mContext.getSystemService(UserManager.class); 22326 UserManagerInternal umInternal = getUserManagerInternal(); 22327 for (UserInfo user : um.getUsers()) { 22328 final int flags; 22329 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22330 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22331 } else if (umInternal.isUserRunning(user.id)) { 22332 flags = StorageManager.FLAG_STORAGE_DE; 22333 } else { 22334 continue; 22335 } 22336 22337 if (ps.getInstalled(user.id)) { 22338 // TODO: when user data is locked, mark that we're still dirty 22339 prepareAppDataLIF(pkg, user.id, flags); 22340 } 22341 } 22342 } 22343 22344 /** 22345 * Prepare app data for the given app. 22346 * <p> 22347 * Verifies that directories exist and that ownership and labeling is 22348 * correct for all installed apps. If there is an ownership mismatch, this 22349 * will try recovering system apps by wiping data; third-party app data is 22350 * left intact. 22351 */ 22352 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 22353 if (pkg == null) { 22354 Slog.wtf(TAG, "Package was null!", new Throwable()); 22355 return; 22356 } 22357 prepareAppDataLeafLIF(pkg, userId, flags); 22358 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22359 for (int i = 0; i < childCount; i++) { 22360 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 22361 } 22362 } 22363 22364 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 22365 boolean maybeMigrateAppData) { 22366 prepareAppDataLIF(pkg, userId, flags); 22367 22368 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 22369 // We may have just shuffled around app data directories, so 22370 // prepare them one more time 22371 prepareAppDataLIF(pkg, userId, flags); 22372 } 22373 } 22374 22375 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22376 if (DEBUG_APP_DATA) { 22377 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 22378 + Integer.toHexString(flags)); 22379 } 22380 22381 final String volumeUuid = pkg.volumeUuid; 22382 final String packageName = pkg.packageName; 22383 final ApplicationInfo app = pkg.applicationInfo; 22384 final int appId = UserHandle.getAppId(app.uid); 22385 22386 Preconditions.checkNotNull(app.seInfo); 22387 22388 long ceDataInode = -1; 22389 try { 22390 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22391 appId, app.seInfo, app.targetSdkVersion); 22392 } catch (InstallerException e) { 22393 if (app.isSystemApp()) { 22394 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 22395 + ", but trying to recover: " + e); 22396 destroyAppDataLeafLIF(pkg, userId, flags); 22397 try { 22398 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22399 appId, app.seInfo, app.targetSdkVersion); 22400 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 22401 } catch (InstallerException e2) { 22402 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 22403 } 22404 } else { 22405 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22406 } 22407 } 22408 // Prepare the application profiles only for upgrades and first boot (so that we don't 22409 // repeat the same operation at each boot). 22410 // We only have to cover the upgrade and first boot here because for app installs we 22411 // prepare the profiles before invoking dexopt (in installPackageLI). 22412 // 22413 // We also have to cover non system users because we do not call the usual install package 22414 // methods for them. 22415 if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) { 22416 mArtManagerService.prepareAppProfiles(pkg, userId); 22417 } 22418 22419 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22420 // TODO: mark this structure as dirty so we persist it! 22421 synchronized (mPackages) { 22422 final PackageSetting ps = mSettings.mPackages.get(packageName); 22423 if (ps != null) { 22424 ps.setCeDataInode(ceDataInode, userId); 22425 } 22426 } 22427 } 22428 22429 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22430 } 22431 22432 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22433 if (pkg == null) { 22434 Slog.wtf(TAG, "Package was null!", new Throwable()); 22435 return; 22436 } 22437 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22438 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22439 for (int i = 0; i < childCount; i++) { 22440 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22441 } 22442 } 22443 22444 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22445 final String volumeUuid = pkg.volumeUuid; 22446 final String packageName = pkg.packageName; 22447 final ApplicationInfo app = pkg.applicationInfo; 22448 22449 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22450 // Create a native library symlink only if we have native libraries 22451 // and if the native libraries are 32 bit libraries. We do not provide 22452 // this symlink for 64 bit libraries. 22453 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22454 final String nativeLibPath = app.nativeLibraryDir; 22455 try { 22456 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22457 nativeLibPath, userId); 22458 } catch (InstallerException e) { 22459 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22460 } 22461 } 22462 } 22463 } 22464 22465 /** 22466 * For system apps on non-FBE devices, this method migrates any existing 22467 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22468 * requested by the app. 22469 */ 22470 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22471 if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated() 22472 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22473 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22474 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22475 try { 22476 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22477 storageTarget); 22478 } catch (InstallerException e) { 22479 logCriticalInfo(Log.WARN, 22480 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22481 } 22482 return true; 22483 } else { 22484 return false; 22485 } 22486 } 22487 22488 public PackageFreezer freezePackage(String packageName, String killReason) { 22489 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22490 } 22491 22492 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22493 return new PackageFreezer(packageName, userId, killReason); 22494 } 22495 22496 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22497 String killReason) { 22498 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22499 } 22500 22501 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22502 String killReason) { 22503 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22504 return new PackageFreezer(); 22505 } else { 22506 return freezePackage(packageName, userId, killReason); 22507 } 22508 } 22509 22510 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22511 String killReason) { 22512 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22513 } 22514 22515 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22516 String killReason) { 22517 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22518 return new PackageFreezer(); 22519 } else { 22520 return freezePackage(packageName, userId, killReason); 22521 } 22522 } 22523 22524 /** 22525 * Class that freezes and kills the given package upon creation, and 22526 * unfreezes it upon closing. This is typically used when doing surgery on 22527 * app code/data to prevent the app from running while you're working. 22528 */ 22529 private class PackageFreezer implements AutoCloseable { 22530 private final String mPackageName; 22531 private final PackageFreezer[] mChildren; 22532 22533 private final boolean mWeFroze; 22534 22535 private final AtomicBoolean mClosed = new AtomicBoolean(); 22536 private final CloseGuard mCloseGuard = CloseGuard.get(); 22537 22538 /** 22539 * Create and return a stub freezer that doesn't actually do anything, 22540 * typically used when someone requested 22541 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22542 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22543 */ 22544 public PackageFreezer() { 22545 mPackageName = null; 22546 mChildren = null; 22547 mWeFroze = false; 22548 mCloseGuard.open("close"); 22549 } 22550 22551 public PackageFreezer(String packageName, int userId, String killReason) { 22552 synchronized (mPackages) { 22553 mPackageName = packageName; 22554 mWeFroze = mFrozenPackages.add(mPackageName); 22555 22556 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22557 if (ps != null) { 22558 killApplication(ps.name, ps.appId, userId, killReason); 22559 } 22560 22561 final PackageParser.Package p = mPackages.get(packageName); 22562 if (p != null && p.childPackages != null) { 22563 final int N = p.childPackages.size(); 22564 mChildren = new PackageFreezer[N]; 22565 for (int i = 0; i < N; i++) { 22566 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22567 userId, killReason); 22568 } 22569 } else { 22570 mChildren = null; 22571 } 22572 } 22573 mCloseGuard.open("close"); 22574 } 22575 22576 @Override 22577 protected void finalize() throws Throwable { 22578 try { 22579 if (mCloseGuard != null) { 22580 mCloseGuard.warnIfOpen(); 22581 } 22582 22583 close(); 22584 } finally { 22585 super.finalize(); 22586 } 22587 } 22588 22589 @Override 22590 public void close() { 22591 mCloseGuard.close(); 22592 if (mClosed.compareAndSet(false, true)) { 22593 synchronized (mPackages) { 22594 if (mWeFroze) { 22595 mFrozenPackages.remove(mPackageName); 22596 } 22597 22598 if (mChildren != null) { 22599 for (PackageFreezer freezer : mChildren) { 22600 freezer.close(); 22601 } 22602 } 22603 } 22604 } 22605 } 22606 } 22607 22608 /** 22609 * Verify that given package is currently frozen. 22610 */ 22611 private void checkPackageFrozen(String packageName) { 22612 synchronized (mPackages) { 22613 if (!mFrozenPackages.contains(packageName)) { 22614 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22615 } 22616 } 22617 } 22618 22619 @Override 22620 public int movePackage(final String packageName, final String volumeUuid) { 22621 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22622 22623 final int callingUid = Binder.getCallingUid(); 22624 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 22625 final int moveId = mNextMoveId.getAndIncrement(); 22626 mHandler.post(new Runnable() { 22627 @Override 22628 public void run() { 22629 try { 22630 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 22631 } catch (PackageManagerException e) { 22632 Slog.w(TAG, "Failed to move " + packageName, e); 22633 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 22634 } 22635 } 22636 }); 22637 return moveId; 22638 } 22639 22640 private void movePackageInternal(final String packageName, final String volumeUuid, 22641 final int moveId, final int callingUid, UserHandle user) 22642 throws PackageManagerException { 22643 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22644 final PackageManager pm = mContext.getPackageManager(); 22645 22646 final boolean currentAsec; 22647 final String currentVolumeUuid; 22648 final File codeFile; 22649 final String installerPackageName; 22650 final String packageAbiOverride; 22651 final int appId; 22652 final String seinfo; 22653 final String label; 22654 final int targetSdkVersion; 22655 final PackageFreezer freezer; 22656 final int[] installedUserIds; 22657 22658 // reader 22659 synchronized (mPackages) { 22660 final PackageParser.Package pkg = mPackages.get(packageName); 22661 final PackageSetting ps = mSettings.mPackages.get(packageName); 22662 if (pkg == null 22663 || ps == null 22664 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 22665 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22666 } 22667 if (pkg.applicationInfo.isSystemApp()) { 22668 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22669 "Cannot move system application"); 22670 } 22671 22672 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22673 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22674 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22675 if (isInternalStorage && !allow3rdPartyOnInternal) { 22676 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22677 "3rd party apps are not allowed on internal storage"); 22678 } 22679 22680 if (pkg.applicationInfo.isExternalAsec()) { 22681 currentAsec = true; 22682 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22683 } else if (pkg.applicationInfo.isForwardLocked()) { 22684 currentAsec = true; 22685 currentVolumeUuid = "forward_locked"; 22686 } else { 22687 currentAsec = false; 22688 currentVolumeUuid = ps.volumeUuid; 22689 22690 final File probe = new File(pkg.codePath); 22691 final File probeOat = new File(probe, "oat"); 22692 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22693 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22694 "Move only supported for modern cluster style installs"); 22695 } 22696 } 22697 22698 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22699 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22700 "Package already moved to " + volumeUuid); 22701 } 22702 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22703 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22704 "Device admin cannot be moved"); 22705 } 22706 22707 if (mFrozenPackages.contains(packageName)) { 22708 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22709 "Failed to move already frozen package"); 22710 } 22711 22712 codeFile = new File(pkg.codePath); 22713 installerPackageName = ps.installerPackageName; 22714 packageAbiOverride = ps.cpuAbiOverrideString; 22715 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22716 seinfo = pkg.applicationInfo.seInfo; 22717 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22718 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22719 freezer = freezePackage(packageName, "movePackageInternal"); 22720 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22721 } 22722 22723 final Bundle extras = new Bundle(); 22724 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22725 extras.putString(Intent.EXTRA_TITLE, label); 22726 mMoveCallbacks.notifyCreated(moveId, extras); 22727 22728 int installFlags; 22729 final boolean moveCompleteApp; 22730 final File measurePath; 22731 22732 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22733 installFlags = INSTALL_INTERNAL; 22734 moveCompleteApp = !currentAsec; 22735 measurePath = Environment.getDataAppDirectory(volumeUuid); 22736 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22737 installFlags = INSTALL_EXTERNAL; 22738 moveCompleteApp = false; 22739 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22740 } else { 22741 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22742 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22743 || !volume.isMountedWritable()) { 22744 freezer.close(); 22745 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22746 "Move location not mounted private volume"); 22747 } 22748 22749 Preconditions.checkState(!currentAsec); 22750 22751 installFlags = INSTALL_INTERNAL; 22752 moveCompleteApp = true; 22753 measurePath = Environment.getDataAppDirectory(volumeUuid); 22754 } 22755 22756 // If we're moving app data around, we need all the users unlocked 22757 if (moveCompleteApp) { 22758 for (int userId : installedUserIds) { 22759 if (StorageManager.isFileEncryptedNativeOrEmulated() 22760 && !StorageManager.isUserKeyUnlocked(userId)) { 22761 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 22762 "User " + userId + " must be unlocked"); 22763 } 22764 } 22765 } 22766 22767 final PackageStats stats = new PackageStats(null, -1); 22768 synchronized (mInstaller) { 22769 for (int userId : installedUserIds) { 22770 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22771 freezer.close(); 22772 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22773 "Failed to measure package size"); 22774 } 22775 } 22776 } 22777 22778 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22779 + stats.dataSize); 22780 22781 final long startFreeBytes = measurePath.getUsableSpace(); 22782 final long sizeBytes; 22783 if (moveCompleteApp) { 22784 sizeBytes = stats.codeSize + stats.dataSize; 22785 } else { 22786 sizeBytes = stats.codeSize; 22787 } 22788 22789 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22790 freezer.close(); 22791 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22792 "Not enough free space to move"); 22793 } 22794 22795 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22796 22797 final CountDownLatch installedLatch = new CountDownLatch(1); 22798 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22799 @Override 22800 public void onUserActionRequired(Intent intent) throws RemoteException { 22801 throw new IllegalStateException(); 22802 } 22803 22804 @Override 22805 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22806 Bundle extras) throws RemoteException { 22807 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22808 + PackageManager.installStatusToString(returnCode, msg)); 22809 22810 installedLatch.countDown(); 22811 freezer.close(); 22812 22813 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22814 switch (status) { 22815 case PackageInstaller.STATUS_SUCCESS: 22816 mMoveCallbacks.notifyStatusChanged(moveId, 22817 PackageManager.MOVE_SUCCEEDED); 22818 break; 22819 case PackageInstaller.STATUS_FAILURE_STORAGE: 22820 mMoveCallbacks.notifyStatusChanged(moveId, 22821 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22822 break; 22823 default: 22824 mMoveCallbacks.notifyStatusChanged(moveId, 22825 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22826 break; 22827 } 22828 } 22829 }; 22830 22831 final MoveInfo move; 22832 if (moveCompleteApp) { 22833 // Kick off a thread to report progress estimates 22834 new Thread() { 22835 @Override 22836 public void run() { 22837 while (true) { 22838 try { 22839 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22840 break; 22841 } 22842 } catch (InterruptedException ignored) { 22843 } 22844 22845 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22846 final int progress = 10 + (int) MathUtils.constrain( 22847 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22848 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22849 } 22850 } 22851 }.start(); 22852 22853 final String dataAppName = codeFile.getName(); 22854 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22855 dataAppName, appId, seinfo, targetSdkVersion); 22856 } else { 22857 move = null; 22858 } 22859 22860 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22861 22862 final Message msg = mHandler.obtainMessage(INIT_COPY); 22863 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22864 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22865 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22866 packageAbiOverride, null /*grantedPermissions*/, 22867 PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN); 22868 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22869 msg.obj = params; 22870 22871 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22872 System.identityHashCode(msg.obj)); 22873 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22874 System.identityHashCode(msg.obj)); 22875 22876 mHandler.sendMessage(msg); 22877 } 22878 22879 @Override 22880 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22881 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22882 22883 final int realMoveId = mNextMoveId.getAndIncrement(); 22884 final Bundle extras = new Bundle(); 22885 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22886 mMoveCallbacks.notifyCreated(realMoveId, extras); 22887 22888 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22889 @Override 22890 public void onCreated(int moveId, Bundle extras) { 22891 // Ignored 22892 } 22893 22894 @Override 22895 public void onStatusChanged(int moveId, int status, long estMillis) { 22896 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22897 } 22898 }; 22899 22900 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22901 storage.setPrimaryStorageUuid(volumeUuid, callback); 22902 return realMoveId; 22903 } 22904 22905 @Override 22906 public int getMoveStatus(int moveId) { 22907 mContext.enforceCallingOrSelfPermission( 22908 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22909 return mMoveCallbacks.mLastStatus.get(moveId); 22910 } 22911 22912 @Override 22913 public void registerMoveCallback(IPackageMoveObserver callback) { 22914 mContext.enforceCallingOrSelfPermission( 22915 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22916 mMoveCallbacks.register(callback); 22917 } 22918 22919 @Override 22920 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22921 mContext.enforceCallingOrSelfPermission( 22922 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22923 mMoveCallbacks.unregister(callback); 22924 } 22925 22926 @Override 22927 public boolean setInstallLocation(int loc) { 22928 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22929 null); 22930 if (getInstallLocation() == loc) { 22931 return true; 22932 } 22933 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22934 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22935 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22936 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22937 return true; 22938 } 22939 return false; 22940 } 22941 22942 @Override 22943 public int getInstallLocation() { 22944 // allow instant app access 22945 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22946 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22947 PackageHelper.APP_INSTALL_AUTO); 22948 } 22949 22950 /** Called by UserManagerService */ 22951 void cleanUpUser(UserManagerService userManager, int userHandle) { 22952 synchronized (mPackages) { 22953 mDirtyUsers.remove(userHandle); 22954 mUserNeedsBadging.delete(userHandle); 22955 mSettings.removeUserLPw(userHandle); 22956 mPendingBroadcasts.remove(userHandle); 22957 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22958 removeUnusedPackagesLPw(userManager, userHandle); 22959 } 22960 } 22961 22962 /** 22963 * We're removing userHandle and would like to remove any downloaded packages 22964 * that are no longer in use by any other user. 22965 * @param userHandle the user being removed 22966 */ 22967 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22968 final boolean DEBUG_CLEAN_APKS = false; 22969 int [] users = userManager.getUserIds(); 22970 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22971 while (psit.hasNext()) { 22972 PackageSetting ps = psit.next(); 22973 if (ps.pkg == null) { 22974 continue; 22975 } 22976 final String packageName = ps.pkg.packageName; 22977 // Skip over if system app 22978 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22979 continue; 22980 } 22981 if (DEBUG_CLEAN_APKS) { 22982 Slog.i(TAG, "Checking package " + packageName); 22983 } 22984 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22985 if (keep) { 22986 if (DEBUG_CLEAN_APKS) { 22987 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22988 } 22989 } else { 22990 for (int i = 0; i < users.length; i++) { 22991 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22992 keep = true; 22993 if (DEBUG_CLEAN_APKS) { 22994 Slog.i(TAG, " Keeping package " + packageName + " for user " 22995 + users[i]); 22996 } 22997 break; 22998 } 22999 } 23000 } 23001 if (!keep) { 23002 if (DEBUG_CLEAN_APKS) { 23003 Slog.i(TAG, " Removing package " + packageName); 23004 } 23005 mHandler.post(new Runnable() { 23006 public void run() { 23007 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23008 userHandle, 0); 23009 } //end run 23010 }); 23011 } 23012 } 23013 } 23014 23015 /** Called by UserManagerService */ 23016 void createNewUser(int userId, String[] disallowedPackages) { 23017 synchronized (mInstallLock) { 23018 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 23019 } 23020 synchronized (mPackages) { 23021 scheduleWritePackageRestrictionsLocked(userId); 23022 scheduleWritePackageListLocked(userId); 23023 applyFactoryDefaultBrowserLPw(userId); 23024 primeDomainVerificationsLPw(userId); 23025 } 23026 } 23027 23028 void onNewUserCreated(final int userId) { 23029 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 23030 synchronized(mPackages) { 23031 // If permission review for legacy apps is required, we represent 23032 // dagerous permissions for such apps as always granted runtime 23033 // permissions to keep per user flag state whether review is needed. 23034 // Hence, if a new user is added we have to propagate dangerous 23035 // permission grants for these legacy apps. 23036 if (mSettings.mPermissions.mPermissionReviewRequired) { 23037// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG 23038 mPermissionManager.updateAllPermissions( 23039 StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(), 23040 mPermissionCallback); 23041 } 23042 } 23043 } 23044 23045 @Override 23046 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 23047 mContext.enforceCallingOrSelfPermission( 23048 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 23049 "Only package verification agents can read the verifier device identity"); 23050 23051 synchronized (mPackages) { 23052 return mSettings.getVerifierDeviceIdentityLPw(); 23053 } 23054 } 23055 23056 @Override 23057 public void setPermissionEnforced(String permission, boolean enforced) { 23058 // TODO: Now that we no longer change GID for storage, this should to away. 23059 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 23060 "setPermissionEnforced"); 23061 if (READ_EXTERNAL_STORAGE.equals(permission)) { 23062 synchronized (mPackages) { 23063 if (mSettings.mReadExternalStorageEnforced == null 23064 || mSettings.mReadExternalStorageEnforced != enforced) { 23065 mSettings.mReadExternalStorageEnforced = 23066 enforced ? Boolean.TRUE : Boolean.FALSE; 23067 mSettings.writeLPr(); 23068 } 23069 } 23070 // kill any non-foreground processes so we restart them and 23071 // grant/revoke the GID. 23072 final IActivityManager am = ActivityManager.getService(); 23073 if (am != null) { 23074 final long token = Binder.clearCallingIdentity(); 23075 try { 23076 am.killProcessesBelowForeground("setPermissionEnforcement"); 23077 } catch (RemoteException e) { 23078 } finally { 23079 Binder.restoreCallingIdentity(token); 23080 } 23081 } 23082 } else { 23083 throw new IllegalArgumentException("No selective enforcement for " + permission); 23084 } 23085 } 23086 23087 @Override 23088 @Deprecated 23089 public boolean isPermissionEnforced(String permission) { 23090 // allow instant applications 23091 return true; 23092 } 23093 23094 @Override 23095 public boolean isStorageLow() { 23096 // allow instant applications 23097 final long token = Binder.clearCallingIdentity(); 23098 try { 23099 final DeviceStorageMonitorInternal 23100 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 23101 if (dsm != null) { 23102 return dsm.isMemoryLow(); 23103 } else { 23104 return false; 23105 } 23106 } finally { 23107 Binder.restoreCallingIdentity(token); 23108 } 23109 } 23110 23111 @Override 23112 public IPackageInstaller getPackageInstaller() { 23113 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23114 return null; 23115 } 23116 return mInstallerService; 23117 } 23118 23119 @Override 23120 public IArtManager getArtManager() { 23121 return mArtManagerService; 23122 } 23123 23124 private boolean userNeedsBadging(int userId) { 23125 int index = mUserNeedsBadging.indexOfKey(userId); 23126 if (index < 0) { 23127 final UserInfo userInfo; 23128 final long token = Binder.clearCallingIdentity(); 23129 try { 23130 userInfo = sUserManager.getUserInfo(userId); 23131 } finally { 23132 Binder.restoreCallingIdentity(token); 23133 } 23134 final boolean b; 23135 if (userInfo != null && userInfo.isManagedProfile()) { 23136 b = true; 23137 } else { 23138 b = false; 23139 } 23140 mUserNeedsBadging.put(userId, b); 23141 return b; 23142 } 23143 return mUserNeedsBadging.valueAt(index); 23144 } 23145 23146 @Override 23147 public KeySet getKeySetByAlias(String packageName, String alias) { 23148 if (packageName == null || alias == null) { 23149 return null; 23150 } 23151 synchronized(mPackages) { 23152 final PackageParser.Package pkg = mPackages.get(packageName); 23153 if (pkg == null) { 23154 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23155 throw new IllegalArgumentException("Unknown package: " + packageName); 23156 } 23157 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23158 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 23159 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 23160 throw new IllegalArgumentException("Unknown package: " + packageName); 23161 } 23162 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23163 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 23164 } 23165 } 23166 23167 @Override 23168 public KeySet getSigningKeySet(String packageName) { 23169 if (packageName == null) { 23170 return null; 23171 } 23172 synchronized(mPackages) { 23173 final int callingUid = Binder.getCallingUid(); 23174 final int callingUserId = UserHandle.getUserId(callingUid); 23175 final PackageParser.Package pkg = mPackages.get(packageName); 23176 if (pkg == null) { 23177 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23178 throw new IllegalArgumentException("Unknown package: " + packageName); 23179 } 23180 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23181 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 23182 // filter and pretend the package doesn't exist 23183 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 23184 + ", uid:" + callingUid); 23185 throw new IllegalArgumentException("Unknown package: " + packageName); 23186 } 23187 if (pkg.applicationInfo.uid != callingUid 23188 && Process.SYSTEM_UID != callingUid) { 23189 throw new SecurityException("May not access signing KeySet of other apps."); 23190 } 23191 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23192 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 23193 } 23194 } 23195 23196 @Override 23197 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 23198 final int callingUid = Binder.getCallingUid(); 23199 if (getInstantAppPackageName(callingUid) != null) { 23200 return false; 23201 } 23202 if (packageName == null || ks == null) { 23203 return false; 23204 } 23205 synchronized(mPackages) { 23206 final PackageParser.Package pkg = mPackages.get(packageName); 23207 if (pkg == null 23208 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23209 UserHandle.getUserId(callingUid))) { 23210 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23211 throw new IllegalArgumentException("Unknown package: " + packageName); 23212 } 23213 IBinder ksh = ks.getToken(); 23214 if (ksh instanceof KeySetHandle) { 23215 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23216 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 23217 } 23218 return false; 23219 } 23220 } 23221 23222 @Override 23223 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 23224 final int callingUid = Binder.getCallingUid(); 23225 if (getInstantAppPackageName(callingUid) != null) { 23226 return false; 23227 } 23228 if (packageName == null || ks == null) { 23229 return false; 23230 } 23231 synchronized(mPackages) { 23232 final PackageParser.Package pkg = mPackages.get(packageName); 23233 if (pkg == null 23234 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23235 UserHandle.getUserId(callingUid))) { 23236 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23237 throw new IllegalArgumentException("Unknown package: " + packageName); 23238 } 23239 IBinder ksh = ks.getToken(); 23240 if (ksh instanceof KeySetHandle) { 23241 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23242 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 23243 } 23244 return false; 23245 } 23246 } 23247 23248 private void deletePackageIfUnusedLPr(final String packageName) { 23249 PackageSetting ps = mSettings.mPackages.get(packageName); 23250 if (ps == null) { 23251 return; 23252 } 23253 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 23254 // TODO Implement atomic delete if package is unused 23255 // It is currently possible that the package will be deleted even if it is installed 23256 // after this method returns. 23257 mHandler.post(new Runnable() { 23258 public void run() { 23259 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23260 0, PackageManager.DELETE_ALL_USERS); 23261 } 23262 }); 23263 } 23264 } 23265 23266 /** 23267 * Check and throw if the given before/after packages would be considered a 23268 * downgrade. 23269 */ 23270 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 23271 throws PackageManagerException { 23272 if (after.getLongVersionCode() < before.getLongVersionCode()) { 23273 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23274 "Update version code " + after.versionCode + " is older than current " 23275 + before.getLongVersionCode()); 23276 } else if (after.getLongVersionCode() == before.getLongVersionCode()) { 23277 if (after.baseRevisionCode < before.baseRevisionCode) { 23278 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23279 "Update base revision code " + after.baseRevisionCode 23280 + " is older than current " + before.baseRevisionCode); 23281 } 23282 23283 if (!ArrayUtils.isEmpty(after.splitNames)) { 23284 for (int i = 0; i < after.splitNames.length; i++) { 23285 final String splitName = after.splitNames[i]; 23286 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 23287 if (j != -1) { 23288 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 23289 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23290 "Update split " + splitName + " revision code " 23291 + after.splitRevisionCodes[i] + " is older than current " 23292 + before.splitRevisionCodes[j]); 23293 } 23294 } 23295 } 23296 } 23297 } 23298 } 23299 23300 private static class MoveCallbacks extends Handler { 23301 private static final int MSG_CREATED = 1; 23302 private static final int MSG_STATUS_CHANGED = 2; 23303 23304 private final RemoteCallbackList<IPackageMoveObserver> 23305 mCallbacks = new RemoteCallbackList<>(); 23306 23307 private final SparseIntArray mLastStatus = new SparseIntArray(); 23308 23309 public MoveCallbacks(Looper looper) { 23310 super(looper); 23311 } 23312 23313 public void register(IPackageMoveObserver callback) { 23314 mCallbacks.register(callback); 23315 } 23316 23317 public void unregister(IPackageMoveObserver callback) { 23318 mCallbacks.unregister(callback); 23319 } 23320 23321 @Override 23322 public void handleMessage(Message msg) { 23323 final SomeArgs args = (SomeArgs) msg.obj; 23324 final int n = mCallbacks.beginBroadcast(); 23325 for (int i = 0; i < n; i++) { 23326 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 23327 try { 23328 invokeCallback(callback, msg.what, args); 23329 } catch (RemoteException ignored) { 23330 } 23331 } 23332 mCallbacks.finishBroadcast(); 23333 args.recycle(); 23334 } 23335 23336 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 23337 throws RemoteException { 23338 switch (what) { 23339 case MSG_CREATED: { 23340 callback.onCreated(args.argi1, (Bundle) args.arg2); 23341 break; 23342 } 23343 case MSG_STATUS_CHANGED: { 23344 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 23345 break; 23346 } 23347 } 23348 } 23349 23350 private void notifyCreated(int moveId, Bundle extras) { 23351 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 23352 23353 final SomeArgs args = SomeArgs.obtain(); 23354 args.argi1 = moveId; 23355 args.arg2 = extras; 23356 obtainMessage(MSG_CREATED, args).sendToTarget(); 23357 } 23358 23359 private void notifyStatusChanged(int moveId, int status) { 23360 notifyStatusChanged(moveId, status, -1); 23361 } 23362 23363 private void notifyStatusChanged(int moveId, int status, long estMillis) { 23364 Slog.v(TAG, "Move " + moveId + " status " + status); 23365 23366 final SomeArgs args = SomeArgs.obtain(); 23367 args.argi1 = moveId; 23368 args.argi2 = status; 23369 args.arg3 = estMillis; 23370 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 23371 23372 synchronized (mLastStatus) { 23373 mLastStatus.put(moveId, status); 23374 } 23375 } 23376 } 23377 23378 private final static class OnPermissionChangeListeners extends Handler { 23379 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 23380 23381 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 23382 new RemoteCallbackList<>(); 23383 23384 public OnPermissionChangeListeners(Looper looper) { 23385 super(looper); 23386 } 23387 23388 @Override 23389 public void handleMessage(Message msg) { 23390 switch (msg.what) { 23391 case MSG_ON_PERMISSIONS_CHANGED: { 23392 final int uid = msg.arg1; 23393 handleOnPermissionsChanged(uid); 23394 } break; 23395 } 23396 } 23397 23398 public void addListenerLocked(IOnPermissionsChangeListener listener) { 23399 mPermissionListeners.register(listener); 23400 23401 } 23402 23403 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 23404 mPermissionListeners.unregister(listener); 23405 } 23406 23407 public void onPermissionsChanged(int uid) { 23408 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 23409 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 23410 } 23411 } 23412 23413 private void handleOnPermissionsChanged(int uid) { 23414 final int count = mPermissionListeners.beginBroadcast(); 23415 try { 23416 for (int i = 0; i < count; i++) { 23417 IOnPermissionsChangeListener callback = mPermissionListeners 23418 .getBroadcastItem(i); 23419 try { 23420 callback.onPermissionsChanged(uid); 23421 } catch (RemoteException e) { 23422 Log.e(TAG, "Permission listener is dead", e); 23423 } 23424 } 23425 } finally { 23426 mPermissionListeners.finishBroadcast(); 23427 } 23428 } 23429 } 23430 23431 private class PackageManagerNative extends IPackageManagerNative.Stub { 23432 @Override 23433 public String[] getNamesForUids(int[] uids) throws RemoteException { 23434 final String[] results = PackageManagerService.this.getNamesForUids(uids); 23435 // massage results so they can be parsed by the native binder 23436 for (int i = results.length - 1; i >= 0; --i) { 23437 if (results[i] == null) { 23438 results[i] = ""; 23439 } 23440 } 23441 return results; 23442 } 23443 23444 // NB: this differentiates between preloads and sideloads 23445 @Override 23446 public String getInstallerForPackage(String packageName) throws RemoteException { 23447 final String installerName = getInstallerPackageName(packageName); 23448 if (!TextUtils.isEmpty(installerName)) { 23449 return installerName; 23450 } 23451 // differentiate between preload and sideload 23452 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23453 ApplicationInfo appInfo = getApplicationInfo(packageName, 23454 /*flags*/ 0, 23455 /*userId*/ callingUser); 23456 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 23457 return "preload"; 23458 } 23459 return ""; 23460 } 23461 23462 @Override 23463 public long getVersionCodeForPackage(String packageName) throws RemoteException { 23464 try { 23465 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23466 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 23467 if (pInfo != null) { 23468 return pInfo.getLongVersionCode(); 23469 } 23470 } catch (Exception e) { 23471 } 23472 return 0; 23473 } 23474 } 23475 23476 private class PackageManagerInternalImpl extends PackageManagerInternal { 23477 @Override 23478 public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask, 23479 int flagValues, int userId) { 23480 PackageManagerService.this.updatePermissionFlags( 23481 permName, packageName, flagMask, flagValues, userId); 23482 } 23483 23484 @Override 23485 public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) { 23486 SigningDetails sd = getSigningDetails(packageName); 23487 if (sd == null) { 23488 return false; 23489 } 23490 return sd.hasSha256Certificate(restoringFromSigHash, 23491 SigningDetails.CertCapabilities.INSTALLED_DATA); 23492 } 23493 23494 @Override 23495 public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) { 23496 SigningDetails sd = getSigningDetails(packageName); 23497 if (sd == null) { 23498 return false; 23499 } 23500 return sd.hasCertificate(restoringFromSig, 23501 SigningDetails.CertCapabilities.INSTALLED_DATA); 23502 } 23503 23504 private SigningDetails getSigningDetails(@NonNull String packageName) { 23505 synchronized (mPackages) { 23506 PackageParser.Package p = mPackages.get(packageName); 23507 if (p == null) { 23508 return null; 23509 } 23510 return p.mSigningDetails; 23511 } 23512 } 23513 23514 @Override 23515 public int getPermissionFlagsTEMP(String permName, String packageName, int userId) { 23516 return PackageManagerService.this.getPermissionFlags(permName, packageName, userId); 23517 } 23518 23519 @Override 23520 public boolean isInstantApp(String packageName, int userId) { 23521 return PackageManagerService.this.isInstantApp(packageName, userId); 23522 } 23523 23524 @Override 23525 public String getInstantAppPackageName(int uid) { 23526 return PackageManagerService.this.getInstantAppPackageName(uid); 23527 } 23528 23529 @Override 23530 public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) { 23531 synchronized (mPackages) { 23532 return PackageManagerService.this.filterAppAccessLPr( 23533 (PackageSetting) pkg.mExtras, callingUid, userId); 23534 } 23535 } 23536 23537 @Override 23538 public PackageParser.Package getPackage(String packageName) { 23539 synchronized (mPackages) { 23540 packageName = resolveInternalPackageNameLPr( 23541 packageName, PackageManager.VERSION_CODE_HIGHEST); 23542 return mPackages.get(packageName); 23543 } 23544 } 23545 23546 @Override 23547 public PackageList getPackageList(PackageListObserver observer) { 23548 synchronized (mPackages) { 23549 final int N = mPackages.size(); 23550 final ArrayList<String> list = new ArrayList<>(N); 23551 for (int i = 0; i < N; i++) { 23552 list.add(mPackages.keyAt(i)); 23553 } 23554 final PackageList packageList = new PackageList(list, observer); 23555 if (observer != null) { 23556 mPackageListObservers.add(packageList); 23557 } 23558 return packageList; 23559 } 23560 } 23561 23562 @Override 23563 public void removePackageListObserver(PackageListObserver observer) { 23564 synchronized (mPackages) { 23565 mPackageListObservers.remove(observer); 23566 } 23567 } 23568 23569 @Override 23570 public PackageParser.Package getDisabledPackage(String packageName) { 23571 synchronized (mPackages) { 23572 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 23573 return (ps != null) ? ps.pkg : null; 23574 } 23575 } 23576 23577 @Override 23578 public String getKnownPackageName(int knownPackage, int userId) { 23579 switch(knownPackage) { 23580 case PackageManagerInternal.PACKAGE_BROWSER: 23581 return getDefaultBrowserPackageName(userId); 23582 case PackageManagerInternal.PACKAGE_INSTALLER: 23583 return mRequiredInstallerPackage; 23584 case PackageManagerInternal.PACKAGE_SETUP_WIZARD: 23585 return mSetupWizardPackage; 23586 case PackageManagerInternal.PACKAGE_SYSTEM: 23587 return "android"; 23588 case PackageManagerInternal.PACKAGE_VERIFIER: 23589 return mRequiredVerifierPackage; 23590 case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER: 23591 return mSystemTextClassifierPackage; 23592 } 23593 return null; 23594 } 23595 23596 @Override 23597 public boolean isResolveActivityComponent(ComponentInfo component) { 23598 return mResolveActivity.packageName.equals(component.packageName) 23599 && mResolveActivity.name.equals(component.name); 23600 } 23601 23602 @Override 23603 public void setLocationPackagesProvider(PackagesProvider provider) { 23604 mDefaultPermissionPolicy.setLocationPackagesProvider(provider); 23605 } 23606 23607 @Override 23608 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23609 mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider); 23610 } 23611 23612 @Override 23613 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23614 mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider); 23615 } 23616 23617 @Override 23618 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23619 mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider); 23620 } 23621 23622 @Override 23623 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23624 mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider); 23625 } 23626 23627 @Override 23628 public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) { 23629 mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider); 23630 } 23631 23632 @Override 23633 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23634 mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider); 23635 } 23636 23637 @Override 23638 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23639 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId); 23640 } 23641 23642 @Override 23643 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23644 synchronized (mPackages) { 23645 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23646 } 23647 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId); 23648 } 23649 23650 @Override 23651 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23652 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager( 23653 packageName, userId); 23654 } 23655 23656 @Override 23657 public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) { 23658 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp( 23659 packageName, userId); 23660 } 23661 23662 @Override 23663 public void setKeepUninstalledPackages(final List<String> packageList) { 23664 Preconditions.checkNotNull(packageList); 23665 List<String> removedFromList = null; 23666 synchronized (mPackages) { 23667 if (mKeepUninstalledPackages != null) { 23668 final int packagesCount = mKeepUninstalledPackages.size(); 23669 for (int i = 0; i < packagesCount; i++) { 23670 String oldPackage = mKeepUninstalledPackages.get(i); 23671 if (packageList != null && packageList.contains(oldPackage)) { 23672 continue; 23673 } 23674 if (removedFromList == null) { 23675 removedFromList = new ArrayList<>(); 23676 } 23677 removedFromList.add(oldPackage); 23678 } 23679 } 23680 mKeepUninstalledPackages = new ArrayList<>(packageList); 23681 if (removedFromList != null) { 23682 final int removedCount = removedFromList.size(); 23683 for (int i = 0; i < removedCount; i++) { 23684 deletePackageIfUnusedLPr(removedFromList.get(i)); 23685 } 23686 } 23687 } 23688 } 23689 23690 @Override 23691 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23692 synchronized (mPackages) { 23693 return mPermissionManager.isPermissionsReviewRequired( 23694 mPackages.get(packageName), userId); 23695 } 23696 } 23697 23698 @Override 23699 public PackageInfo getPackageInfo( 23700 String packageName, int flags, int filterCallingUid, int userId) { 23701 return PackageManagerService.this 23702 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 23703 flags, filterCallingUid, userId); 23704 } 23705 23706 @Override 23707 public int getPackageUid(String packageName, int flags, int userId) { 23708 return PackageManagerService.this 23709 .getPackageUid(packageName, flags, userId); 23710 } 23711 23712 @Override 23713 public ApplicationInfo getApplicationInfo( 23714 String packageName, int flags, int filterCallingUid, int userId) { 23715 return PackageManagerService.this 23716 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 23717 } 23718 23719 @Override 23720 public ActivityInfo getActivityInfo( 23721 ComponentName component, int flags, int filterCallingUid, int userId) { 23722 return PackageManagerService.this 23723 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 23724 } 23725 23726 @Override 23727 public List<ResolveInfo> queryIntentActivities( 23728 Intent intent, int flags, int filterCallingUid, int userId) { 23729 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23730 return PackageManagerService.this 23731 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 23732 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 23733 } 23734 23735 @Override 23736 public List<ResolveInfo> queryIntentServices( 23737 Intent intent, int flags, int callingUid, int userId) { 23738 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23739 return PackageManagerService.this 23740 .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid, 23741 false); 23742 } 23743 23744 @Override 23745 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23746 int userId) { 23747 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23748 } 23749 23750 @Override 23751 public ComponentName getDefaultHomeActivity(int userId) { 23752 return PackageManagerService.this.getDefaultHomeActivity(userId); 23753 } 23754 23755 @Override 23756 public void setDeviceAndProfileOwnerPackages( 23757 int deviceOwnerUserId, String deviceOwnerPackage, 23758 SparseArray<String> profileOwnerPackages) { 23759 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23760 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23761 } 23762 23763 @Override 23764 public boolean isPackageDataProtected(int userId, String packageName) { 23765 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23766 } 23767 23768 @Override 23769 public boolean isPackageEphemeral(int userId, String packageName) { 23770 synchronized (mPackages) { 23771 final PackageSetting ps = mSettings.mPackages.get(packageName); 23772 return ps != null ? ps.getInstantApp(userId) : false; 23773 } 23774 } 23775 23776 @Override 23777 public boolean wasPackageEverLaunched(String packageName, int userId) { 23778 synchronized (mPackages) { 23779 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23780 } 23781 } 23782 23783 @Override 23784 public void grantRuntimePermission(String packageName, String permName, int userId, 23785 boolean overridePolicy) { 23786 PackageManagerService.this.mPermissionManager.grantRuntimePermission( 23787 permName, packageName, overridePolicy, getCallingUid(), userId, 23788 mPermissionCallback); 23789 } 23790 23791 @Override 23792 public void revokeRuntimePermission(String packageName, String permName, int userId, 23793 boolean overridePolicy) { 23794 mPermissionManager.revokeRuntimePermission( 23795 permName, packageName, overridePolicy, getCallingUid(), userId, 23796 mPermissionCallback); 23797 } 23798 23799 @Override 23800 public String getNameForUid(int uid) { 23801 return PackageManagerService.this.getNameForUid(uid); 23802 } 23803 23804 @Override 23805 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23806 Intent origIntent, String resolvedType, String callingPackage, 23807 Bundle verificationBundle, int userId) { 23808 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23809 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 23810 userId); 23811 } 23812 23813 @Override 23814 public void grantEphemeralAccess(int userId, Intent intent, 23815 int targetAppId, int ephemeralAppId) { 23816 synchronized (mPackages) { 23817 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23818 targetAppId, ephemeralAppId); 23819 } 23820 } 23821 23822 @Override 23823 public boolean isInstantAppInstallerComponent(ComponentName component) { 23824 synchronized (mPackages) { 23825 return mInstantAppInstallerActivity != null 23826 && mInstantAppInstallerActivity.getComponentName().equals(component); 23827 } 23828 } 23829 23830 @Override 23831 public void pruneInstantApps() { 23832 mInstantAppRegistry.pruneInstantApps(); 23833 } 23834 23835 @Override 23836 public String getSetupWizardPackageName() { 23837 return mSetupWizardPackage; 23838 } 23839 23840 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23841 if (policy != null) { 23842 mExternalSourcesPolicy = policy; 23843 } 23844 } 23845 23846 @Override 23847 public boolean isPackagePersistent(String packageName) { 23848 synchronized (mPackages) { 23849 PackageParser.Package pkg = mPackages.get(packageName); 23850 return pkg != null 23851 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23852 | ApplicationInfo.FLAG_PERSISTENT)) == 23853 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23854 : false; 23855 } 23856 } 23857 23858 @Override 23859 public boolean isLegacySystemApp(Package pkg) { 23860 synchronized (mPackages) { 23861 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23862 return mPromoteSystemApps 23863 && ps.isSystem() 23864 && mExistingSystemPackages.contains(ps.name); 23865 } 23866 } 23867 23868 @Override 23869 public List<PackageInfo> getOverlayPackages(int userId) { 23870 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23871 synchronized (mPackages) { 23872 for (PackageParser.Package p : mPackages.values()) { 23873 if (p.mOverlayTarget != null) { 23874 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23875 if (pkg != null) { 23876 overlayPackages.add(pkg); 23877 } 23878 } 23879 } 23880 } 23881 return overlayPackages; 23882 } 23883 23884 @Override 23885 public List<String> getTargetPackageNames(int userId) { 23886 List<String> targetPackages = new ArrayList<>(); 23887 synchronized (mPackages) { 23888 for (PackageParser.Package p : mPackages.values()) { 23889 if (p.mOverlayTarget == null) { 23890 targetPackages.add(p.packageName); 23891 } 23892 } 23893 } 23894 return targetPackages; 23895 } 23896 23897 @Override 23898 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23899 @Nullable List<String> overlayPackageNames) { 23900 synchronized (mPackages) { 23901 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23902 Slog.e(TAG, "failed to find package " + targetPackageName); 23903 return false; 23904 } 23905 ArrayList<String> overlayPaths = null; 23906 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 23907 final int N = overlayPackageNames.size(); 23908 overlayPaths = new ArrayList<>(N); 23909 for (int i = 0; i < N; i++) { 23910 final String packageName = overlayPackageNames.get(i); 23911 final PackageParser.Package pkg = mPackages.get(packageName); 23912 if (pkg == null) { 23913 Slog.e(TAG, "failed to find package " + packageName); 23914 return false; 23915 } 23916 overlayPaths.add(pkg.baseCodePath); 23917 } 23918 } 23919 23920 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 23921 ps.setOverlayPaths(overlayPaths, userId); 23922 return true; 23923 } 23924 } 23925 23926 @Override 23927 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23928 int flags, int userId, boolean resolveForStart) { 23929 return resolveIntentInternal( 23930 intent, resolvedType, flags, userId, resolveForStart); 23931 } 23932 23933 @Override 23934 public ResolveInfo resolveService(Intent intent, String resolvedType, 23935 int flags, int userId, int callingUid) { 23936 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 23937 } 23938 23939 @Override 23940 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 23941 return PackageManagerService.this.resolveContentProviderInternal( 23942 name, flags, userId); 23943 } 23944 23945 @Override 23946 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23947 synchronized (mPackages) { 23948 mIsolatedOwners.put(isolatedUid, ownerUid); 23949 } 23950 } 23951 23952 @Override 23953 public void removeIsolatedUid(int isolatedUid) { 23954 synchronized (mPackages) { 23955 mIsolatedOwners.delete(isolatedUid); 23956 } 23957 } 23958 23959 @Override 23960 public int getUidTargetSdkVersion(int uid) { 23961 synchronized (mPackages) { 23962 return getUidTargetSdkVersionLockedLPr(uid); 23963 } 23964 } 23965 23966 @Override 23967 public int getPackageTargetSdkVersion(String packageName) { 23968 synchronized (mPackages) { 23969 return getPackageTargetSdkVersionLockedLPr(packageName); 23970 } 23971 } 23972 23973 @Override 23974 public boolean canAccessInstantApps(int callingUid, int userId) { 23975 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 23976 } 23977 23978 @Override 23979 public boolean canAccessComponent(int callingUid, ComponentName component, int userId) { 23980 synchronized (mPackages) { 23981 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 23982 return !PackageManagerService.this.filterAppAccessLPr( 23983 ps, callingUid, component, TYPE_UNKNOWN, userId); 23984 } 23985 } 23986 23987 @Override 23988 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 23989 synchronized (mPackages) { 23990 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 23991 } 23992 } 23993 23994 @Override 23995 public void notifyPackageUse(String packageName, int reason) { 23996 synchronized (mPackages) { 23997 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 23998 } 23999 } 24000 } 24001 24002 @Override 24003 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 24004 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 24005 synchronized (mPackages) { 24006 final long identity = Binder.clearCallingIdentity(); 24007 try { 24008 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps( 24009 packageNames, userId); 24010 } finally { 24011 Binder.restoreCallingIdentity(identity); 24012 } 24013 } 24014 } 24015 24016 @Override 24017 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 24018 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 24019 synchronized (mPackages) { 24020 final long identity = Binder.clearCallingIdentity(); 24021 try { 24022 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices( 24023 packageNames, userId); 24024 } finally { 24025 Binder.restoreCallingIdentity(identity); 24026 } 24027 } 24028 } 24029 24030 @Override 24031 public void grantDefaultPermissionsToEnabledTelephonyDataServices( 24032 String[] packageNames, int userId) { 24033 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices"); 24034 synchronized (mPackages) { 24035 Binder.withCleanCallingIdentity( () -> { 24036 mDefaultPermissionPolicy. 24037 grantDefaultPermissionsToEnabledTelephonyDataServices( 24038 packageNames, userId); 24039 }); 24040 } 24041 } 24042 24043 @Override 24044 public void revokeDefaultPermissionsFromDisabledTelephonyDataServices( 24045 String[] packageNames, int userId) { 24046 enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices"); 24047 synchronized (mPackages) { 24048 Binder.withCleanCallingIdentity( () -> { 24049 mDefaultPermissionPolicy. 24050 revokeDefaultPermissionsFromDisabledTelephonyDataServices( 24051 packageNames, userId); 24052 }); 24053 } 24054 } 24055 24056 private static void enforceSystemOrPhoneCaller(String tag) { 24057 int callingUid = Binder.getCallingUid(); 24058 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 24059 throw new SecurityException( 24060 "Cannot call " + tag + " from UID " + callingUid); 24061 } 24062 } 24063 24064 boolean isHistoricalPackageUsageAvailable() { 24065 return mPackageUsage.isHistoricalPackageUsageAvailable(); 24066 } 24067 24068 /** 24069 * Return a <b>copy</b> of the collection of packages known to the package manager. 24070 * @return A copy of the values of mPackages. 24071 */ 24072 Collection<PackageParser.Package> getPackages() { 24073 synchronized (mPackages) { 24074 return new ArrayList<>(mPackages.values()); 24075 } 24076 } 24077 24078 /** 24079 * Logs process start information (including base APK hash) to the security log. 24080 * @hide 24081 */ 24082 @Override 24083 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 24084 String apkFile, int pid) { 24085 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 24086 return; 24087 } 24088 if (!SecurityLog.isLoggingEnabled()) { 24089 return; 24090 } 24091 Bundle data = new Bundle(); 24092 data.putLong("startTimestamp", System.currentTimeMillis()); 24093 data.putString("processName", processName); 24094 data.putInt("uid", uid); 24095 data.putString("seinfo", seinfo); 24096 data.putString("apkFile", apkFile); 24097 data.putInt("pid", pid); 24098 Message msg = mProcessLoggingHandler.obtainMessage( 24099 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 24100 msg.setData(data); 24101 mProcessLoggingHandler.sendMessage(msg); 24102 } 24103 24104 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 24105 return mCompilerStats.getPackageStats(pkgName); 24106 } 24107 24108 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 24109 return getOrCreateCompilerPackageStats(pkg.packageName); 24110 } 24111 24112 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 24113 return mCompilerStats.getOrCreatePackageStats(pkgName); 24114 } 24115 24116 public void deleteCompilerPackageStats(String pkgName) { 24117 mCompilerStats.deletePackageStats(pkgName); 24118 } 24119 24120 @Override 24121 public int getInstallReason(String packageName, int userId) { 24122 final int callingUid = Binder.getCallingUid(); 24123 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24124 true /* requireFullPermission */, false /* checkShell */, 24125 "get install reason"); 24126 synchronized (mPackages) { 24127 final PackageSetting ps = mSettings.mPackages.get(packageName); 24128 if (filterAppAccessLPr(ps, callingUid, userId)) { 24129 return PackageManager.INSTALL_REASON_UNKNOWN; 24130 } 24131 if (ps != null) { 24132 return ps.getInstallReason(userId); 24133 } 24134 } 24135 return PackageManager.INSTALL_REASON_UNKNOWN; 24136 } 24137 24138 @Override 24139 public boolean canRequestPackageInstalls(String packageName, int userId) { 24140 return canRequestPackageInstallsInternal(packageName, 0, userId, 24141 true /* throwIfPermNotDeclared*/); 24142 } 24143 24144 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 24145 boolean throwIfPermNotDeclared) { 24146 int callingUid = Binder.getCallingUid(); 24147 int uid = getPackageUid(packageName, 0, userId); 24148 if (callingUid != uid && callingUid != Process.ROOT_UID 24149 && callingUid != Process.SYSTEM_UID) { 24150 throw new SecurityException( 24151 "Caller uid " + callingUid + " does not own package " + packageName); 24152 } 24153 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 24154 if (info == null) { 24155 return false; 24156 } 24157 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 24158 return false; 24159 } 24160 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 24161 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 24162 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 24163 if (throwIfPermNotDeclared) { 24164 throw new SecurityException("Need to declare " + appOpPermission 24165 + " to call this api"); 24166 } else { 24167 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 24168 return false; 24169 } 24170 } 24171 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 24172 return false; 24173 } 24174 if (mExternalSourcesPolicy != null) { 24175 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 24176 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 24177 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 24178 } 24179 } 24180 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 24181 } 24182 24183 @Override 24184 public ComponentName getInstantAppResolverSettingsComponent() { 24185 return mInstantAppResolverSettingsComponent; 24186 } 24187 24188 @Override 24189 public ComponentName getInstantAppInstallerComponent() { 24190 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 24191 return null; 24192 } 24193 return mInstantAppInstallerActivity == null 24194 ? null : mInstantAppInstallerActivity.getComponentName(); 24195 } 24196 24197 @Override 24198 public String getInstantAppAndroidId(String packageName, int userId) { 24199 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 24200 "getInstantAppAndroidId"); 24201 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 24202 true /* requireFullPermission */, false /* checkShell */, 24203 "getInstantAppAndroidId"); 24204 // Make sure the target is an Instant App. 24205 if (!isInstantApp(packageName, userId)) { 24206 return null; 24207 } 24208 synchronized (mPackages) { 24209 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 24210 } 24211 } 24212 24213 boolean canHaveOatDir(String packageName) { 24214 synchronized (mPackages) { 24215 PackageParser.Package p = mPackages.get(packageName); 24216 if (p == null) { 24217 return false; 24218 } 24219 return p.canHaveOatDir(); 24220 } 24221 } 24222 24223 private String getOatDir(PackageParser.Package pkg) { 24224 if (!pkg.canHaveOatDir()) { 24225 return null; 24226 } 24227 File codePath = new File(pkg.codePath); 24228 if (codePath.isDirectory()) { 24229 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 24230 } 24231 return null; 24232 } 24233 24234 void deleteOatArtifactsOfPackage(String packageName) { 24235 final String[] instructionSets; 24236 final List<String> codePaths; 24237 final String oatDir; 24238 final PackageParser.Package pkg; 24239 synchronized (mPackages) { 24240 pkg = mPackages.get(packageName); 24241 } 24242 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 24243 codePaths = pkg.getAllCodePaths(); 24244 oatDir = getOatDir(pkg); 24245 24246 for (String codePath : codePaths) { 24247 for (String isa : instructionSets) { 24248 try { 24249 mInstaller.deleteOdex(codePath, isa, oatDir); 24250 } catch (InstallerException e) { 24251 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 24252 } 24253 } 24254 } 24255 } 24256 24257 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 24258 Set<String> unusedPackages = new HashSet<>(); 24259 long currentTimeInMillis = System.currentTimeMillis(); 24260 synchronized (mPackages) { 24261 for (PackageParser.Package pkg : mPackages.values()) { 24262 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 24263 if (ps == null) { 24264 continue; 24265 } 24266 PackageDexUsage.PackageUseInfo packageUseInfo = 24267 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 24268 if (PackageManagerServiceUtils 24269 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 24270 downgradeTimeThresholdMillis, packageUseInfo, 24271 pkg.getLatestPackageUseTimeInMills(), 24272 pkg.getLatestForegroundPackageUseTimeInMills())) { 24273 unusedPackages.add(pkg.packageName); 24274 } 24275 } 24276 } 24277 return unusedPackages; 24278 } 24279 24280 @Override 24281 public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning, 24282 int userId) { 24283 final int callingUid = Binder.getCallingUid(); 24284 final int callingAppId = UserHandle.getAppId(callingUid); 24285 24286 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24287 true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo"); 24288 24289 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24290 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24291 throw new SecurityException("Caller must have the " 24292 + SET_HARMFUL_APP_WARNINGS + " permission."); 24293 } 24294 24295 synchronized(mPackages) { 24296 mSettings.setHarmfulAppWarningLPw(packageName, warning, userId); 24297 scheduleWritePackageRestrictionsLocked(userId); 24298 } 24299 } 24300 24301 @Nullable 24302 @Override 24303 public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) { 24304 final int callingUid = Binder.getCallingUid(); 24305 final int callingAppId = UserHandle.getAppId(callingUid); 24306 24307 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24308 true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo"); 24309 24310 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24311 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24312 throw new SecurityException("Caller must have the " 24313 + SET_HARMFUL_APP_WARNINGS + " permission."); 24314 } 24315 24316 synchronized(mPackages) { 24317 return mSettings.getHarmfulAppWarningLPr(packageName, userId); 24318 } 24319 } 24320 24321 @Override 24322 public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) { 24323 final int callingUid = Binder.getCallingUid(); 24324 final int callingAppId = UserHandle.getAppId(callingUid); 24325 24326 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24327 false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected"); 24328 24329 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID 24330 && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) { 24331 throw new SecurityException("Caller must have the " 24332 + MANAGE_DEVICE_ADMINS + " permission."); 24333 } 24334 24335 return mProtectedPackages.isPackageStateProtected(userId, packageName); 24336 } 24337} 24338 24339interface PackageSender { 24340 /** 24341 * @param userIds User IDs where the action occurred on a full application 24342 * @param instantUserIds User IDs where the action occurred on an instant application 24343 */ 24344 void sendPackageBroadcast(final String action, final String pkg, 24345 final Bundle extras, final int flags, final String targetPkg, 24346 final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds); 24347 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 24348 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds); 24349 void notifyPackageAdded(String packageName); 24350 void notifyPackageRemoved(String packageName); 24351} 24352