PackageManagerService.java revision 55f1499592ba632a0166b415a4aa7bf1d33a9c96
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.SET_HARMFUL_APP_WARNINGS; 21import static android.Manifest.permission.INSTALL_PACKAGES; 22import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS; 23import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 24import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 25import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 26import static android.Manifest.permission.WRITE_MEDIA_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_SANDBOX_VERSION_DOWNGRADE; 56import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 57import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 58import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 59import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 60import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 61import static android.content.pm.PackageManager.INSTALL_INTERNAL; 62import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 66import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 67import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 68import static android.content.pm.PackageManager.MATCH_ALL; 69import static android.content.pm.PackageManager.MATCH_ANY_USER; 70import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 71import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 72import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 73import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 74import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 75import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 76import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 77import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 78import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 79import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 80import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 81import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 82import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER; 83import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 84import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 85import static android.content.pm.PackageManager.PERMISSION_DENIED; 86import static android.content.pm.PackageManager.PERMISSION_GRANTED; 87import static android.content.pm.PackageParser.isApkFile; 88import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 89import static android.os.storage.StorageManager.FLAG_STORAGE_CE; 90import static android.os.storage.StorageManager.FLAG_STORAGE_DE; 91import static android.system.OsConstants.O_CREAT; 92import static android.system.OsConstants.O_RDWR; 93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 95import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 96import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 97import static com.android.internal.util.ArrayUtils.appendInt; 98import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 101import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 102import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 105import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures; 106import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists; 107import static com.android.server.pm.PackageManagerServiceUtils.decompressFile; 108import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride; 109import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo; 110import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles; 111import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime; 112import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo; 113import static com.android.server.pm.PackageManagerServiceUtils.signingDetailsHasCertificate; 114import static com.android.server.pm.PackageManagerServiceUtils.signingDetailsHasSha256Certificate; 115import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures; 116import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE; 117import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS; 118import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 119 120import android.Manifest; 121import android.annotation.IntDef; 122import android.annotation.NonNull; 123import android.annotation.Nullable; 124import android.app.ActivityManager; 125import android.app.ActivityManagerInternal; 126import android.app.AppOpsManager; 127import android.app.IActivityManager; 128import android.app.ResourcesManager; 129import android.app.admin.IDevicePolicyManager; 130import android.app.admin.SecurityLog; 131import android.app.backup.IBackupManager; 132import android.content.BroadcastReceiver; 133import android.content.ComponentName; 134import android.content.ContentResolver; 135import android.content.Context; 136import android.content.IIntentReceiver; 137import android.content.Intent; 138import android.content.IntentFilter; 139import android.content.IntentSender; 140import android.content.IntentSender.SendIntentException; 141import android.content.ServiceConnection; 142import android.content.pm.ActivityInfo; 143import android.content.pm.ApplicationInfo; 144import android.content.pm.AppsQueryHelper; 145import android.content.pm.AuxiliaryResolveInfo; 146import android.content.pm.ChangedPackages; 147import android.content.pm.ComponentInfo; 148import android.content.pm.FallbackCategoryProvider; 149import android.content.pm.FeatureInfo; 150import android.content.pm.IDexModuleRegisterCallback; 151import android.content.pm.IOnPermissionsChangeListener; 152import android.content.pm.IPackageDataObserver; 153import android.content.pm.IPackageDeleteObserver; 154import android.content.pm.IPackageDeleteObserver2; 155import android.content.pm.IPackageInstallObserver2; 156import android.content.pm.IPackageInstaller; 157import android.content.pm.IPackageManager; 158import android.content.pm.IPackageManagerNative; 159import android.content.pm.IPackageMoveObserver; 160import android.content.pm.IPackageStatsObserver; 161import android.content.pm.InstantAppInfo; 162import android.content.pm.InstantAppRequest; 163import android.content.pm.InstantAppResolveInfo; 164import android.content.pm.InstrumentationInfo; 165import android.content.pm.IntentFilterVerificationInfo; 166import android.content.pm.KeySet; 167import android.content.pm.PackageCleanItem; 168import android.content.pm.PackageInfo; 169import android.content.pm.PackageInfoLite; 170import android.content.pm.PackageInstaller; 171import android.content.pm.PackageList; 172import android.content.pm.PackageManager; 173import android.content.pm.PackageManagerInternal; 174import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 175import android.content.pm.PackageManagerInternal.PackageListObserver; 176import android.content.pm.PackageParser; 177import android.content.pm.PackageParser.ActivityIntentInfo; 178import android.content.pm.PackageParser.Package; 179import android.content.pm.PackageParser.PackageLite; 180import android.content.pm.PackageParser.PackageParserException; 181import android.content.pm.PackageParser.ParseFlags; 182import android.content.pm.PackageParser.ServiceIntentInfo; 183import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion; 184import android.content.pm.PackageStats; 185import android.content.pm.PackageUserState; 186import android.content.pm.ParceledListSlice; 187import android.content.pm.PermissionGroupInfo; 188import android.content.pm.PermissionInfo; 189import android.content.pm.ProviderInfo; 190import android.content.pm.ResolveInfo; 191import android.content.pm.ServiceInfo; 192import android.content.pm.SharedLibraryInfo; 193import android.content.pm.Signature; 194import android.content.pm.UserInfo; 195import android.content.pm.VerifierDeviceIdentity; 196import android.content.pm.VerifierInfo; 197import android.content.pm.VersionedPackage; 198import android.content.pm.dex.DexMetadataHelper; 199import android.content.pm.dex.IArtManager; 200import android.content.res.Resources; 201import android.database.ContentObserver; 202import android.graphics.Bitmap; 203import android.hardware.display.DisplayManager; 204import android.net.Uri; 205import android.os.Binder; 206import android.os.Build; 207import android.os.Bundle; 208import android.os.Debug; 209import android.os.Environment; 210import android.os.Environment.UserEnvironment; 211import android.os.FileUtils; 212import android.os.Handler; 213import android.os.IBinder; 214import android.os.Looper; 215import android.os.Message; 216import android.os.Parcel; 217import android.os.ParcelFileDescriptor; 218import android.os.PatternMatcher; 219import android.os.Process; 220import android.os.RemoteCallbackList; 221import android.os.RemoteException; 222import android.os.ResultReceiver; 223import android.os.SELinux; 224import android.os.ServiceManager; 225import android.os.ShellCallback; 226import android.os.SystemClock; 227import android.os.SystemProperties; 228import android.os.Trace; 229import android.os.UserHandle; 230import android.os.UserManager; 231import android.os.UserManagerInternal; 232import android.os.storage.IStorageManager; 233import android.os.storage.StorageEventListener; 234import android.os.storage.StorageManager; 235import android.os.storage.StorageManagerInternal; 236import android.os.storage.VolumeInfo; 237import android.os.storage.VolumeRecord; 238import android.provider.Settings.Global; 239import android.provider.Settings.Secure; 240import android.security.KeyStore; 241import android.security.SystemKeyStore; 242import android.service.pm.PackageServiceDumpProto; 243import android.system.ErrnoException; 244import android.system.Os; 245import android.text.TextUtils; 246import android.text.format.DateUtils; 247import android.util.ArrayMap; 248import android.util.ArraySet; 249import android.util.Base64; 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.DigestInputStream; 343import java.security.MessageDigest; 344import java.security.NoSuchAlgorithmException; 345import java.security.PublicKey; 346import java.security.SecureRandom; 347import java.security.cert.CertificateException; 348import java.util.ArrayList; 349import java.util.Arrays; 350import java.util.Collection; 351import java.util.Collections; 352import java.util.Comparator; 353import java.util.HashMap; 354import java.util.HashSet; 355import java.util.Iterator; 356import java.util.LinkedHashSet; 357import java.util.List; 358import java.util.Map; 359import java.util.Objects; 360import java.util.Set; 361import java.util.concurrent.CountDownLatch; 362import java.util.concurrent.Future; 363import java.util.concurrent.TimeUnit; 364import java.util.concurrent.atomic.AtomicBoolean; 365import java.util.concurrent.atomic.AtomicInteger; 366 367/** 368 * Keep track of all those APKs everywhere. 369 * <p> 370 * Internally there are two important locks: 371 * <ul> 372 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 373 * and other related state. It is a fine-grained lock that should only be held 374 * momentarily, as it's one of the most contended locks in the system. 375 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 376 * operations typically involve heavy lifting of application data on disk. Since 377 * {@code installd} is single-threaded, and it's operations can often be slow, 378 * this lock should never be acquired while already holding {@link #mPackages}. 379 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 380 * holding {@link #mInstallLock}. 381 * </ul> 382 * Many internal methods rely on the caller to hold the appropriate locks, and 383 * this contract is expressed through method name suffixes: 384 * <ul> 385 * <li>fooLI(): the caller must hold {@link #mInstallLock} 386 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 387 * being modified must be frozen 388 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 389 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 390 * </ul> 391 * <p> 392 * Because this class is very central to the platform's security; please run all 393 * CTS and unit tests whenever making modifications: 394 * 395 * <pre> 396 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 397 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 398 * </pre> 399 */ 400public class PackageManagerService extends IPackageManager.Stub 401 implements PackageSender { 402 static final String TAG = "PackageManager"; 403 public static final boolean DEBUG_SETTINGS = false; 404 static final boolean DEBUG_PREFERRED = false; 405 static final boolean DEBUG_UPGRADE = false; 406 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 407 private static final boolean DEBUG_BACKUP = false; 408 public static final boolean DEBUG_INSTALL = false; 409 public static final boolean DEBUG_REMOVE = false; 410 private static final boolean DEBUG_BROADCASTS = false; 411 private static final boolean DEBUG_SHOW_INFO = false; 412 private static final boolean DEBUG_PACKAGE_INFO = false; 413 private static final boolean DEBUG_INTENT_MATCHING = false; 414 public static final boolean DEBUG_PACKAGE_SCANNING = false; 415 private static final boolean DEBUG_VERIFY = false; 416 private static final boolean DEBUG_FILTERS = false; 417 public static final boolean DEBUG_PERMISSIONS = false; 418 private static final boolean DEBUG_SHARED_LIBRARIES = false; 419 public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE; 420 421 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 422 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 423 // user, but by default initialize to this. 424 public static final boolean DEBUG_DEXOPT = false; 425 426 private static final boolean DEBUG_ABI_SELECTION = false; 427 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 428 private static final boolean DEBUG_TRIAGED_MISSING = false; 429 private static final boolean DEBUG_APP_DATA = false; 430 431 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 432 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 433 434 private static final boolean HIDE_EPHEMERAL_APIS = false; 435 436 private static final boolean ENABLE_FREE_CACHE_V2 = 437 SystemProperties.getBoolean("fw.free_cache_v2", true); 438 439 private static final int RADIO_UID = Process.PHONE_UID; 440 private static final int LOG_UID = Process.LOG_UID; 441 private static final int NFC_UID = Process.NFC_UID; 442 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 443 private static final int SHELL_UID = Process.SHELL_UID; 444 445 // Suffix used during package installation when copying/moving 446 // package apks to install directory. 447 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 448 449 static final int SCAN_NO_DEX = 1<<0; 450 static final int SCAN_UPDATE_SIGNATURE = 1<<1; 451 static final int SCAN_NEW_INSTALL = 1<<2; 452 static final int SCAN_UPDATE_TIME = 1<<3; 453 static final int SCAN_BOOTING = 1<<4; 454 static final int SCAN_TRUSTED_OVERLAY = 1<<5; 455 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6; 456 static final int SCAN_REQUIRE_KNOWN = 1<<7; 457 static final int SCAN_MOVE = 1<<8; 458 static final int SCAN_INITIAL = 1<<9; 459 static final int SCAN_CHECK_ONLY = 1<<10; 460 static final int SCAN_DONT_KILL_APP = 1<<11; 461 static final int SCAN_IGNORE_FROZEN = 1<<12; 462 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13; 463 static final int SCAN_AS_INSTANT_APP = 1<<14; 464 static final int SCAN_AS_FULL_APP = 1<<15; 465 static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16; 466 static final int SCAN_AS_SYSTEM = 1<<17; 467 static final int SCAN_AS_PRIVILEGED = 1<<18; 468 static final int SCAN_AS_OEM = 1<<19; 469 static final int SCAN_AS_VENDOR = 1<<20; 470 471 @IntDef(flag = true, prefix = { "SCAN_" }, value = { 472 SCAN_NO_DEX, 473 SCAN_UPDATE_SIGNATURE, 474 SCAN_NEW_INSTALL, 475 SCAN_UPDATE_TIME, 476 SCAN_BOOTING, 477 SCAN_TRUSTED_OVERLAY, 478 SCAN_DELETE_DATA_ON_FAILURES, 479 SCAN_REQUIRE_KNOWN, 480 SCAN_MOVE, 481 SCAN_INITIAL, 482 SCAN_CHECK_ONLY, 483 SCAN_DONT_KILL_APP, 484 SCAN_IGNORE_FROZEN, 485 SCAN_FIRST_BOOT_OR_UPGRADE, 486 SCAN_AS_INSTANT_APP, 487 SCAN_AS_FULL_APP, 488 SCAN_AS_VIRTUAL_PRELOAD, 489 }) 490 @Retention(RetentionPolicy.SOURCE) 491 public @interface ScanFlags {} 492 493 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 494 /** Extension of the compressed packages */ 495 public final static String COMPRESSED_EXTENSION = ".gz"; 496 /** Suffix of stub packages on the system partition */ 497 public final static String STUB_SUFFIX = "-Stub"; 498 499 private static final int[] EMPTY_INT_ARRAY = new int[0]; 500 501 private static final int TYPE_UNKNOWN = 0; 502 private static final int TYPE_ACTIVITY = 1; 503 private static final int TYPE_RECEIVER = 2; 504 private static final int TYPE_SERVICE = 3; 505 private static final int TYPE_PROVIDER = 4; 506 @IntDef(prefix = { "TYPE_" }, value = { 507 TYPE_UNKNOWN, 508 TYPE_ACTIVITY, 509 TYPE_RECEIVER, 510 TYPE_SERVICE, 511 TYPE_PROVIDER, 512 }) 513 @Retention(RetentionPolicy.SOURCE) 514 public @interface ComponentType {} 515 516 /** 517 * Timeout (in milliseconds) after which the watchdog should declare that 518 * our handler thread is wedged. The usual default for such things is one 519 * minute but we sometimes do very lengthy I/O operations on this thread, 520 * such as installing multi-gigabyte applications, so ours needs to be longer. 521 */ 522 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 523 524 /** 525 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 526 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 527 * settings entry if available, otherwise we use the hardcoded default. If it's been 528 * more than this long since the last fstrim, we force one during the boot sequence. 529 * 530 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 531 * one gets run at the next available charging+idle time. This final mandatory 532 * no-fstrim check kicks in only of the other scheduling criteria is never met. 533 */ 534 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 535 536 /** 537 * Whether verification is enabled by default. 538 */ 539 private static final boolean DEFAULT_VERIFY_ENABLE = true; 540 541 /** 542 * The default maximum time to wait for the verification agent to return in 543 * milliseconds. 544 */ 545 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 546 547 /** 548 * The default response for package verification timeout. 549 * 550 * This can be either PackageManager.VERIFICATION_ALLOW or 551 * PackageManager.VERIFICATION_REJECT. 552 */ 553 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 554 555 public static final String PLATFORM_PACKAGE_NAME = "android"; 556 557 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 558 559 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 560 DEFAULT_CONTAINER_PACKAGE, 561 "com.android.defcontainer.DefaultContainerService"); 562 563 private static final String KILL_APP_REASON_GIDS_CHANGED = 564 "permission grant or revoke changed gids"; 565 566 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 567 "permissions revoked"; 568 569 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 570 571 private static final String PACKAGE_SCHEME = "package"; 572 573 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 574 575 private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob"; 576 577 /** Canonical intent used to identify what counts as a "web browser" app */ 578 private static final Intent sBrowserIntent; 579 static { 580 sBrowserIntent = new Intent(); 581 sBrowserIntent.setAction(Intent.ACTION_VIEW); 582 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 583 sBrowserIntent.setData(Uri.parse("http:")); 584 } 585 586 /** 587 * The set of all protected actions [i.e. those actions for which a high priority 588 * intent filter is disallowed]. 589 */ 590 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 591 static { 592 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 593 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 594 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 595 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 596 } 597 598 // Compilation reasons. 599 public static final int REASON_FIRST_BOOT = 0; 600 public static final int REASON_BOOT = 1; 601 public static final int REASON_INSTALL = 2; 602 public static final int REASON_BACKGROUND_DEXOPT = 3; 603 public static final int REASON_AB_OTA = 4; 604 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5; 605 public static final int REASON_SHARED = 6; 606 607 public static final int REASON_LAST = REASON_SHARED; 608 609 /** 610 * Version number for the package parser cache. Increment this whenever the format or 611 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 612 */ 613 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 614 615 /** 616 * Whether the package parser cache is enabled. 617 */ 618 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 619 620 /** 621 * Permissions required in order to receive instant application lifecycle broadcasts. 622 */ 623 private static final String[] INSTANT_APP_BROADCAST_PERMISSION = 624 new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS }; 625 626 final ServiceThread mHandlerThread; 627 628 final PackageHandler mHandler; 629 630 private final ProcessLoggingHandler mProcessLoggingHandler; 631 632 /** 633 * Messages for {@link #mHandler} that need to wait for system ready before 634 * being dispatched. 635 */ 636 private ArrayList<Message> mPostSystemReadyMessages; 637 638 final int mSdkVersion = Build.VERSION.SDK_INT; 639 640 final Context mContext; 641 final boolean mFactoryTest; 642 final boolean mOnlyCore; 643 final DisplayMetrics mMetrics; 644 final int mDefParseFlags; 645 final String[] mSeparateProcesses; 646 final boolean mIsUpgrade; 647 final boolean mIsPreNUpgrade; 648 final boolean mIsPreNMR1Upgrade; 649 650 // Have we told the Activity Manager to whitelist the default container service by uid yet? 651 @GuardedBy("mPackages") 652 boolean mDefaultContainerWhitelisted = false; 653 654 @GuardedBy("mPackages") 655 private boolean mDexOptDialogShown; 656 657 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 658 // LOCK HELD. Can be called with mInstallLock held. 659 @GuardedBy("mInstallLock") 660 final Installer mInstaller; 661 662 /** Directory where installed applications are stored */ 663 private static final File sAppInstallDir = 664 new File(Environment.getDataDirectory(), "app"); 665 /** Directory where installed application's 32-bit native libraries are copied. */ 666 private static final File sAppLib32InstallDir = 667 new File(Environment.getDataDirectory(), "app-lib"); 668 /** Directory where code and non-resource assets of forward-locked applications are stored */ 669 private static final File sDrmAppPrivateInstallDir = 670 new File(Environment.getDataDirectory(), "app-private"); 671 672 // ---------------------------------------------------------------- 673 674 // Lock for state used when installing and doing other long running 675 // operations. Methods that must be called with this lock held have 676 // the suffix "LI". 677 final Object mInstallLock = new Object(); 678 679 // ---------------------------------------------------------------- 680 681 // Keys are String (package name), values are Package. This also serves 682 // as the lock for the global state. Methods that must be called with 683 // this lock held have the prefix "LP". 684 @GuardedBy("mPackages") 685 final ArrayMap<String, PackageParser.Package> mPackages = 686 new ArrayMap<String, PackageParser.Package>(); 687 688 final ArrayMap<String, Set<String>> mKnownCodebase = 689 new ArrayMap<String, Set<String>>(); 690 691 // Keys are isolated uids and values are the uid of the application 692 // that created the isolated proccess. 693 @GuardedBy("mPackages") 694 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 695 696 /** 697 * Tracks new system packages [received in an OTA] that we expect to 698 * find updated user-installed versions. Keys are package name, values 699 * are package location. 700 */ 701 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 702 /** 703 * Tracks high priority intent filters for protected actions. During boot, certain 704 * filter actions are protected and should never be allowed to have a high priority 705 * intent filter for them. However, there is one, and only one exception -- the 706 * setup wizard. It must be able to define a high priority intent filter for these 707 * actions to ensure there are no escapes from the wizard. We need to delay processing 708 * of these during boot as we need to look at all of the system packages in order 709 * to know which component is the setup wizard. 710 */ 711 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 712 /** 713 * Whether or not processing protected filters should be deferred. 714 */ 715 private boolean mDeferProtectedFilters = true; 716 717 /** 718 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 719 */ 720 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 721 /** 722 * Whether or not system app permissions should be promoted from install to runtime. 723 */ 724 boolean mPromoteSystemApps; 725 726 @GuardedBy("mPackages") 727 final Settings mSettings; 728 729 /** 730 * Set of package names that are currently "frozen", which means active 731 * surgery is being done on the code/data for that package. The platform 732 * will refuse to launch frozen packages to avoid race conditions. 733 * 734 * @see PackageFreezer 735 */ 736 @GuardedBy("mPackages") 737 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 738 739 final ProtectedPackages mProtectedPackages; 740 741 @GuardedBy("mLoadedVolumes") 742 final ArraySet<String> mLoadedVolumes = new ArraySet<>(); 743 744 boolean mFirstBoot; 745 746 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 747 748 @GuardedBy("mAvailableFeatures") 749 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 750 751 private final InstantAppRegistry mInstantAppRegistry; 752 753 @GuardedBy("mPackages") 754 int mChangedPackagesSequenceNumber; 755 /** 756 * List of changed [installed, removed or updated] packages. 757 * mapping from user id -> sequence number -> package name 758 */ 759 @GuardedBy("mPackages") 760 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 761 /** 762 * The sequence number of the last change to a package. 763 * mapping from user id -> package name -> sequence number 764 */ 765 @GuardedBy("mPackages") 766 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 767 768 @GuardedBy("mPackages") 769 final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>(); 770 771 class PackageParserCallback implements PackageParser.Callback { 772 @Override public final boolean hasFeature(String feature) { 773 return PackageManagerService.this.hasSystemFeature(feature, 0); 774 } 775 776 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 777 Collection<PackageParser.Package> allPackages, String targetPackageName) { 778 List<PackageParser.Package> overlayPackages = null; 779 for (PackageParser.Package p : allPackages) { 780 if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) { 781 if (overlayPackages == null) { 782 overlayPackages = new ArrayList<PackageParser.Package>(); 783 } 784 overlayPackages.add(p); 785 } 786 } 787 if (overlayPackages != null) { 788 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 789 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 790 return p1.mOverlayPriority - p2.mOverlayPriority; 791 } 792 }; 793 Collections.sort(overlayPackages, cmp); 794 } 795 return overlayPackages; 796 } 797 798 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 799 String targetPackageName, String targetPath) { 800 if ("android".equals(targetPackageName)) { 801 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 802 // native AssetManager. 803 return null; 804 } 805 List<PackageParser.Package> overlayPackages = 806 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 807 if (overlayPackages == null || overlayPackages.isEmpty()) { 808 return null; 809 } 810 List<String> overlayPathList = null; 811 for (PackageParser.Package overlayPackage : overlayPackages) { 812 if (targetPath == null) { 813 if (overlayPathList == null) { 814 overlayPathList = new ArrayList<String>(); 815 } 816 overlayPathList.add(overlayPackage.baseCodePath); 817 continue; 818 } 819 820 try { 821 // Creates idmaps for system to parse correctly the Android manifest of the 822 // target package. 823 // 824 // OverlayManagerService will update each of them with a correct gid from its 825 // target package app id. 826 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 827 UserHandle.getSharedAppGid( 828 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 829 if (overlayPathList == null) { 830 overlayPathList = new ArrayList<String>(); 831 } 832 overlayPathList.add(overlayPackage.baseCodePath); 833 } catch (InstallerException e) { 834 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 835 overlayPackage.baseCodePath); 836 } 837 } 838 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 839 } 840 841 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 842 synchronized (mPackages) { 843 return getStaticOverlayPathsLocked( 844 mPackages.values(), targetPackageName, targetPath); 845 } 846 } 847 848 @Override public final String[] getOverlayApks(String targetPackageName) { 849 return getStaticOverlayPaths(targetPackageName, null); 850 } 851 852 @Override public final String[] getOverlayPaths(String targetPackageName, 853 String targetPath) { 854 return getStaticOverlayPaths(targetPackageName, targetPath); 855 } 856 } 857 858 class ParallelPackageParserCallback extends PackageParserCallback { 859 List<PackageParser.Package> mOverlayPackages = null; 860 861 void findStaticOverlayPackages() { 862 synchronized (mPackages) { 863 for (PackageParser.Package p : mPackages.values()) { 864 if (p.mIsStaticOverlay) { 865 if (mOverlayPackages == null) { 866 mOverlayPackages = new ArrayList<PackageParser.Package>(); 867 } 868 mOverlayPackages.add(p); 869 } 870 } 871 } 872 } 873 874 @Override 875 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 876 // We can trust mOverlayPackages without holding mPackages because package uninstall 877 // can't happen while running parallel parsing. 878 // Moreover holding mPackages on each parsing thread causes dead-lock. 879 return mOverlayPackages == null ? null : 880 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 881 } 882 } 883 884 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 885 final ParallelPackageParserCallback mParallelPackageParserCallback = 886 new ParallelPackageParserCallback(); 887 888 public static final class SharedLibraryEntry { 889 public final @Nullable String path; 890 public final @Nullable String apk; 891 public final @NonNull SharedLibraryInfo info; 892 893 SharedLibraryEntry(String _path, String _apk, String name, long version, int type, 894 String declaringPackageName, long declaringPackageVersionCode) { 895 path = _path; 896 apk = _apk; 897 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 898 declaringPackageName, declaringPackageVersionCode), null); 899 } 900 } 901 902 // Currently known shared libraries. 903 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 904 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 905 new ArrayMap<>(); 906 907 // All available activities, for your resolving pleasure. 908 final ActivityIntentResolver mActivities = 909 new ActivityIntentResolver(); 910 911 // All available receivers, for your resolving pleasure. 912 final ActivityIntentResolver mReceivers = 913 new ActivityIntentResolver(); 914 915 // All available services, for your resolving pleasure. 916 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 917 918 // All available providers, for your resolving pleasure. 919 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 920 921 // Mapping from provider base names (first directory in content URI codePath) 922 // to the provider information. 923 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 924 new ArrayMap<String, PackageParser.Provider>(); 925 926 // Mapping from instrumentation class names to info about them. 927 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 928 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 929 930 // Packages whose data we have transfered into another package, thus 931 // should no longer exist. 932 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 933 934 // Broadcast actions that are only available to the system. 935 @GuardedBy("mProtectedBroadcasts") 936 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>(); 937 938 /** List of packages waiting for verification. */ 939 final SparseArray<PackageVerificationState> mPendingVerification 940 = new SparseArray<PackageVerificationState>(); 941 942 final PackageInstallerService mInstallerService; 943 944 final ArtManagerService mArtManagerService; 945 946 private final PackageDexOptimizer mPackageDexOptimizer; 947 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 948 // is used by other apps). 949 private final DexManager mDexManager; 950 951 private AtomicInteger mNextMoveId = new AtomicInteger(); 952 private final MoveCallbacks mMoveCallbacks; 953 954 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 955 956 // Cache of users who need badging. 957 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 958 959 /** Token for keys in mPendingVerification. */ 960 private int mPendingVerificationToken = 0; 961 962 volatile boolean mSystemReady; 963 volatile boolean mSafeMode; 964 volatile boolean mHasSystemUidErrors; 965 private volatile boolean mEphemeralAppsDisabled; 966 967 ApplicationInfo mAndroidApplication; 968 final ActivityInfo mResolveActivity = new ActivityInfo(); 969 final ResolveInfo mResolveInfo = new ResolveInfo(); 970 ComponentName mResolveComponentName; 971 PackageParser.Package mPlatformPackage; 972 ComponentName mCustomResolverComponentName; 973 974 boolean mResolverReplaced = false; 975 976 private final @Nullable ComponentName mIntentFilterVerifierComponent; 977 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 978 979 private int mIntentFilterVerificationToken = 0; 980 981 /** The service connection to the ephemeral resolver */ 982 final EphemeralResolverConnection mInstantAppResolverConnection; 983 /** Component used to show resolver settings for Instant Apps */ 984 final ComponentName mInstantAppResolverSettingsComponent; 985 986 /** Activity used to install instant applications */ 987 ActivityInfo mInstantAppInstallerActivity; 988 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 989 990 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 991 = new SparseArray<IntentFilterVerificationState>(); 992 993 // TODO remove this and go through mPermissonManager directly 994 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 995 private final PermissionManagerInternal mPermissionManager; 996 997 // List of packages names to keep cached, even if they are uninstalled for all users 998 private List<String> mKeepUninstalledPackages; 999 1000 private UserManagerInternal mUserManagerInternal; 1001 private ActivityManagerInternal mActivityManagerInternal; 1002 1003 private DeviceIdleController.LocalService mDeviceIdleController; 1004 1005 private File mCacheDir; 1006 1007 private Future<?> mPrepareAppDataFuture; 1008 1009 private static class IFVerificationParams { 1010 PackageParser.Package pkg; 1011 boolean replacing; 1012 int userId; 1013 int verifierUid; 1014 1015 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1016 int _userId, int _verifierUid) { 1017 pkg = _pkg; 1018 replacing = _replacing; 1019 userId = _userId; 1020 replacing = _replacing; 1021 verifierUid = _verifierUid; 1022 } 1023 } 1024 1025 private interface IntentFilterVerifier<T extends IntentFilter> { 1026 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1027 T filter, String packageName); 1028 void startVerifications(int userId); 1029 void receiveVerificationResponse(int verificationId); 1030 } 1031 1032 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1033 private Context mContext; 1034 private ComponentName mIntentFilterVerifierComponent; 1035 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1036 1037 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1038 mContext = context; 1039 mIntentFilterVerifierComponent = verifierComponent; 1040 } 1041 1042 private String getDefaultScheme() { 1043 return IntentFilter.SCHEME_HTTPS; 1044 } 1045 1046 @Override 1047 public void startVerifications(int userId) { 1048 // Launch verifications requests 1049 int count = mCurrentIntentFilterVerifications.size(); 1050 for (int n=0; n<count; n++) { 1051 int verificationId = mCurrentIntentFilterVerifications.get(n); 1052 final IntentFilterVerificationState ivs = 1053 mIntentFilterVerificationStates.get(verificationId); 1054 1055 String packageName = ivs.getPackageName(); 1056 1057 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1058 final int filterCount = filters.size(); 1059 ArraySet<String> domainsSet = new ArraySet<>(); 1060 for (int m=0; m<filterCount; m++) { 1061 PackageParser.ActivityIntentInfo filter = filters.get(m); 1062 domainsSet.addAll(filter.getHostsList()); 1063 } 1064 synchronized (mPackages) { 1065 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1066 packageName, domainsSet) != null) { 1067 scheduleWriteSettingsLocked(); 1068 } 1069 } 1070 sendVerificationRequest(verificationId, ivs); 1071 } 1072 mCurrentIntentFilterVerifications.clear(); 1073 } 1074 1075 private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) { 1076 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1077 verificationIntent.putExtra( 1078 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1079 verificationId); 1080 verificationIntent.putExtra( 1081 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1082 getDefaultScheme()); 1083 verificationIntent.putExtra( 1084 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1085 ivs.getHostsString()); 1086 verificationIntent.putExtra( 1087 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1088 ivs.getPackageName()); 1089 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1090 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1091 1092 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1093 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1094 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1095 UserHandle.USER_SYSTEM, true, "intent filter verifier"); 1096 1097 mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM); 1098 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1099 "Sending IntentFilter verification broadcast"); 1100 } 1101 1102 public void receiveVerificationResponse(int verificationId) { 1103 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1104 1105 final boolean verified = ivs.isVerified(); 1106 1107 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1108 final int count = filters.size(); 1109 if (DEBUG_DOMAIN_VERIFICATION) { 1110 Slog.i(TAG, "Received verification response " + verificationId 1111 + " for " + count + " filters, verified=" + verified); 1112 } 1113 for (int n=0; n<count; n++) { 1114 PackageParser.ActivityIntentInfo filter = filters.get(n); 1115 filter.setVerified(verified); 1116 1117 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1118 + " verified with result:" + verified + " and hosts:" 1119 + ivs.getHostsString()); 1120 } 1121 1122 mIntentFilterVerificationStates.remove(verificationId); 1123 1124 final String packageName = ivs.getPackageName(); 1125 IntentFilterVerificationInfo ivi = null; 1126 1127 synchronized (mPackages) { 1128 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1129 } 1130 if (ivi == null) { 1131 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1132 + verificationId + " packageName:" + packageName); 1133 return; 1134 } 1135 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1136 "Updating IntentFilterVerificationInfo for package " + packageName 1137 +" verificationId:" + verificationId); 1138 1139 synchronized (mPackages) { 1140 if (verified) { 1141 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1142 } else { 1143 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1144 } 1145 scheduleWriteSettingsLocked(); 1146 1147 final int userId = ivs.getUserId(); 1148 if (userId != UserHandle.USER_ALL) { 1149 final int userStatus = 1150 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1151 1152 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1153 boolean needUpdate = false; 1154 1155 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1156 // already been set by the User thru the Disambiguation dialog 1157 switch (userStatus) { 1158 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1159 if (verified) { 1160 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1161 } else { 1162 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1163 } 1164 needUpdate = true; 1165 break; 1166 1167 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1168 if (verified) { 1169 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1170 needUpdate = true; 1171 } 1172 break; 1173 1174 default: 1175 // Nothing to do 1176 } 1177 1178 if (needUpdate) { 1179 mSettings.updateIntentFilterVerificationStatusLPw( 1180 packageName, updatedStatus, userId); 1181 scheduleWritePackageRestrictionsLocked(userId); 1182 } 1183 } 1184 } 1185 } 1186 1187 @Override 1188 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1189 ActivityIntentInfo filter, String packageName) { 1190 if (!hasValidDomains(filter)) { 1191 return false; 1192 } 1193 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1194 if (ivs == null) { 1195 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1196 packageName); 1197 } 1198 if (DEBUG_DOMAIN_VERIFICATION) { 1199 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1200 } 1201 ivs.addFilter(filter); 1202 return true; 1203 } 1204 1205 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1206 int userId, int verificationId, String packageName) { 1207 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1208 verifierUid, userId, packageName); 1209 ivs.setPendingState(); 1210 synchronized (mPackages) { 1211 mIntentFilterVerificationStates.append(verificationId, ivs); 1212 mCurrentIntentFilterVerifications.add(verificationId); 1213 } 1214 return ivs; 1215 } 1216 } 1217 1218 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1219 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1220 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1221 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1222 } 1223 1224 // Set of pending broadcasts for aggregating enable/disable of components. 1225 static class PendingPackageBroadcasts { 1226 // for each user id, a map of <package name -> components within that package> 1227 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1228 1229 public PendingPackageBroadcasts() { 1230 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1231 } 1232 1233 public ArrayList<String> get(int userId, String packageName) { 1234 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1235 return packages.get(packageName); 1236 } 1237 1238 public void put(int userId, String packageName, ArrayList<String> components) { 1239 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1240 packages.put(packageName, components); 1241 } 1242 1243 public void remove(int userId, String packageName) { 1244 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1245 if (packages != null) { 1246 packages.remove(packageName); 1247 } 1248 } 1249 1250 public void remove(int userId) { 1251 mUidMap.remove(userId); 1252 } 1253 1254 public int userIdCount() { 1255 return mUidMap.size(); 1256 } 1257 1258 public int userIdAt(int n) { 1259 return mUidMap.keyAt(n); 1260 } 1261 1262 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1263 return mUidMap.get(userId); 1264 } 1265 1266 public int size() { 1267 // total number of pending broadcast entries across all userIds 1268 int num = 0; 1269 for (int i = 0; i< mUidMap.size(); i++) { 1270 num += mUidMap.valueAt(i).size(); 1271 } 1272 return num; 1273 } 1274 1275 public void clear() { 1276 mUidMap.clear(); 1277 } 1278 1279 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1280 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1281 if (map == null) { 1282 map = new ArrayMap<String, ArrayList<String>>(); 1283 mUidMap.put(userId, map); 1284 } 1285 return map; 1286 } 1287 } 1288 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1289 1290 // Service Connection to remote media container service to copy 1291 // package uri's from external media onto secure containers 1292 // or internal storage. 1293 private IMediaContainerService mContainerService = null; 1294 1295 static final int SEND_PENDING_BROADCAST = 1; 1296 static final int MCS_BOUND = 3; 1297 static final int END_COPY = 4; 1298 static final int INIT_COPY = 5; 1299 static final int MCS_UNBIND = 6; 1300 static final int START_CLEANING_PACKAGE = 7; 1301 static final int FIND_INSTALL_LOC = 8; 1302 static final int POST_INSTALL = 9; 1303 static final int MCS_RECONNECT = 10; 1304 static final int MCS_GIVE_UP = 11; 1305 static final int WRITE_SETTINGS = 13; 1306 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1307 static final int PACKAGE_VERIFIED = 15; 1308 static final int CHECK_PENDING_VERIFICATION = 16; 1309 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1310 static final int INTENT_FILTER_VERIFIED = 18; 1311 static final int WRITE_PACKAGE_LIST = 19; 1312 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1313 1314 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1315 1316 // Delay time in millisecs 1317 static final int BROADCAST_DELAY = 10 * 1000; 1318 1319 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1320 2 * 60 * 60 * 1000L; /* two hours */ 1321 1322 static UserManagerService sUserManager; 1323 1324 // Stores a list of users whose package restrictions file needs to be updated 1325 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1326 1327 final private DefaultContainerConnection mDefContainerConn = 1328 new DefaultContainerConnection(); 1329 class DefaultContainerConnection implements ServiceConnection { 1330 public void onServiceConnected(ComponentName name, IBinder service) { 1331 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1332 final IMediaContainerService imcs = IMediaContainerService.Stub 1333 .asInterface(Binder.allowBlocking(service)); 1334 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1335 } 1336 1337 public void onServiceDisconnected(ComponentName name) { 1338 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1339 } 1340 } 1341 1342 // Recordkeeping of restore-after-install operations that are currently in flight 1343 // between the Package Manager and the Backup Manager 1344 static class PostInstallData { 1345 public InstallArgs args; 1346 public PackageInstalledInfo res; 1347 1348 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1349 args = _a; 1350 res = _r; 1351 } 1352 } 1353 1354 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1355 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1356 1357 // XML tags for backup/restore of various bits of state 1358 private static final String TAG_PREFERRED_BACKUP = "pa"; 1359 private static final String TAG_DEFAULT_APPS = "da"; 1360 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1361 1362 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1363 private static final String TAG_ALL_GRANTS = "rt-grants"; 1364 private static final String TAG_GRANT = "grant"; 1365 private static final String ATTR_PACKAGE_NAME = "pkg"; 1366 1367 private static final String TAG_PERMISSION = "perm"; 1368 private static final String ATTR_PERMISSION_NAME = "name"; 1369 private static final String ATTR_IS_GRANTED = "g"; 1370 private static final String ATTR_USER_SET = "set"; 1371 private static final String ATTR_USER_FIXED = "fixed"; 1372 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1373 1374 // System/policy permission grants are not backed up 1375 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1376 FLAG_PERMISSION_POLICY_FIXED 1377 | FLAG_PERMISSION_SYSTEM_FIXED 1378 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1379 1380 // And we back up these user-adjusted states 1381 private static final int USER_RUNTIME_GRANT_MASK = 1382 FLAG_PERMISSION_USER_SET 1383 | FLAG_PERMISSION_USER_FIXED 1384 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1385 1386 final @Nullable String mRequiredVerifierPackage; 1387 final @NonNull String mRequiredInstallerPackage; 1388 final @NonNull String mRequiredUninstallerPackage; 1389 final @Nullable String mSetupWizardPackage; 1390 final @Nullable String mStorageManagerPackage; 1391 final @NonNull String mServicesSystemSharedLibraryPackageName; 1392 final @NonNull String mSharedSystemSharedLibraryPackageName; 1393 1394 private final PackageUsage mPackageUsage = new PackageUsage(); 1395 private final CompilerStats mCompilerStats = new CompilerStats(); 1396 1397 class PackageHandler extends Handler { 1398 private boolean mBound = false; 1399 final ArrayList<HandlerParams> mPendingInstalls = 1400 new ArrayList<HandlerParams>(); 1401 1402 private boolean connectToService() { 1403 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1404 " DefaultContainerService"); 1405 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1406 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1407 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1408 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1409 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1410 mBound = true; 1411 return true; 1412 } 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1414 return false; 1415 } 1416 1417 private void disconnectService() { 1418 mContainerService = null; 1419 mBound = false; 1420 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1421 mContext.unbindService(mDefContainerConn); 1422 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1423 } 1424 1425 PackageHandler(Looper looper) { 1426 super(looper); 1427 } 1428 1429 public void handleMessage(Message msg) { 1430 try { 1431 doHandleMessage(msg); 1432 } finally { 1433 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1434 } 1435 } 1436 1437 void doHandleMessage(Message msg) { 1438 switch (msg.what) { 1439 case INIT_COPY: { 1440 HandlerParams params = (HandlerParams) msg.obj; 1441 int idx = mPendingInstalls.size(); 1442 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1443 // If a bind was already initiated we dont really 1444 // need to do anything. The pending install 1445 // will be processed later on. 1446 if (!mBound) { 1447 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1448 System.identityHashCode(mHandler)); 1449 // If this is the only one pending we might 1450 // have to bind to the service again. 1451 if (!connectToService()) { 1452 Slog.e(TAG, "Failed to bind to media container service"); 1453 params.serviceError(); 1454 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1455 System.identityHashCode(mHandler)); 1456 if (params.traceMethod != null) { 1457 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1458 params.traceCookie); 1459 } 1460 return; 1461 } else { 1462 // Once we bind to the service, the first 1463 // pending request will be processed. 1464 mPendingInstalls.add(idx, params); 1465 } 1466 } else { 1467 mPendingInstalls.add(idx, params); 1468 // Already bound to the service. Just make 1469 // sure we trigger off processing the first request. 1470 if (idx == 0) { 1471 mHandler.sendEmptyMessage(MCS_BOUND); 1472 } 1473 } 1474 break; 1475 } 1476 case MCS_BOUND: { 1477 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1478 if (msg.obj != null) { 1479 mContainerService = (IMediaContainerService) msg.obj; 1480 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1481 System.identityHashCode(mHandler)); 1482 } 1483 if (mContainerService == null) { 1484 if (!mBound) { 1485 // Something seriously wrong since we are not bound and we are not 1486 // waiting for connection. Bail out. 1487 Slog.e(TAG, "Cannot bind to media container service"); 1488 for (HandlerParams params : mPendingInstalls) { 1489 // Indicate service bind error 1490 params.serviceError(); 1491 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1492 System.identityHashCode(params)); 1493 if (params.traceMethod != null) { 1494 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1495 params.traceMethod, params.traceCookie); 1496 } 1497 return; 1498 } 1499 mPendingInstalls.clear(); 1500 } else { 1501 Slog.w(TAG, "Waiting to connect to media container service"); 1502 } 1503 } else if (mPendingInstalls.size() > 0) { 1504 HandlerParams params = mPendingInstalls.get(0); 1505 if (params != null) { 1506 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1507 System.identityHashCode(params)); 1508 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1509 if (params.startCopy()) { 1510 // We are done... look for more work or to 1511 // go idle. 1512 if (DEBUG_SD_INSTALL) Log.i(TAG, 1513 "Checking for more work or unbind..."); 1514 // Delete pending install 1515 if (mPendingInstalls.size() > 0) { 1516 mPendingInstalls.remove(0); 1517 } 1518 if (mPendingInstalls.size() == 0) { 1519 if (mBound) { 1520 if (DEBUG_SD_INSTALL) Log.i(TAG, 1521 "Posting delayed MCS_UNBIND"); 1522 removeMessages(MCS_UNBIND); 1523 Message ubmsg = obtainMessage(MCS_UNBIND); 1524 // Unbind after a little delay, to avoid 1525 // continual thrashing. 1526 sendMessageDelayed(ubmsg, 10000); 1527 } 1528 } else { 1529 // There are more pending requests in queue. 1530 // Just post MCS_BOUND message to trigger processing 1531 // of next pending install. 1532 if (DEBUG_SD_INSTALL) Log.i(TAG, 1533 "Posting MCS_BOUND for next work"); 1534 mHandler.sendEmptyMessage(MCS_BOUND); 1535 } 1536 } 1537 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1538 } 1539 } else { 1540 // Should never happen ideally. 1541 Slog.w(TAG, "Empty queue"); 1542 } 1543 break; 1544 } 1545 case MCS_RECONNECT: { 1546 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1547 if (mPendingInstalls.size() > 0) { 1548 if (mBound) { 1549 disconnectService(); 1550 } 1551 if (!connectToService()) { 1552 Slog.e(TAG, "Failed to bind to media container service"); 1553 for (HandlerParams params : mPendingInstalls) { 1554 // Indicate service bind error 1555 params.serviceError(); 1556 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1557 System.identityHashCode(params)); 1558 } 1559 mPendingInstalls.clear(); 1560 } 1561 } 1562 break; 1563 } 1564 case MCS_UNBIND: { 1565 // If there is no actual work left, then time to unbind. 1566 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1567 1568 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1569 if (mBound) { 1570 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1571 1572 disconnectService(); 1573 } 1574 } else if (mPendingInstalls.size() > 0) { 1575 // There are more pending requests in queue. 1576 // Just post MCS_BOUND message to trigger processing 1577 // of next pending install. 1578 mHandler.sendEmptyMessage(MCS_BOUND); 1579 } 1580 1581 break; 1582 } 1583 case MCS_GIVE_UP: { 1584 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1585 HandlerParams params = mPendingInstalls.remove(0); 1586 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1587 System.identityHashCode(params)); 1588 break; 1589 } 1590 case SEND_PENDING_BROADCAST: { 1591 String packages[]; 1592 ArrayList<String> components[]; 1593 int size = 0; 1594 int uids[]; 1595 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1596 synchronized (mPackages) { 1597 if (mPendingBroadcasts == null) { 1598 return; 1599 } 1600 size = mPendingBroadcasts.size(); 1601 if (size <= 0) { 1602 // Nothing to be done. Just return 1603 return; 1604 } 1605 packages = new String[size]; 1606 components = new ArrayList[size]; 1607 uids = new int[size]; 1608 int i = 0; // filling out the above arrays 1609 1610 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1611 int packageUserId = mPendingBroadcasts.userIdAt(n); 1612 Iterator<Map.Entry<String, ArrayList<String>>> it 1613 = mPendingBroadcasts.packagesForUserId(packageUserId) 1614 .entrySet().iterator(); 1615 while (it.hasNext() && i < size) { 1616 Map.Entry<String, ArrayList<String>> ent = it.next(); 1617 packages[i] = ent.getKey(); 1618 components[i] = ent.getValue(); 1619 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1620 uids[i] = (ps != null) 1621 ? UserHandle.getUid(packageUserId, ps.appId) 1622 : -1; 1623 i++; 1624 } 1625 } 1626 size = i; 1627 mPendingBroadcasts.clear(); 1628 } 1629 // Send broadcasts 1630 for (int i = 0; i < size; i++) { 1631 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1632 } 1633 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1634 break; 1635 } 1636 case START_CLEANING_PACKAGE: { 1637 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1638 final String packageName = (String)msg.obj; 1639 final int userId = msg.arg1; 1640 final boolean andCode = msg.arg2 != 0; 1641 synchronized (mPackages) { 1642 if (userId == UserHandle.USER_ALL) { 1643 int[] users = sUserManager.getUserIds(); 1644 for (int user : users) { 1645 mSettings.addPackageToCleanLPw( 1646 new PackageCleanItem(user, packageName, andCode)); 1647 } 1648 } else { 1649 mSettings.addPackageToCleanLPw( 1650 new PackageCleanItem(userId, packageName, andCode)); 1651 } 1652 } 1653 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1654 startCleaningPackages(); 1655 } break; 1656 case POST_INSTALL: { 1657 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1658 1659 PostInstallData data = mRunningInstalls.get(msg.arg1); 1660 final boolean didRestore = (msg.arg2 != 0); 1661 mRunningInstalls.delete(msg.arg1); 1662 1663 if (data != null) { 1664 InstallArgs args = data.args; 1665 PackageInstalledInfo parentRes = data.res; 1666 1667 final boolean grantPermissions = (args.installFlags 1668 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1669 final boolean killApp = (args.installFlags 1670 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1671 final boolean virtualPreload = ((args.installFlags 1672 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 1673 final String[] grantedPermissions = args.installGrantPermissions; 1674 1675 // Handle the parent package 1676 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1677 virtualPreload, grantedPermissions, didRestore, 1678 args.installerPackageName, args.observer); 1679 1680 // Handle the child packages 1681 final int childCount = (parentRes.addedChildPackages != null) 1682 ? parentRes.addedChildPackages.size() : 0; 1683 for (int i = 0; i < childCount; i++) { 1684 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1685 handlePackagePostInstall(childRes, grantPermissions, killApp, 1686 virtualPreload, grantedPermissions, false /*didRestore*/, 1687 args.installerPackageName, args.observer); 1688 } 1689 1690 // Log tracing if needed 1691 if (args.traceMethod != null) { 1692 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1693 args.traceCookie); 1694 } 1695 } else { 1696 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1697 } 1698 1699 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1700 } break; 1701 case WRITE_SETTINGS: { 1702 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1703 synchronized (mPackages) { 1704 removeMessages(WRITE_SETTINGS); 1705 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1706 mSettings.writeLPr(); 1707 mDirtyUsers.clear(); 1708 } 1709 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1710 } break; 1711 case WRITE_PACKAGE_RESTRICTIONS: { 1712 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1713 synchronized (mPackages) { 1714 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1715 for (int userId : mDirtyUsers) { 1716 mSettings.writePackageRestrictionsLPr(userId); 1717 } 1718 mDirtyUsers.clear(); 1719 } 1720 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1721 } break; 1722 case WRITE_PACKAGE_LIST: { 1723 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1724 synchronized (mPackages) { 1725 removeMessages(WRITE_PACKAGE_LIST); 1726 mSettings.writePackageListLPr(msg.arg1); 1727 } 1728 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1729 } break; 1730 case CHECK_PENDING_VERIFICATION: { 1731 final int verificationId = msg.arg1; 1732 final PackageVerificationState state = mPendingVerification.get(verificationId); 1733 1734 if ((state != null) && !state.timeoutExtended()) { 1735 final InstallArgs args = state.getInstallArgs(); 1736 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1737 1738 Slog.i(TAG, "Verification timed out for " + originUri); 1739 mPendingVerification.remove(verificationId); 1740 1741 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1742 1743 final UserHandle user = args.getUser(); 1744 if (getDefaultVerificationResponse(user) 1745 == PackageManager.VERIFICATION_ALLOW) { 1746 Slog.i(TAG, "Continuing with installation of " + originUri); 1747 state.setVerifierResponse(Binder.getCallingUid(), 1748 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1749 broadcastPackageVerified(verificationId, originUri, 1750 PackageManager.VERIFICATION_ALLOW, user); 1751 try { 1752 ret = args.copyApk(mContainerService, true); 1753 } catch (RemoteException e) { 1754 Slog.e(TAG, "Could not contact the ContainerService"); 1755 } 1756 } else { 1757 broadcastPackageVerified(verificationId, originUri, 1758 PackageManager.VERIFICATION_REJECT, user); 1759 } 1760 1761 Trace.asyncTraceEnd( 1762 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1763 1764 processPendingInstall(args, ret); 1765 mHandler.sendEmptyMessage(MCS_UNBIND); 1766 } 1767 break; 1768 } 1769 case PACKAGE_VERIFIED: { 1770 final int verificationId = msg.arg1; 1771 1772 final PackageVerificationState state = mPendingVerification.get(verificationId); 1773 if (state == null) { 1774 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1775 break; 1776 } 1777 1778 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1779 1780 state.setVerifierResponse(response.callerUid, response.code); 1781 1782 if (state.isVerificationComplete()) { 1783 mPendingVerification.remove(verificationId); 1784 1785 final InstallArgs args = state.getInstallArgs(); 1786 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1787 1788 int ret; 1789 if (state.isInstallAllowed()) { 1790 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1791 broadcastPackageVerified(verificationId, originUri, 1792 response.code, state.getInstallArgs().getUser()); 1793 try { 1794 ret = args.copyApk(mContainerService, true); 1795 } catch (RemoteException e) { 1796 Slog.e(TAG, "Could not contact the ContainerService"); 1797 } 1798 } else { 1799 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1800 } 1801 1802 Trace.asyncTraceEnd( 1803 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1804 1805 processPendingInstall(args, ret); 1806 mHandler.sendEmptyMessage(MCS_UNBIND); 1807 } 1808 1809 break; 1810 } 1811 case START_INTENT_FILTER_VERIFICATIONS: { 1812 IFVerificationParams params = (IFVerificationParams) msg.obj; 1813 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1814 params.replacing, params.pkg); 1815 break; 1816 } 1817 case INTENT_FILTER_VERIFIED: { 1818 final int verificationId = msg.arg1; 1819 1820 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1821 verificationId); 1822 if (state == null) { 1823 Slog.w(TAG, "Invalid IntentFilter verification token " 1824 + verificationId + " received"); 1825 break; 1826 } 1827 1828 final int userId = state.getUserId(); 1829 1830 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1831 "Processing IntentFilter verification with token:" 1832 + verificationId + " and userId:" + userId); 1833 1834 final IntentFilterVerificationResponse response = 1835 (IntentFilterVerificationResponse) msg.obj; 1836 1837 state.setVerifierResponse(response.callerUid, response.code); 1838 1839 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1840 "IntentFilter verification with token:" + verificationId 1841 + " and userId:" + userId 1842 + " is settings verifier response with response code:" 1843 + response.code); 1844 1845 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1846 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1847 + response.getFailedDomainsString()); 1848 } 1849 1850 if (state.isVerificationComplete()) { 1851 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1852 } else { 1853 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1854 "IntentFilter verification with token:" + verificationId 1855 + " was not said to be complete"); 1856 } 1857 1858 break; 1859 } 1860 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1861 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1862 mInstantAppResolverConnection, 1863 (InstantAppRequest) msg.obj, 1864 mInstantAppInstallerActivity, 1865 mHandler); 1866 } 1867 } 1868 } 1869 } 1870 1871 private PermissionCallback mPermissionCallback = new PermissionCallback() { 1872 @Override 1873 public void onGidsChanged(int appId, int userId) { 1874 mHandler.post(new Runnable() { 1875 @Override 1876 public void run() { 1877 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 1878 } 1879 }); 1880 } 1881 @Override 1882 public void onPermissionGranted(int uid, int userId) { 1883 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1884 1885 // Not critical; if this is lost, the application has to request again. 1886 synchronized (mPackages) { 1887 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 1888 } 1889 } 1890 @Override 1891 public void onInstallPermissionGranted() { 1892 synchronized (mPackages) { 1893 scheduleWriteSettingsLocked(); 1894 } 1895 } 1896 @Override 1897 public void onPermissionRevoked(int uid, int userId) { 1898 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1899 1900 synchronized (mPackages) { 1901 // Critical; after this call the application should never have the permission 1902 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 1903 } 1904 1905 final int appId = UserHandle.getAppId(uid); 1906 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 1907 } 1908 @Override 1909 public void onInstallPermissionRevoked() { 1910 synchronized (mPackages) { 1911 scheduleWriteSettingsLocked(); 1912 } 1913 } 1914 @Override 1915 public void onPermissionUpdated(int[] updatedUserIds, boolean sync) { 1916 synchronized (mPackages) { 1917 for (int userId : updatedUserIds) { 1918 mSettings.writeRuntimePermissionsForUserLPr(userId, sync); 1919 } 1920 } 1921 } 1922 @Override 1923 public void onInstallPermissionUpdated() { 1924 synchronized (mPackages) { 1925 scheduleWriteSettingsLocked(); 1926 } 1927 } 1928 @Override 1929 public void onPermissionRemoved() { 1930 synchronized (mPackages) { 1931 mSettings.writeLPr(); 1932 } 1933 } 1934 }; 1935 1936 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1937 boolean killApp, boolean virtualPreload, String[] grantedPermissions, 1938 boolean launchedForRestore, String installerPackage, 1939 IPackageInstallObserver2 installObserver) { 1940 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1941 // Send the removed broadcasts 1942 if (res.removedInfo != null) { 1943 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1944 } 1945 1946 // Now that we successfully installed the package, grant runtime 1947 // permissions if requested before broadcasting the install. Also 1948 // for legacy apps in permission review mode we clear the permission 1949 // review flag which is used to emulate runtime permissions for 1950 // legacy apps. 1951 if (grantPermissions) { 1952 final int callingUid = Binder.getCallingUid(); 1953 mPermissionManager.grantRequestedRuntimePermissions( 1954 res.pkg, res.newUsers, grantedPermissions, callingUid, 1955 mPermissionCallback); 1956 } 1957 1958 final boolean update = res.removedInfo != null 1959 && res.removedInfo.removedPackage != null; 1960 final String installerPackageName = 1961 res.installerPackageName != null 1962 ? res.installerPackageName 1963 : res.removedInfo != null 1964 ? res.removedInfo.installerPackageName 1965 : null; 1966 1967 // If this is the first time we have child packages for a disabled privileged 1968 // app that had no children, we grant requested runtime permissions to the new 1969 // children if the parent on the system image had them already granted. 1970 if (res.pkg.parentPackage != null) { 1971 final int callingUid = Binder.getCallingUid(); 1972 mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage( 1973 res.pkg, callingUid, mPermissionCallback); 1974 } 1975 1976 synchronized (mPackages) { 1977 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1978 } 1979 1980 final String packageName = res.pkg.applicationInfo.packageName; 1981 1982 // Determine the set of users who are adding this package for 1983 // the first time vs. those who are seeing an update. 1984 int[] firstUserIds = EMPTY_INT_ARRAY; 1985 int[] firstInstantUserIds = EMPTY_INT_ARRAY; 1986 int[] updateUserIds = EMPTY_INT_ARRAY; 1987 int[] instantUserIds = EMPTY_INT_ARRAY; 1988 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1989 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1990 for (int newUser : res.newUsers) { 1991 final boolean isInstantApp = ps.getInstantApp(newUser); 1992 if (allNewUsers) { 1993 if (isInstantApp) { 1994 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 1995 } else { 1996 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 1997 } 1998 continue; 1999 } 2000 boolean isNew = true; 2001 for (int origUser : res.origUsers) { 2002 if (origUser == newUser) { 2003 isNew = false; 2004 break; 2005 } 2006 } 2007 if (isNew) { 2008 if (isInstantApp) { 2009 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 2010 } else { 2011 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 2012 } 2013 } else { 2014 if (isInstantApp) { 2015 instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser); 2016 } else { 2017 updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser); 2018 } 2019 } 2020 } 2021 2022 // Send installed broadcasts if the package is not a static shared lib. 2023 if (res.pkg.staticSharedLibName == null) { 2024 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 2025 2026 // Send added for users that see the package for the first time 2027 // sendPackageAddedForNewUsers also deals with system apps 2028 int appId = UserHandle.getAppId(res.uid); 2029 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 2030 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload, 2031 virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds); 2032 2033 // Send added for users that don't see the package for the first time 2034 Bundle extras = new Bundle(1); 2035 extras.putInt(Intent.EXTRA_UID, res.uid); 2036 if (update) { 2037 extras.putBoolean(Intent.EXTRA_REPLACING, true); 2038 } 2039 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2040 extras, 0 /*flags*/, 2041 null /*targetPackage*/, null /*finishedReceiver*/, 2042 updateUserIds, instantUserIds); 2043 if (installerPackageName != null) { 2044 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2045 extras, 0 /*flags*/, 2046 installerPackageName, null /*finishedReceiver*/, 2047 updateUserIds, instantUserIds); 2048 } 2049 2050 // Send replaced for users that don't see the package for the first time 2051 if (update) { 2052 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 2053 packageName, extras, 0 /*flags*/, 2054 null /*targetPackage*/, null /*finishedReceiver*/, 2055 updateUserIds, instantUserIds); 2056 if (installerPackageName != null) { 2057 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 2058 extras, 0 /*flags*/, 2059 installerPackageName, null /*finishedReceiver*/, 2060 updateUserIds, instantUserIds); 2061 } 2062 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 2063 null /*package*/, null /*extras*/, 0 /*flags*/, 2064 packageName /*targetPackage*/, 2065 null /*finishedReceiver*/, updateUserIds, instantUserIds); 2066 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 2067 // First-install and we did a restore, so we're responsible for the 2068 // first-launch broadcast. 2069 if (DEBUG_BACKUP) { 2070 Slog.i(TAG, "Post-restore of " + packageName 2071 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds)); 2072 } 2073 sendFirstLaunchBroadcast(packageName, installerPackage, 2074 firstUserIds, firstInstantUserIds); 2075 } 2076 2077 // Send broadcast package appeared if forward locked/external for all users 2078 // treat asec-hosted packages like removable media on upgrade 2079 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 2080 if (DEBUG_INSTALL) { 2081 Slog.i(TAG, "upgrading pkg " + res.pkg 2082 + " is ASEC-hosted -> AVAILABLE"); 2083 } 2084 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2085 ArrayList<String> pkgList = new ArrayList<>(1); 2086 pkgList.add(packageName); 2087 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2088 } 2089 } 2090 2091 // Work that needs to happen on first install within each user 2092 if (firstUserIds != null && firstUserIds.length > 0) { 2093 synchronized (mPackages) { 2094 for (int userId : firstUserIds) { 2095 // If this app is a browser and it's newly-installed for some 2096 // users, clear any default-browser state in those users. The 2097 // app's nature doesn't depend on the user, so we can just check 2098 // its browser nature in any user and generalize. 2099 if (packageIsBrowser(packageName, userId)) { 2100 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2101 } 2102 2103 // We may also need to apply pending (restored) runtime 2104 // permission grants within these users. 2105 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2106 } 2107 } 2108 } 2109 2110 if (allNewUsers && !update) { 2111 notifyPackageAdded(packageName); 2112 } 2113 2114 // Log current value of "unknown sources" setting 2115 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2116 getUnknownSourcesSettings()); 2117 2118 // Remove the replaced package's older resources safely now 2119 // We delete after a gc for applications on sdcard. 2120 if (res.removedInfo != null && res.removedInfo.args != null) { 2121 Runtime.getRuntime().gc(); 2122 synchronized (mInstallLock) { 2123 res.removedInfo.args.doPostDeleteLI(true); 2124 } 2125 } else { 2126 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2127 // and not block here. 2128 VMRuntime.getRuntime().requestConcurrentGC(); 2129 } 2130 2131 // Notify DexManager that the package was installed for new users. 2132 // The updated users should already be indexed and the package code paths 2133 // should not change. 2134 // Don't notify the manager for ephemeral apps as they are not expected to 2135 // survive long enough to benefit of background optimizations. 2136 for (int userId : firstUserIds) { 2137 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2138 // There's a race currently where some install events may interleave with an uninstall. 2139 // This can lead to package info being null (b/36642664). 2140 if (info != null) { 2141 mDexManager.notifyPackageInstalled(info, userId); 2142 } 2143 } 2144 } 2145 2146 // If someone is watching installs - notify them 2147 if (installObserver != null) { 2148 try { 2149 Bundle extras = extrasForInstallResult(res); 2150 installObserver.onPackageInstalled(res.name, res.returnCode, 2151 res.returnMsg, extras); 2152 } catch (RemoteException e) { 2153 Slog.i(TAG, "Observer no longer exists."); 2154 } 2155 } 2156 } 2157 2158 private StorageEventListener mStorageListener = new StorageEventListener() { 2159 @Override 2160 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2161 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2162 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2163 final String volumeUuid = vol.getFsUuid(); 2164 2165 // Clean up any users or apps that were removed or recreated 2166 // while this volume was missing 2167 sUserManager.reconcileUsers(volumeUuid); 2168 reconcileApps(volumeUuid); 2169 2170 // Clean up any install sessions that expired or were 2171 // cancelled while this volume was missing 2172 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2173 2174 loadPrivatePackages(vol); 2175 2176 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2177 unloadPrivatePackages(vol); 2178 } 2179 } 2180 } 2181 2182 @Override 2183 public void onVolumeForgotten(String fsUuid) { 2184 if (TextUtils.isEmpty(fsUuid)) { 2185 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2186 return; 2187 } 2188 2189 // Remove any apps installed on the forgotten volume 2190 synchronized (mPackages) { 2191 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2192 for (PackageSetting ps : packages) { 2193 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2194 deletePackageVersioned(new VersionedPackage(ps.name, 2195 PackageManager.VERSION_CODE_HIGHEST), 2196 new LegacyPackageDeleteObserver(null).getBinder(), 2197 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2198 // Try very hard to release any references to this package 2199 // so we don't risk the system server being killed due to 2200 // open FDs 2201 AttributeCache.instance().removePackage(ps.name); 2202 } 2203 2204 mSettings.onVolumeForgotten(fsUuid); 2205 mSettings.writeLPr(); 2206 } 2207 } 2208 }; 2209 2210 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2211 Bundle extras = null; 2212 switch (res.returnCode) { 2213 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2214 extras = new Bundle(); 2215 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2216 res.origPermission); 2217 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2218 res.origPackage); 2219 break; 2220 } 2221 case PackageManager.INSTALL_SUCCEEDED: { 2222 extras = new Bundle(); 2223 extras.putBoolean(Intent.EXTRA_REPLACING, 2224 res.removedInfo != null && res.removedInfo.removedPackage != null); 2225 break; 2226 } 2227 } 2228 return extras; 2229 } 2230 2231 void scheduleWriteSettingsLocked() { 2232 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2233 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2234 } 2235 } 2236 2237 void scheduleWritePackageListLocked(int userId) { 2238 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2239 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2240 msg.arg1 = userId; 2241 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2242 } 2243 } 2244 2245 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2246 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2247 scheduleWritePackageRestrictionsLocked(userId); 2248 } 2249 2250 void scheduleWritePackageRestrictionsLocked(int userId) { 2251 final int[] userIds = (userId == UserHandle.USER_ALL) 2252 ? sUserManager.getUserIds() : new int[]{userId}; 2253 for (int nextUserId : userIds) { 2254 if (!sUserManager.exists(nextUserId)) return; 2255 mDirtyUsers.add(nextUserId); 2256 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2257 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2258 } 2259 } 2260 } 2261 2262 public static PackageManagerService main(Context context, Installer installer, 2263 boolean factoryTest, boolean onlyCore) { 2264 // Self-check for initial settings. 2265 PackageManagerServiceCompilerMapping.checkProperties(); 2266 2267 PackageManagerService m = new PackageManagerService(context, installer, 2268 factoryTest, onlyCore); 2269 m.enableSystemUserPackages(); 2270 ServiceManager.addService("package", m); 2271 final PackageManagerNative pmn = m.new PackageManagerNative(); 2272 ServiceManager.addService("package_native", pmn); 2273 return m; 2274 } 2275 2276 private void enableSystemUserPackages() { 2277 if (!UserManager.isSplitSystemUser()) { 2278 return; 2279 } 2280 // For system user, enable apps based on the following conditions: 2281 // - app is whitelisted or belong to one of these groups: 2282 // -- system app which has no launcher icons 2283 // -- system app which has INTERACT_ACROSS_USERS permission 2284 // -- system IME app 2285 // - app is not in the blacklist 2286 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2287 Set<String> enableApps = new ArraySet<>(); 2288 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2289 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2290 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2291 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2292 enableApps.addAll(wlApps); 2293 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2294 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2295 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2296 enableApps.removeAll(blApps); 2297 Log.i(TAG, "Applications installed for system user: " + enableApps); 2298 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2299 UserHandle.SYSTEM); 2300 final int allAppsSize = allAps.size(); 2301 synchronized (mPackages) { 2302 for (int i = 0; i < allAppsSize; i++) { 2303 String pName = allAps.get(i); 2304 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2305 // Should not happen, but we shouldn't be failing if it does 2306 if (pkgSetting == null) { 2307 continue; 2308 } 2309 boolean install = enableApps.contains(pName); 2310 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2311 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2312 + " for system user"); 2313 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2314 } 2315 } 2316 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2317 } 2318 } 2319 2320 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2321 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2322 Context.DISPLAY_SERVICE); 2323 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2324 } 2325 2326 /** 2327 * Requests that files preopted on a secondary system partition be copied to the data partition 2328 * if possible. Note that the actual copying of the files is accomplished by init for security 2329 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2330 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2331 */ 2332 private static void requestCopyPreoptedFiles() { 2333 final int WAIT_TIME_MS = 100; 2334 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2335 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2336 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2337 // We will wait for up to 100 seconds. 2338 final long timeStart = SystemClock.uptimeMillis(); 2339 final long timeEnd = timeStart + 100 * 1000; 2340 long timeNow = timeStart; 2341 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2342 try { 2343 Thread.sleep(WAIT_TIME_MS); 2344 } catch (InterruptedException e) { 2345 // Do nothing 2346 } 2347 timeNow = SystemClock.uptimeMillis(); 2348 if (timeNow > timeEnd) { 2349 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2350 Slog.wtf(TAG, "cppreopt did not finish!"); 2351 break; 2352 } 2353 } 2354 2355 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2356 } 2357 } 2358 2359 public PackageManagerService(Context context, Installer installer, 2360 boolean factoryTest, boolean onlyCore) { 2361 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2362 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2363 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2364 SystemClock.uptimeMillis()); 2365 2366 if (mSdkVersion <= 0) { 2367 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2368 } 2369 2370 mContext = context; 2371 2372 mFactoryTest = factoryTest; 2373 mOnlyCore = onlyCore; 2374 mMetrics = new DisplayMetrics(); 2375 mInstaller = installer; 2376 2377 // Create sub-components that provide services / data. Order here is important. 2378 synchronized (mInstallLock) { 2379 synchronized (mPackages) { 2380 // Expose private service for system components to use. 2381 LocalServices.addService( 2382 PackageManagerInternal.class, new PackageManagerInternalImpl()); 2383 sUserManager = new UserManagerService(context, this, 2384 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2385 mPermissionManager = PermissionManagerService.create(context, 2386 new DefaultPermissionGrantedCallback() { 2387 @Override 2388 public void onDefaultRuntimePermissionsGranted(int userId) { 2389 synchronized(mPackages) { 2390 mSettings.onDefaultRuntimePermissionsGrantedLPr(userId); 2391 } 2392 } 2393 }, mPackages /*externalLock*/); 2394 mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy(); 2395 mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages); 2396 } 2397 } 2398 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2399 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2400 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2401 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2402 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2403 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2404 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2405 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2406 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2407 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2408 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2409 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2410 2411 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2412 if (separateProcesses != null && separateProcesses.length() > 0) { 2413 if ("*".equals(separateProcesses)) { 2414 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2415 mSeparateProcesses = null; 2416 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2417 } else { 2418 mDefParseFlags = 0; 2419 mSeparateProcesses = separateProcesses.split(","); 2420 Slog.w(TAG, "Running with debug.separate_processes: " 2421 + separateProcesses); 2422 } 2423 } else { 2424 mDefParseFlags = 0; 2425 mSeparateProcesses = null; 2426 } 2427 2428 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2429 "*dexopt*"); 2430 DexManager.Listener dexManagerListener = DexLogger.getListener(this, 2431 installer, mInstallLock); 2432 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock, 2433 dexManagerListener); 2434 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2435 2436 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2437 FgThread.get().getLooper()); 2438 2439 getDefaultDisplayMetrics(context, mMetrics); 2440 2441 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2442 SystemConfig systemConfig = SystemConfig.getInstance(); 2443 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2444 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2445 2446 mProtectedPackages = new ProtectedPackages(mContext); 2447 2448 synchronized (mInstallLock) { 2449 // writer 2450 synchronized (mPackages) { 2451 mHandlerThread = new ServiceThread(TAG, 2452 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2453 mHandlerThread.start(); 2454 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2455 mProcessLoggingHandler = new ProcessLoggingHandler(); 2456 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2457 mInstantAppRegistry = new InstantAppRegistry(this); 2458 2459 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2460 final int builtInLibCount = libConfig.size(); 2461 for (int i = 0; i < builtInLibCount; i++) { 2462 String name = libConfig.keyAt(i); 2463 String path = libConfig.valueAt(i); 2464 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2465 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2466 } 2467 2468 SELinuxMMAC.readInstallPolicy(); 2469 2470 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2471 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2472 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2473 2474 // Clean up orphaned packages for which the code path doesn't exist 2475 // and they are an update to a system app - caused by bug/32321269 2476 final int packageSettingCount = mSettings.mPackages.size(); 2477 for (int i = packageSettingCount - 1; i >= 0; i--) { 2478 PackageSetting ps = mSettings.mPackages.valueAt(i); 2479 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2480 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2481 mSettings.mPackages.removeAt(i); 2482 mSettings.enableSystemPackageLPw(ps.name); 2483 } 2484 } 2485 2486 if (mFirstBoot) { 2487 requestCopyPreoptedFiles(); 2488 } 2489 2490 String customResolverActivity = Resources.getSystem().getString( 2491 R.string.config_customResolverActivity); 2492 if (TextUtils.isEmpty(customResolverActivity)) { 2493 customResolverActivity = null; 2494 } else { 2495 mCustomResolverComponentName = ComponentName.unflattenFromString( 2496 customResolverActivity); 2497 } 2498 2499 long startTime = SystemClock.uptimeMillis(); 2500 2501 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2502 startTime); 2503 2504 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2505 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2506 2507 if (bootClassPath == null) { 2508 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2509 } 2510 2511 if (systemServerClassPath == null) { 2512 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2513 } 2514 2515 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2516 2517 final VersionInfo ver = mSettings.getInternalVersion(); 2518 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2519 if (mIsUpgrade) { 2520 logCriticalInfo(Log.INFO, 2521 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2522 } 2523 2524 // when upgrading from pre-M, promote system app permissions from install to runtime 2525 mPromoteSystemApps = 2526 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2527 2528 // When upgrading from pre-N, we need to handle package extraction like first boot, 2529 // as there is no profiling data available. 2530 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2531 2532 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2533 2534 // save off the names of pre-existing system packages prior to scanning; we don't 2535 // want to automatically grant runtime permissions for new system apps 2536 if (mPromoteSystemApps) { 2537 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2538 while (pkgSettingIter.hasNext()) { 2539 PackageSetting ps = pkgSettingIter.next(); 2540 if (isSystemApp(ps)) { 2541 mExistingSystemPackages.add(ps.name); 2542 } 2543 } 2544 } 2545 2546 mCacheDir = preparePackageParserCache(mIsUpgrade); 2547 2548 // Set flag to monitor and not change apk file paths when 2549 // scanning install directories. 2550 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2551 2552 if (mIsUpgrade || mFirstBoot) { 2553 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2554 } 2555 2556 // Collect vendor overlay packages. (Do this before scanning any apps.) 2557 // For security and version matching reason, only consider 2558 // overlay packages if they reside in the right directory. 2559 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), 2560 mDefParseFlags 2561 | PackageParser.PARSE_IS_SYSTEM_DIR, 2562 scanFlags 2563 | SCAN_AS_SYSTEM 2564 | SCAN_TRUSTED_OVERLAY, 2565 0); 2566 2567 mParallelPackageParserCallback.findStaticOverlayPackages(); 2568 2569 // Find base frameworks (resource packages without code). 2570 scanDirTracedLI(frameworkDir, 2571 mDefParseFlags 2572 | PackageParser.PARSE_IS_SYSTEM_DIR, 2573 scanFlags 2574 | SCAN_NO_DEX 2575 | SCAN_AS_SYSTEM 2576 | SCAN_AS_PRIVILEGED, 2577 0); 2578 2579 // Collected privileged system packages. 2580 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2581 scanDirTracedLI(privilegedAppDir, 2582 mDefParseFlags 2583 | PackageParser.PARSE_IS_SYSTEM_DIR, 2584 scanFlags 2585 | SCAN_AS_SYSTEM 2586 | SCAN_AS_PRIVILEGED, 2587 0); 2588 2589 // Collect ordinary system packages. 2590 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2591 scanDirTracedLI(systemAppDir, 2592 mDefParseFlags 2593 | PackageParser.PARSE_IS_SYSTEM_DIR, 2594 scanFlags 2595 | SCAN_AS_SYSTEM, 2596 0); 2597 2598 // Collected privileged vendor packages. 2599 File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), 2600 "priv-app"); 2601 try { 2602 privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile(); 2603 } catch (IOException e) { 2604 // failed to look up canonical path, continue with original one 2605 } 2606 scanDirTracedLI(privilegedVendorAppDir, 2607 mDefParseFlags 2608 | PackageParser.PARSE_IS_SYSTEM_DIR, 2609 scanFlags 2610 | SCAN_AS_SYSTEM 2611 | SCAN_AS_VENDOR 2612 | SCAN_AS_PRIVILEGED, 2613 0); 2614 2615 // Collect ordinary vendor packages. 2616 File vendorAppDir = new File(Environment.getVendorDirectory(), "app"); 2617 try { 2618 vendorAppDir = vendorAppDir.getCanonicalFile(); 2619 } catch (IOException e) { 2620 // failed to look up canonical path, continue with original one 2621 } 2622 scanDirTracedLI(vendorAppDir, 2623 mDefParseFlags 2624 | PackageParser.PARSE_IS_SYSTEM_DIR, 2625 scanFlags 2626 | SCAN_AS_SYSTEM 2627 | SCAN_AS_VENDOR, 2628 0); 2629 2630 // Collect all OEM packages. 2631 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2632 scanDirTracedLI(oemAppDir, 2633 mDefParseFlags 2634 | PackageParser.PARSE_IS_SYSTEM_DIR, 2635 scanFlags 2636 | SCAN_AS_SYSTEM 2637 | SCAN_AS_OEM, 2638 0); 2639 2640 // Prune any system packages that no longer exist. 2641 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>(); 2642 // Stub packages must either be replaced with full versions in the /data 2643 // partition or be disabled. 2644 final List<String> stubSystemApps = new ArrayList<>(); 2645 if (!mOnlyCore) { 2646 // do this first before mucking with mPackages for the "expecting better" case 2647 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator(); 2648 while (pkgIterator.hasNext()) { 2649 final PackageParser.Package pkg = pkgIterator.next(); 2650 if (pkg.isStub) { 2651 stubSystemApps.add(pkg.packageName); 2652 } 2653 } 2654 2655 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2656 while (psit.hasNext()) { 2657 PackageSetting ps = psit.next(); 2658 2659 /* 2660 * If this is not a system app, it can't be a 2661 * disable system app. 2662 */ 2663 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2664 continue; 2665 } 2666 2667 /* 2668 * If the package is scanned, it's not erased. 2669 */ 2670 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2671 if (scannedPkg != null) { 2672 /* 2673 * If the system app is both scanned and in the 2674 * disabled packages list, then it must have been 2675 * added via OTA. Remove it from the currently 2676 * scanned package so the previously user-installed 2677 * application can be scanned. 2678 */ 2679 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2680 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2681 + ps.name + "; removing system app. Last known codePath=" 2682 + ps.codePathString + ", installStatus=" + ps.installStatus 2683 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2684 + scannedPkg.getLongVersionCode()); 2685 removePackageLI(scannedPkg, true); 2686 mExpectingBetter.put(ps.name, ps.codePath); 2687 } 2688 2689 continue; 2690 } 2691 2692 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2693 psit.remove(); 2694 logCriticalInfo(Log.WARN, "System package " + ps.name 2695 + " no longer exists; it's data will be wiped"); 2696 // Actual deletion of code and data will be handled by later 2697 // reconciliation step 2698 } else { 2699 // we still have a disabled system package, but, it still might have 2700 // been removed. check the code path still exists and check there's 2701 // still a package. the latter can happen if an OTA keeps the same 2702 // code path, but, changes the package name. 2703 final PackageSetting disabledPs = 2704 mSettings.getDisabledSystemPkgLPr(ps.name); 2705 if (disabledPs.codePath == null || !disabledPs.codePath.exists() 2706 || disabledPs.pkg == null) { 2707if (REFACTOR_DEBUG) { 2708Slog.e("TODD", 2709 "Possibly deleted app: " + ps.dumpState_temp() 2710 + "; path: " + (disabledPs.codePath == null ? "<<NULL>>":disabledPs.codePath) 2711 + "; pkg: " + (disabledPs.pkg==null?"<<NULL>>":disabledPs.pkg.toString())); 2712} 2713 possiblyDeletedUpdatedSystemApps.add(ps.name); 2714 } 2715 } 2716 } 2717 } 2718 2719 //look for any incomplete package installations 2720 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2721 for (int i = 0; i < deletePkgsList.size(); i++) { 2722 // Actual deletion of code and data will be handled by later 2723 // reconciliation step 2724 final String packageName = deletePkgsList.get(i).name; 2725 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2726 synchronized (mPackages) { 2727 mSettings.removePackageLPw(packageName); 2728 } 2729 } 2730 2731 //delete tmp files 2732 deleteTempPackageFiles(); 2733 2734 final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get(); 2735 2736 // Remove any shared userIDs that have no associated packages 2737 mSettings.pruneSharedUsersLPw(); 2738 final long systemScanTime = SystemClock.uptimeMillis() - startTime; 2739 final int systemPackagesCount = mPackages.size(); 2740 Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime 2741 + " ms, packageCount: " + systemPackagesCount 2742 + " , timePerPackage: " 2743 + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount) 2744 + " , cached: " + cachedSystemApps); 2745 if (mIsUpgrade && systemPackagesCount > 0) { 2746 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time", 2747 ((int) systemScanTime) / systemPackagesCount); 2748 } 2749 if (!mOnlyCore) { 2750 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2751 SystemClock.uptimeMillis()); 2752 scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2753 2754 scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags 2755 | PackageParser.PARSE_FORWARD_LOCK, 2756 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2757 2758 // Remove disable package settings for updated system apps that were 2759 // removed via an OTA. If the update is no longer present, remove the 2760 // app completely. Otherwise, revoke their system privileges. 2761 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2762 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2763 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2764if (REFACTOR_DEBUG) { 2765Slog.e("TODD", 2766 "remove update; name: " + deletedAppName + ", exists? " + (deletedPkg != null)); 2767} 2768 final String msg; 2769 if (deletedPkg == null) { 2770 // should have found an update, but, we didn't; remove everything 2771 msg = "Updated system package " + deletedAppName 2772 + " no longer exists; removing its data"; 2773 // Actual deletion of code and data will be handled by later 2774 // reconciliation step 2775 } else { 2776 // found an update; revoke system privileges 2777 msg = "Updated system package + " + deletedAppName 2778 + " no longer exists; revoking system privileges"; 2779 2780 // Don't do anything if a stub is removed from the system image. If 2781 // we were to remove the uncompressed version from the /data partition, 2782 // this is where it'd be done. 2783 2784 final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2785 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2786 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2787 } 2788 logCriticalInfo(Log.WARN, msg); 2789 } 2790 2791 /* 2792 * Make sure all system apps that we expected to appear on 2793 * the userdata partition actually showed up. If they never 2794 * appeared, crawl back and revive the system version. 2795 */ 2796 for (int i = 0; i < mExpectingBetter.size(); i++) { 2797 final String packageName = mExpectingBetter.keyAt(i); 2798 if (!mPackages.containsKey(packageName)) { 2799 final File scanFile = mExpectingBetter.valueAt(i); 2800 2801 logCriticalInfo(Log.WARN, "Expected better " + packageName 2802 + " but never showed up; reverting to system"); 2803 2804 final @ParseFlags int reparseFlags; 2805 final @ScanFlags int rescanFlags; 2806 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2807 reparseFlags = 2808 mDefParseFlags | 2809 PackageParser.PARSE_IS_SYSTEM_DIR; 2810 rescanFlags = 2811 scanFlags 2812 | SCAN_AS_SYSTEM 2813 | SCAN_AS_PRIVILEGED; 2814 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2815 reparseFlags = 2816 mDefParseFlags | 2817 PackageParser.PARSE_IS_SYSTEM_DIR; 2818 rescanFlags = 2819 scanFlags 2820 | SCAN_AS_SYSTEM; 2821 } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) { 2822 reparseFlags = 2823 mDefParseFlags | 2824 PackageParser.PARSE_IS_SYSTEM_DIR; 2825 rescanFlags = 2826 scanFlags 2827 | SCAN_AS_SYSTEM 2828 | SCAN_AS_VENDOR 2829 | SCAN_AS_PRIVILEGED; 2830 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2831 reparseFlags = 2832 mDefParseFlags | 2833 PackageParser.PARSE_IS_SYSTEM_DIR; 2834 rescanFlags = 2835 scanFlags 2836 | SCAN_AS_SYSTEM 2837 | SCAN_AS_VENDOR; 2838 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2839 reparseFlags = 2840 mDefParseFlags | 2841 PackageParser.PARSE_IS_SYSTEM_DIR; 2842 rescanFlags = 2843 scanFlags 2844 | SCAN_AS_SYSTEM 2845 | SCAN_AS_OEM; 2846 } else { 2847 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2848 continue; 2849 } 2850 2851 mSettings.enableSystemPackageLPw(packageName); 2852 2853 try { 2854 scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null); 2855 } catch (PackageManagerException e) { 2856 Slog.e(TAG, "Failed to parse original system package: " 2857 + e.getMessage()); 2858 } 2859 } 2860 } 2861 2862 // Uncompress and install any stubbed system applications. 2863 // This must be done last to ensure all stubs are replaced or disabled. 2864 decompressSystemApplications(stubSystemApps, scanFlags); 2865 2866 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get() 2867 - cachedSystemApps; 2868 2869 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime; 2870 final int dataPackagesCount = mPackages.size() - systemPackagesCount; 2871 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime 2872 + " ms, packageCount: " + dataPackagesCount 2873 + " , timePerPackage: " 2874 + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) 2875 + " , cached: " + cachedNonSystemApps); 2876 if (mIsUpgrade && dataPackagesCount > 0) { 2877 MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time", 2878 ((int) dataScanTime) / dataPackagesCount); 2879 } 2880 } 2881 mExpectingBetter.clear(); 2882 2883 // Resolve the storage manager. 2884 mStorageManagerPackage = getStorageManagerPackageName(); 2885 2886 // Resolve protected action filters. Only the setup wizard is allowed to 2887 // have a high priority filter for these actions. 2888 mSetupWizardPackage = getSetupWizardPackageName(); 2889 if (mProtectedFilters.size() > 0) { 2890 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2891 Slog.i(TAG, "No setup wizard;" 2892 + " All protected intents capped to priority 0"); 2893 } 2894 for (ActivityIntentInfo filter : mProtectedFilters) { 2895 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2896 if (DEBUG_FILTERS) { 2897 Slog.i(TAG, "Found setup wizard;" 2898 + " allow priority " + filter.getPriority() + ";" 2899 + " package: " + filter.activity.info.packageName 2900 + " activity: " + filter.activity.className 2901 + " priority: " + filter.getPriority()); 2902 } 2903 // skip setup wizard; allow it to keep the high priority filter 2904 continue; 2905 } 2906 if (DEBUG_FILTERS) { 2907 Slog.i(TAG, "Protected action; cap priority to 0;" 2908 + " package: " + filter.activity.info.packageName 2909 + " activity: " + filter.activity.className 2910 + " origPrio: " + filter.getPriority()); 2911 } 2912 filter.setPriority(0); 2913 } 2914 } 2915 mDeferProtectedFilters = false; 2916 mProtectedFilters.clear(); 2917 2918 // Now that we know all of the shared libraries, update all clients to have 2919 // the correct library paths. 2920 updateAllSharedLibrariesLPw(null); 2921 2922 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2923 // NOTE: We ignore potential failures here during a system scan (like 2924 // the rest of the commands above) because there's precious little we 2925 // can do about it. A settings error is reported, though. 2926 final List<String> changedAbiCodePath = 2927 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2928 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 2929 for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) { 2930 final String codePathString = changedAbiCodePath.get(i); 2931 try { 2932 mInstaller.rmdex(codePathString, 2933 getDexCodeInstructionSet(getPreferredInstructionSet())); 2934 } catch (InstallerException ignored) { 2935 } 2936 } 2937 } 2938 } 2939 2940 // Now that we know all the packages we are keeping, 2941 // read and update their last usage times. 2942 mPackageUsage.read(mPackages); 2943 mCompilerStats.read(); 2944 2945 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2946 SystemClock.uptimeMillis()); 2947 Slog.i(TAG, "Time to scan packages: " 2948 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2949 + " seconds"); 2950 2951 // If the platform SDK has changed since the last time we booted, 2952 // we need to re-grant app permission to catch any new ones that 2953 // appear. This is really a hack, and means that apps can in some 2954 // cases get permissions that the user didn't initially explicitly 2955 // allow... it would be nice to have some better way to handle 2956 // this situation. 2957 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 2958 if (sdkUpdated) { 2959 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2960 + mSdkVersion + "; regranting permissions for internal storage"); 2961 } 2962 mPermissionManager.updateAllPermissions( 2963 StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(), 2964 mPermissionCallback); 2965 ver.sdkVersion = mSdkVersion; 2966 2967 // If this is the first boot or an update from pre-M, and it is a normal 2968 // boot, then we need to initialize the default preferred apps across 2969 // all defined users. 2970 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2971 for (UserInfo user : sUserManager.getUsers(true)) { 2972 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2973 applyFactoryDefaultBrowserLPw(user.id); 2974 primeDomainVerificationsLPw(user.id); 2975 } 2976 } 2977 2978 // Prepare storage for system user really early during boot, 2979 // since core system apps like SettingsProvider and SystemUI 2980 // can't wait for user to start 2981 final int storageFlags; 2982 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2983 storageFlags = StorageManager.FLAG_STORAGE_DE; 2984 } else { 2985 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2986 } 2987 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2988 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2989 true /* onlyCoreApps */); 2990 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2991 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync", 2992 Trace.TRACE_TAG_PACKAGE_MANAGER); 2993 traceLog.traceBegin("AppDataFixup"); 2994 try { 2995 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2996 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2997 } catch (InstallerException e) { 2998 Slog.w(TAG, "Trouble fixing GIDs", e); 2999 } 3000 traceLog.traceEnd(); 3001 3002 traceLog.traceBegin("AppDataPrepare"); 3003 if (deferPackages == null || deferPackages.isEmpty()) { 3004 return; 3005 } 3006 int count = 0; 3007 for (String pkgName : deferPackages) { 3008 PackageParser.Package pkg = null; 3009 synchronized (mPackages) { 3010 PackageSetting ps = mSettings.getPackageLPr(pkgName); 3011 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 3012 pkg = ps.pkg; 3013 } 3014 } 3015 if (pkg != null) { 3016 synchronized (mInstallLock) { 3017 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 3018 true /* maybeMigrateAppData */); 3019 } 3020 count++; 3021 } 3022 } 3023 traceLog.traceEnd(); 3024 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 3025 }, "prepareAppData"); 3026 3027 // If this is first boot after an OTA, and a normal boot, then 3028 // we need to clear code cache directories. 3029 // Note that we do *not* clear the application profiles. These remain valid 3030 // across OTAs and are used to drive profile verification (post OTA) and 3031 // profile compilation (without waiting to collect a fresh set of profiles). 3032 if (mIsUpgrade && !onlyCore) { 3033 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 3034 for (int i = 0; i < mSettings.mPackages.size(); i++) { 3035 final PackageSetting ps = mSettings.mPackages.valueAt(i); 3036 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 3037 // No apps are running this early, so no need to freeze 3038 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 3039 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 3040 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 3041 } 3042 } 3043 ver.fingerprint = Build.FINGERPRINT; 3044 } 3045 3046 checkDefaultBrowser(); 3047 3048 // clear only after permissions and other defaults have been updated 3049 mExistingSystemPackages.clear(); 3050 mPromoteSystemApps = false; 3051 3052 // All the changes are done during package scanning. 3053 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 3054 3055 // can downgrade to reader 3056 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 3057 mSettings.writeLPr(); 3058 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3059 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 3060 SystemClock.uptimeMillis()); 3061 3062 if (!mOnlyCore) { 3063 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 3064 mRequiredInstallerPackage = getRequiredInstallerLPr(); 3065 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 3066 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 3067 if (mIntentFilterVerifierComponent != null) { 3068 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 3069 mIntentFilterVerifierComponent); 3070 } else { 3071 mIntentFilterVerifier = null; 3072 } 3073 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3074 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 3075 SharedLibraryInfo.VERSION_UNDEFINED); 3076 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3077 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 3078 SharedLibraryInfo.VERSION_UNDEFINED); 3079 } else { 3080 mRequiredVerifierPackage = null; 3081 mRequiredInstallerPackage = null; 3082 mRequiredUninstallerPackage = null; 3083 mIntentFilterVerifierComponent = null; 3084 mIntentFilterVerifier = null; 3085 mServicesSystemSharedLibraryPackageName = null; 3086 mSharedSystemSharedLibraryPackageName = null; 3087 } 3088 3089 mInstallerService = new PackageInstallerService(context, this); 3090 mArtManagerService = new ArtManagerService(this, mInstaller, mInstallLock); 3091 final Pair<ComponentName, String> instantAppResolverComponent = 3092 getInstantAppResolverLPr(); 3093 if (instantAppResolverComponent != null) { 3094 if (DEBUG_EPHEMERAL) { 3095 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 3096 } 3097 mInstantAppResolverConnection = new EphemeralResolverConnection( 3098 mContext, instantAppResolverComponent.first, 3099 instantAppResolverComponent.second); 3100 mInstantAppResolverSettingsComponent = 3101 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 3102 } else { 3103 mInstantAppResolverConnection = null; 3104 mInstantAppResolverSettingsComponent = null; 3105 } 3106 updateInstantAppInstallerLocked(null); 3107 3108 // Read and update the usage of dex files. 3109 // Do this at the end of PM init so that all the packages have their 3110 // data directory reconciled. 3111 // At this point we know the code paths of the packages, so we can validate 3112 // the disk file and build the internal cache. 3113 // The usage file is expected to be small so loading and verifying it 3114 // should take a fairly small time compare to the other activities (e.g. package 3115 // scanning). 3116 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3117 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 3118 for (int userId : currentUserIds) { 3119 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3120 } 3121 mDexManager.load(userPackages); 3122 if (mIsUpgrade) { 3123 MetricsLogger.histogram(null, "ota_package_manager_init_time", 3124 (int) (SystemClock.uptimeMillis() - startTime)); 3125 } 3126 } // synchronized (mPackages) 3127 } // synchronized (mInstallLock) 3128 3129 // Now after opening every single application zip, make sure they 3130 // are all flushed. Not really needed, but keeps things nice and 3131 // tidy. 3132 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3133 Runtime.getRuntime().gc(); 3134 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3135 3136 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 3137 FallbackCategoryProvider.loadFallbacks(); 3138 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3139 3140 // The initial scanning above does many calls into installd while 3141 // holding the mPackages lock, but we're mostly interested in yelling 3142 // once we have a booted system. 3143 mInstaller.setWarnIfHeld(mPackages); 3144 3145 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3146 } 3147 3148 /** 3149 * Uncompress and install stub applications. 3150 * <p>In order to save space on the system partition, some applications are shipped in a 3151 * compressed form. In addition the compressed bits for the full application, the 3152 * system image contains a tiny stub comprised of only the Android manifest. 3153 * <p>During the first boot, attempt to uncompress and install the full application. If 3154 * the application can't be installed for any reason, disable the stub and prevent 3155 * uncompressing the full application during future boots. 3156 * <p>In order to forcefully attempt an installation of a full application, go to app 3157 * settings and enable the application. 3158 */ 3159 private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) { 3160 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3161 final String pkgName = stubSystemApps.get(i); 3162 // skip if the system package is already disabled 3163 if (mSettings.isDisabledSystemPackageLPr(pkgName)) { 3164 stubSystemApps.remove(i); 3165 continue; 3166 } 3167 // skip if the package isn't installed (?!); this should never happen 3168 final PackageParser.Package pkg = mPackages.get(pkgName); 3169 if (pkg == null) { 3170 stubSystemApps.remove(i); 3171 continue; 3172 } 3173 // skip if the package has been disabled by the user 3174 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3175 if (ps != null) { 3176 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM); 3177 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) { 3178 stubSystemApps.remove(i); 3179 continue; 3180 } 3181 } 3182 3183 if (DEBUG_COMPRESSION) { 3184 Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName); 3185 } 3186 3187 // uncompress the binary to its eventual destination on /data 3188 final File scanFile = decompressPackage(pkg); 3189 if (scanFile == null) { 3190 continue; 3191 } 3192 3193 // install the package to replace the stub on /system 3194 try { 3195 mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/); 3196 removePackageLI(pkg, true /*chatty*/); 3197 scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null); 3198 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 3199 UserHandle.USER_SYSTEM, "android"); 3200 stubSystemApps.remove(i); 3201 continue; 3202 } catch (PackageManagerException e) { 3203 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage()); 3204 } 3205 3206 // any failed attempt to install the package will be cleaned up later 3207 } 3208 3209 // disable any stub still left; these failed to install the full application 3210 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3211 final String pkgName = stubSystemApps.get(i); 3212 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3213 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 3214 UserHandle.USER_SYSTEM, "android"); 3215 logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName); 3216 } 3217 } 3218 3219 /** 3220 * Decompresses the given package on the system image onto 3221 * the /data partition. 3222 * @return The directory the package was decompressed into. Otherwise, {@code null}. 3223 */ 3224 private File decompressPackage(PackageParser.Package pkg) { 3225 final File[] compressedFiles = getCompressedFiles(pkg.codePath); 3226 if (compressedFiles == null || compressedFiles.length == 0) { 3227 if (DEBUG_COMPRESSION) { 3228 Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath); 3229 } 3230 return null; 3231 } 3232 final File dstCodePath = 3233 getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName); 3234 int ret = PackageManager.INSTALL_SUCCEEDED; 3235 try { 3236 Os.mkdir(dstCodePath.getAbsolutePath(), 0755); 3237 Os.chmod(dstCodePath.getAbsolutePath(), 0755); 3238 for (File srcFile : compressedFiles) { 3239 final String srcFileName = srcFile.getName(); 3240 final String dstFileName = srcFileName.substring( 3241 0, srcFileName.length() - COMPRESSED_EXTENSION.length()); 3242 final File dstFile = new File(dstCodePath, dstFileName); 3243 ret = decompressFile(srcFile, dstFile); 3244 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3245 logCriticalInfo(Log.ERROR, "Failed to decompress" 3246 + "; pkg: " + pkg.packageName 3247 + ", file: " + dstFileName); 3248 break; 3249 } 3250 } 3251 } catch (ErrnoException e) { 3252 logCriticalInfo(Log.ERROR, "Failed to decompress" 3253 + "; pkg: " + pkg.packageName 3254 + ", err: " + e.errno); 3255 } 3256 if (ret == PackageManager.INSTALL_SUCCEEDED) { 3257 final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME); 3258 NativeLibraryHelper.Handle handle = null; 3259 try { 3260 handle = NativeLibraryHelper.Handle.create(dstCodePath); 3261 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 3262 null /*abiOverride*/); 3263 } catch (IOException e) { 3264 logCriticalInfo(Log.ERROR, "Failed to extract native libraries" 3265 + "; pkg: " + pkg.packageName); 3266 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3267 } finally { 3268 IoUtils.closeQuietly(handle); 3269 } 3270 } 3271 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3272 if (dstCodePath == null || !dstCodePath.exists()) { 3273 return null; 3274 } 3275 removeCodePathLI(dstCodePath); 3276 return null; 3277 } 3278 3279 return dstCodePath; 3280 } 3281 3282 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3283 // we're only interested in updating the installer appliction when 1) it's not 3284 // already set or 2) the modified package is the installer 3285 if (mInstantAppInstallerActivity != null 3286 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3287 .equals(modifiedPackage)) { 3288 return; 3289 } 3290 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3291 } 3292 3293 private static File preparePackageParserCache(boolean isUpgrade) { 3294 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3295 return null; 3296 } 3297 3298 // Disable package parsing on eng builds to allow for faster incremental development. 3299 if (Build.IS_ENG) { 3300 return null; 3301 } 3302 3303 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3304 Slog.i(TAG, "Disabling package parser cache due to system property."); 3305 return null; 3306 } 3307 3308 // The base directory for the package parser cache lives under /data/system/. 3309 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3310 "package_cache"); 3311 if (cacheBaseDir == null) { 3312 return null; 3313 } 3314 3315 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3316 // This also serves to "GC" unused entries when the package cache version changes (which 3317 // can only happen during upgrades). 3318 if (isUpgrade) { 3319 FileUtils.deleteContents(cacheBaseDir); 3320 } 3321 3322 3323 // Return the versioned package cache directory. This is something like 3324 // "/data/system/package_cache/1" 3325 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3326 3327 // The following is a workaround to aid development on non-numbered userdebug 3328 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3329 // the system partition is newer. 3330 // 3331 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3332 // that starts with "eng." to signify that this is an engineering build and not 3333 // destined for release. 3334 if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3335 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3336 3337 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3338 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3339 // in general and should not be used for production changes. In this specific case, 3340 // we know that they will work. 3341 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3342 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3343 FileUtils.deleteContents(cacheBaseDir); 3344 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3345 } 3346 } 3347 3348 return cacheDir; 3349 } 3350 3351 @Override 3352 public boolean isFirstBoot() { 3353 // allow instant applications 3354 return mFirstBoot; 3355 } 3356 3357 @Override 3358 public boolean isOnlyCoreApps() { 3359 // allow instant applications 3360 return mOnlyCore; 3361 } 3362 3363 @Override 3364 public boolean isUpgrade() { 3365 // allow instant applications 3366 // The system property allows testing ota flow when upgraded to the same image. 3367 return mIsUpgrade || SystemProperties.getBoolean( 3368 "persist.pm.mock-upgrade", false /* default */); 3369 } 3370 3371 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3372 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3373 3374 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3375 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3376 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3377 if (matches.size() == 1) { 3378 return matches.get(0).getComponentInfo().packageName; 3379 } else if (matches.size() == 0) { 3380 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3381 return null; 3382 } 3383 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3384 } 3385 3386 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3387 synchronized (mPackages) { 3388 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3389 if (libraryEntry == null) { 3390 throw new IllegalStateException("Missing required shared library:" + name); 3391 } 3392 return libraryEntry.apk; 3393 } 3394 } 3395 3396 private @NonNull String getRequiredInstallerLPr() { 3397 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3398 intent.addCategory(Intent.CATEGORY_DEFAULT); 3399 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3400 3401 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3402 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3403 UserHandle.USER_SYSTEM); 3404 if (matches.size() == 1) { 3405 ResolveInfo resolveInfo = matches.get(0); 3406 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3407 throw new RuntimeException("The installer must be a privileged app"); 3408 } 3409 return matches.get(0).getComponentInfo().packageName; 3410 } else { 3411 throw new RuntimeException("There must be exactly one installer; found " + matches); 3412 } 3413 } 3414 3415 private @NonNull String getRequiredUninstallerLPr() { 3416 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3417 intent.addCategory(Intent.CATEGORY_DEFAULT); 3418 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3419 3420 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3421 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3422 UserHandle.USER_SYSTEM); 3423 if (resolveInfo == null || 3424 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3425 throw new RuntimeException("There must be exactly one uninstaller; found " 3426 + resolveInfo); 3427 } 3428 return resolveInfo.getComponentInfo().packageName; 3429 } 3430 3431 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3432 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3433 3434 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3435 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3436 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3437 ResolveInfo best = null; 3438 final int N = matches.size(); 3439 for (int i = 0; i < N; i++) { 3440 final ResolveInfo cur = matches.get(i); 3441 final String packageName = cur.getComponentInfo().packageName; 3442 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3443 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3444 continue; 3445 } 3446 3447 if (best == null || cur.priority > best.priority) { 3448 best = cur; 3449 } 3450 } 3451 3452 if (best != null) { 3453 return best.getComponentInfo().getComponentName(); 3454 } 3455 Slog.w(TAG, "Intent filter verifier not found"); 3456 return null; 3457 } 3458 3459 @Override 3460 public @Nullable ComponentName getInstantAppResolverComponent() { 3461 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3462 return null; 3463 } 3464 synchronized (mPackages) { 3465 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3466 if (instantAppResolver == null) { 3467 return null; 3468 } 3469 return instantAppResolver.first; 3470 } 3471 } 3472 3473 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3474 final String[] packageArray = 3475 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3476 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3477 if (DEBUG_EPHEMERAL) { 3478 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3479 } 3480 return null; 3481 } 3482 3483 final int callingUid = Binder.getCallingUid(); 3484 final int resolveFlags = 3485 MATCH_DIRECT_BOOT_AWARE 3486 | MATCH_DIRECT_BOOT_UNAWARE 3487 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3488 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3489 final Intent resolverIntent = new Intent(actionName); 3490 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3491 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3492 // temporarily look for the old action 3493 if (resolvers.size() == 0) { 3494 if (DEBUG_EPHEMERAL) { 3495 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3496 } 3497 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE; 3498 resolverIntent.setAction(actionName); 3499 resolvers = queryIntentServicesInternal(resolverIntent, null, 3500 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3501 } 3502 final int N = resolvers.size(); 3503 if (N == 0) { 3504 if (DEBUG_EPHEMERAL) { 3505 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3506 } 3507 return null; 3508 } 3509 3510 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3511 for (int i = 0; i < N; i++) { 3512 final ResolveInfo info = resolvers.get(i); 3513 3514 if (info.serviceInfo == null) { 3515 continue; 3516 } 3517 3518 final String packageName = info.serviceInfo.packageName; 3519 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3520 if (DEBUG_EPHEMERAL) { 3521 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3522 + " pkg: " + packageName + ", info:" + info); 3523 } 3524 continue; 3525 } 3526 3527 if (DEBUG_EPHEMERAL) { 3528 Slog.v(TAG, "Ephemeral resolver found;" 3529 + " pkg: " + packageName + ", info:" + info); 3530 } 3531 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3532 } 3533 if (DEBUG_EPHEMERAL) { 3534 Slog.v(TAG, "Ephemeral resolver NOT found"); 3535 } 3536 return null; 3537 } 3538 3539 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3540 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3541 intent.addCategory(Intent.CATEGORY_DEFAULT); 3542 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3543 3544 final int resolveFlags = 3545 MATCH_DIRECT_BOOT_AWARE 3546 | MATCH_DIRECT_BOOT_UNAWARE 3547 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3548 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3549 resolveFlags, UserHandle.USER_SYSTEM); 3550 // temporarily look for the old action 3551 if (matches.isEmpty()) { 3552 if (DEBUG_EPHEMERAL) { 3553 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3554 } 3555 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3556 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3557 resolveFlags, UserHandle.USER_SYSTEM); 3558 } 3559 Iterator<ResolveInfo> iter = matches.iterator(); 3560 while (iter.hasNext()) { 3561 final ResolveInfo rInfo = iter.next(); 3562 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3563 if (ps != null) { 3564 final PermissionsState permissionsState = ps.getPermissionsState(); 3565 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3566 continue; 3567 } 3568 } 3569 iter.remove(); 3570 } 3571 if (matches.size() == 0) { 3572 return null; 3573 } else if (matches.size() == 1) { 3574 return (ActivityInfo) matches.get(0).getComponentInfo(); 3575 } else { 3576 throw new RuntimeException( 3577 "There must be at most one ephemeral installer; found " + matches); 3578 } 3579 } 3580 3581 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3582 @NonNull ComponentName resolver) { 3583 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3584 .addCategory(Intent.CATEGORY_DEFAULT) 3585 .setPackage(resolver.getPackageName()); 3586 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3587 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3588 UserHandle.USER_SYSTEM); 3589 // temporarily look for the old action 3590 if (matches.isEmpty()) { 3591 if (DEBUG_EPHEMERAL) { 3592 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3593 } 3594 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3595 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3596 UserHandle.USER_SYSTEM); 3597 } 3598 if (matches.isEmpty()) { 3599 return null; 3600 } 3601 return matches.get(0).getComponentInfo().getComponentName(); 3602 } 3603 3604 private void primeDomainVerificationsLPw(int userId) { 3605 if (DEBUG_DOMAIN_VERIFICATION) { 3606 Slog.d(TAG, "Priming domain verifications in user " + userId); 3607 } 3608 3609 SystemConfig systemConfig = SystemConfig.getInstance(); 3610 ArraySet<String> packages = systemConfig.getLinkedApps(); 3611 3612 for (String packageName : packages) { 3613 PackageParser.Package pkg = mPackages.get(packageName); 3614 if (pkg != null) { 3615 if (!pkg.isSystem()) { 3616 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3617 continue; 3618 } 3619 3620 ArraySet<String> domains = null; 3621 for (PackageParser.Activity a : pkg.activities) { 3622 for (ActivityIntentInfo filter : a.intents) { 3623 if (hasValidDomains(filter)) { 3624 if (domains == null) { 3625 domains = new ArraySet<String>(); 3626 } 3627 domains.addAll(filter.getHostsList()); 3628 } 3629 } 3630 } 3631 3632 if (domains != null && domains.size() > 0) { 3633 if (DEBUG_DOMAIN_VERIFICATION) { 3634 Slog.v(TAG, " + " + packageName); 3635 } 3636 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3637 // state w.r.t. the formal app-linkage "no verification attempted" state; 3638 // and then 'always' in the per-user state actually used for intent resolution. 3639 final IntentFilterVerificationInfo ivi; 3640 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3641 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3642 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3643 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3644 } else { 3645 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3646 + "' does not handle web links"); 3647 } 3648 } else { 3649 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3650 } 3651 } 3652 3653 scheduleWritePackageRestrictionsLocked(userId); 3654 scheduleWriteSettingsLocked(); 3655 } 3656 3657 private void applyFactoryDefaultBrowserLPw(int userId) { 3658 // The default browser app's package name is stored in a string resource, 3659 // with a product-specific overlay used for vendor customization. 3660 String browserPkg = mContext.getResources().getString( 3661 com.android.internal.R.string.default_browser); 3662 if (!TextUtils.isEmpty(browserPkg)) { 3663 // non-empty string => required to be a known package 3664 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3665 if (ps == null) { 3666 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3667 browserPkg = null; 3668 } else { 3669 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3670 } 3671 } 3672 3673 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3674 // default. If there's more than one, just leave everything alone. 3675 if (browserPkg == null) { 3676 calculateDefaultBrowserLPw(userId); 3677 } 3678 } 3679 3680 private void calculateDefaultBrowserLPw(int userId) { 3681 List<String> allBrowsers = resolveAllBrowserApps(userId); 3682 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3683 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3684 } 3685 3686 private List<String> resolveAllBrowserApps(int userId) { 3687 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3688 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3689 PackageManager.MATCH_ALL, userId); 3690 3691 final int count = list.size(); 3692 List<String> result = new ArrayList<String>(count); 3693 for (int i=0; i<count; i++) { 3694 ResolveInfo info = list.get(i); 3695 if (info.activityInfo == null 3696 || !info.handleAllWebDataURI 3697 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3698 || result.contains(info.activityInfo.packageName)) { 3699 continue; 3700 } 3701 result.add(info.activityInfo.packageName); 3702 } 3703 3704 return result; 3705 } 3706 3707 private boolean packageIsBrowser(String packageName, int userId) { 3708 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3709 PackageManager.MATCH_ALL, userId); 3710 final int N = list.size(); 3711 for (int i = 0; i < N; i++) { 3712 ResolveInfo info = list.get(i); 3713 if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) { 3714 return true; 3715 } 3716 } 3717 return false; 3718 } 3719 3720 private void checkDefaultBrowser() { 3721 final int myUserId = UserHandle.myUserId(); 3722 final String packageName = getDefaultBrowserPackageName(myUserId); 3723 if (packageName != null) { 3724 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3725 if (info == null) { 3726 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3727 synchronized (mPackages) { 3728 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3729 } 3730 } 3731 } 3732 } 3733 3734 @Override 3735 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3736 throws RemoteException { 3737 try { 3738 return super.onTransact(code, data, reply, flags); 3739 } catch (RuntimeException e) { 3740 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3741 Slog.wtf(TAG, "Package Manager Crash", e); 3742 } 3743 throw e; 3744 } 3745 } 3746 3747 static int[] appendInts(int[] cur, int[] add) { 3748 if (add == null) return cur; 3749 if (cur == null) return add; 3750 final int N = add.length; 3751 for (int i=0; i<N; i++) { 3752 cur = appendInt(cur, add[i]); 3753 } 3754 return cur; 3755 } 3756 3757 /** 3758 * Returns whether or not a full application can see an instant application. 3759 * <p> 3760 * Currently, there are three cases in which this can occur: 3761 * <ol> 3762 * <li>The calling application is a "special" process. Special processes 3763 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 3764 * <li>The calling application has the permission 3765 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 3766 * <li>The calling application is the default launcher on the 3767 * system partition.</li> 3768 * </ol> 3769 */ 3770 private boolean canViewInstantApps(int callingUid, int userId) { 3771 if (callingUid < Process.FIRST_APPLICATION_UID) { 3772 return true; 3773 } 3774 if (mContext.checkCallingOrSelfPermission( 3775 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3776 return true; 3777 } 3778 if (mContext.checkCallingOrSelfPermission( 3779 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3780 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3781 if (homeComponent != null 3782 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3783 return true; 3784 } 3785 } 3786 return false; 3787 } 3788 3789 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3790 if (!sUserManager.exists(userId)) return null; 3791 if (ps == null) { 3792 return null; 3793 } 3794 PackageParser.Package p = ps.pkg; 3795 if (p == null) { 3796 return null; 3797 } 3798 final int callingUid = Binder.getCallingUid(); 3799 // Filter out ephemeral app metadata: 3800 // * The system/shell/root can see metadata for any app 3801 // * An installed app can see metadata for 1) other installed apps 3802 // and 2) ephemeral apps that have explicitly interacted with it 3803 // * Ephemeral apps can only see their own data and exposed installed apps 3804 // * Holding a signature permission allows seeing instant apps 3805 if (filterAppAccessLPr(ps, callingUid, userId)) { 3806 return null; 3807 } 3808 3809 final PermissionsState permissionsState = ps.getPermissionsState(); 3810 3811 // Compute GIDs only if requested 3812 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3813 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3814 // Compute granted permissions only if package has requested permissions 3815 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3816 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3817 final PackageUserState state = ps.readUserState(userId); 3818 3819 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3820 && ps.isSystem()) { 3821 flags |= MATCH_ANY_USER; 3822 } 3823 3824 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3825 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3826 3827 if (packageInfo == null) { 3828 return null; 3829 } 3830 3831 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3832 resolveExternalPackageNameLPr(p); 3833 3834 return packageInfo; 3835 } 3836 3837 @Override 3838 public void checkPackageStartable(String packageName, int userId) { 3839 final int callingUid = Binder.getCallingUid(); 3840 if (getInstantAppPackageName(callingUid) != null) { 3841 throw new SecurityException("Instant applications don't have access to this method"); 3842 } 3843 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3844 synchronized (mPackages) { 3845 final PackageSetting ps = mSettings.mPackages.get(packageName); 3846 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 3847 throw new SecurityException("Package " + packageName + " was not found!"); 3848 } 3849 3850 if (!ps.getInstalled(userId)) { 3851 throw new SecurityException( 3852 "Package " + packageName + " was not installed for user " + userId + "!"); 3853 } 3854 3855 if (mSafeMode && !ps.isSystem()) { 3856 throw new SecurityException("Package " + packageName + " not a system app!"); 3857 } 3858 3859 if (mFrozenPackages.contains(packageName)) { 3860 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3861 } 3862 3863 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) { 3864 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3865 } 3866 } 3867 } 3868 3869 @Override 3870 public boolean isPackageAvailable(String packageName, int userId) { 3871 if (!sUserManager.exists(userId)) return false; 3872 final int callingUid = Binder.getCallingUid(); 3873 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 3874 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 3875 synchronized (mPackages) { 3876 PackageParser.Package p = mPackages.get(packageName); 3877 if (p != null) { 3878 final PackageSetting ps = (PackageSetting) p.mExtras; 3879 if (filterAppAccessLPr(ps, callingUid, userId)) { 3880 return false; 3881 } 3882 if (ps != null) { 3883 final PackageUserState state = ps.readUserState(userId); 3884 if (state != null) { 3885 return PackageParser.isAvailable(state); 3886 } 3887 } 3888 } 3889 } 3890 return false; 3891 } 3892 3893 @Override 3894 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3895 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3896 flags, Binder.getCallingUid(), userId); 3897 } 3898 3899 @Override 3900 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3901 int flags, int userId) { 3902 return getPackageInfoInternal(versionedPackage.getPackageName(), 3903 versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId); 3904 } 3905 3906 /** 3907 * Important: The provided filterCallingUid is used exclusively to filter out packages 3908 * that can be seen based on user state. It's typically the original caller uid prior 3909 * to clearing. Because it can only be provided by trusted code, it's value can be 3910 * trusted and will be used as-is; unlike userId which will be validated by this method. 3911 */ 3912 private PackageInfo getPackageInfoInternal(String packageName, long versionCode, 3913 int flags, int filterCallingUid, int userId) { 3914 if (!sUserManager.exists(userId)) return null; 3915 flags = updateFlagsForPackage(flags, userId, packageName); 3916 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 3917 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3918 3919 // reader 3920 synchronized (mPackages) { 3921 // Normalize package name to handle renamed packages and static libs 3922 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3923 3924 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3925 if (matchFactoryOnly) { 3926 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3927 if (ps != null) { 3928 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3929 return null; 3930 } 3931 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3932 return null; 3933 } 3934 return generatePackageInfo(ps, flags, userId); 3935 } 3936 } 3937 3938 PackageParser.Package p = mPackages.get(packageName); 3939 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3940 return null; 3941 } 3942 if (DEBUG_PACKAGE_INFO) 3943 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3944 if (p != null) { 3945 final PackageSetting ps = (PackageSetting) p.mExtras; 3946 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3947 return null; 3948 } 3949 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 3950 return null; 3951 } 3952 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3953 } 3954 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3955 final PackageSetting ps = mSettings.mPackages.get(packageName); 3956 if (ps == null) return null; 3957 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3958 return null; 3959 } 3960 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3961 return null; 3962 } 3963 return generatePackageInfo(ps, flags, userId); 3964 } 3965 } 3966 return null; 3967 } 3968 3969 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 3970 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 3971 return true; 3972 } 3973 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 3974 return true; 3975 } 3976 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 3977 return true; 3978 } 3979 return false; 3980 } 3981 3982 private boolean isComponentVisibleToInstantApp( 3983 @Nullable ComponentName component, @ComponentType int type) { 3984 if (type == TYPE_ACTIVITY) { 3985 final PackageParser.Activity activity = mActivities.mActivities.get(component); 3986 return activity != null 3987 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3988 : false; 3989 } else if (type == TYPE_RECEIVER) { 3990 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 3991 return activity != null 3992 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3993 : false; 3994 } else if (type == TYPE_SERVICE) { 3995 final PackageParser.Service service = mServices.mServices.get(component); 3996 return service != null 3997 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3998 : false; 3999 } else if (type == TYPE_PROVIDER) { 4000 final PackageParser.Provider provider = mProviders.mProviders.get(component); 4001 return provider != null 4002 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4003 : false; 4004 } else if (type == TYPE_UNKNOWN) { 4005 return isComponentVisibleToInstantApp(component); 4006 } 4007 return false; 4008 } 4009 4010 /** 4011 * Returns whether or not access to the application should be filtered. 4012 * <p> 4013 * Access may be limited based upon whether the calling or target applications 4014 * are instant applications. 4015 * 4016 * @see #canAccessInstantApps(int) 4017 */ 4018 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 4019 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 4020 // if we're in an isolated process, get the real calling UID 4021 if (Process.isIsolated(callingUid)) { 4022 callingUid = mIsolatedOwners.get(callingUid); 4023 } 4024 final String instantAppPkgName = getInstantAppPackageName(callingUid); 4025 final boolean callerIsInstantApp = instantAppPkgName != null; 4026 if (ps == null) { 4027 if (callerIsInstantApp) { 4028 // pretend the application exists, but, needs to be filtered 4029 return true; 4030 } 4031 return false; 4032 } 4033 // if the target and caller are the same application, don't filter 4034 if (isCallerSameApp(ps.name, callingUid)) { 4035 return false; 4036 } 4037 if (callerIsInstantApp) { 4038 // request for a specific component; if it hasn't been explicitly exposed, filter 4039 if (component != null) { 4040 return !isComponentVisibleToInstantApp(component, componentType); 4041 } 4042 // request for application; if no components have been explicitly exposed, filter 4043 return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps; 4044 } 4045 if (ps.getInstantApp(userId)) { 4046 // caller can see all components of all instant applications, don't filter 4047 if (canViewInstantApps(callingUid, userId)) { 4048 return false; 4049 } 4050 // request for a specific instant application component, filter 4051 if (component != null) { 4052 return true; 4053 } 4054 // request for an instant application; if the caller hasn't been granted access, filter 4055 return !mInstantAppRegistry.isInstantAccessGranted( 4056 userId, UserHandle.getAppId(callingUid), ps.appId); 4057 } 4058 return false; 4059 } 4060 4061 /** 4062 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 4063 */ 4064 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 4065 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 4066 } 4067 4068 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 4069 int flags) { 4070 // Callers can access only the libs they depend on, otherwise they need to explicitly 4071 // ask for the shared libraries given the caller is allowed to access all static libs. 4072 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 4073 // System/shell/root get to see all static libs 4074 final int appId = UserHandle.getAppId(uid); 4075 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 4076 || appId == Process.ROOT_UID) { 4077 return false; 4078 } 4079 } 4080 4081 // No package means no static lib as it is always on internal storage 4082 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4083 return false; 4084 } 4085 4086 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 4087 ps.pkg.staticSharedLibVersion); 4088 if (libEntry == null) { 4089 return false; 4090 } 4091 4092 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 4093 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 4094 if (uidPackageNames == null) { 4095 return true; 4096 } 4097 4098 for (String uidPackageName : uidPackageNames) { 4099 if (ps.name.equals(uidPackageName)) { 4100 return false; 4101 } 4102 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 4103 if (uidPs != null) { 4104 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 4105 libEntry.info.getName()); 4106 if (index < 0) { 4107 continue; 4108 } 4109 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) { 4110 return false; 4111 } 4112 } 4113 } 4114 return true; 4115 } 4116 4117 @Override 4118 public String[] currentToCanonicalPackageNames(String[] names) { 4119 final int callingUid = Binder.getCallingUid(); 4120 if (getInstantAppPackageName(callingUid) != null) { 4121 return names; 4122 } 4123 final String[] out = new String[names.length]; 4124 // reader 4125 synchronized (mPackages) { 4126 final int callingUserId = UserHandle.getUserId(callingUid); 4127 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4128 for (int i=names.length-1; i>=0; i--) { 4129 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4130 boolean translateName = false; 4131 if (ps != null && ps.realName != null) { 4132 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 4133 translateName = !targetIsInstantApp 4134 || canViewInstantApps 4135 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4136 UserHandle.getAppId(callingUid), ps.appId); 4137 } 4138 out[i] = translateName ? ps.realName : names[i]; 4139 } 4140 } 4141 return out; 4142 } 4143 4144 @Override 4145 public String[] canonicalToCurrentPackageNames(String[] names) { 4146 final int callingUid = Binder.getCallingUid(); 4147 if (getInstantAppPackageName(callingUid) != null) { 4148 return names; 4149 } 4150 final String[] out = new String[names.length]; 4151 // reader 4152 synchronized (mPackages) { 4153 final int callingUserId = UserHandle.getUserId(callingUid); 4154 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4155 for (int i=names.length-1; i>=0; i--) { 4156 final String cur = mSettings.getRenamedPackageLPr(names[i]); 4157 boolean translateName = false; 4158 if (cur != null) { 4159 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4160 final boolean targetIsInstantApp = 4161 ps != null && ps.getInstantApp(callingUserId); 4162 translateName = !targetIsInstantApp 4163 || canViewInstantApps 4164 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4165 UserHandle.getAppId(callingUid), ps.appId); 4166 } 4167 out[i] = translateName ? cur : names[i]; 4168 } 4169 } 4170 return out; 4171 } 4172 4173 @Override 4174 public int getPackageUid(String packageName, int flags, int userId) { 4175 if (!sUserManager.exists(userId)) return -1; 4176 final int callingUid = Binder.getCallingUid(); 4177 flags = updateFlagsForPackage(flags, userId, packageName); 4178 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4179 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 4180 4181 // reader 4182 synchronized (mPackages) { 4183 final PackageParser.Package p = mPackages.get(packageName); 4184 if (p != null && p.isMatch(flags)) { 4185 PackageSetting ps = (PackageSetting) p.mExtras; 4186 if (filterAppAccessLPr(ps, callingUid, userId)) { 4187 return -1; 4188 } 4189 return UserHandle.getUid(userId, p.applicationInfo.uid); 4190 } 4191 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4192 final PackageSetting ps = mSettings.mPackages.get(packageName); 4193 if (ps != null && ps.isMatch(flags) 4194 && !filterAppAccessLPr(ps, callingUid, userId)) { 4195 return UserHandle.getUid(userId, ps.appId); 4196 } 4197 } 4198 } 4199 4200 return -1; 4201 } 4202 4203 @Override 4204 public int[] getPackageGids(String packageName, int flags, int userId) { 4205 if (!sUserManager.exists(userId)) return null; 4206 final int callingUid = Binder.getCallingUid(); 4207 flags = updateFlagsForPackage(flags, userId, packageName); 4208 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4209 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 4210 4211 // reader 4212 synchronized (mPackages) { 4213 final PackageParser.Package p = mPackages.get(packageName); 4214 if (p != null && p.isMatch(flags)) { 4215 PackageSetting ps = (PackageSetting) p.mExtras; 4216 if (filterAppAccessLPr(ps, callingUid, userId)) { 4217 return null; 4218 } 4219 // TODO: Shouldn't this be checking for package installed state for userId and 4220 // return null? 4221 return ps.getPermissionsState().computeGids(userId); 4222 } 4223 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4224 final PackageSetting ps = mSettings.mPackages.get(packageName); 4225 if (ps != null && ps.isMatch(flags) 4226 && !filterAppAccessLPr(ps, callingUid, userId)) { 4227 return ps.getPermissionsState().computeGids(userId); 4228 } 4229 } 4230 } 4231 4232 return null; 4233 } 4234 4235 @Override 4236 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4237 return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid()); 4238 } 4239 4240 @Override 4241 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName, 4242 int flags) { 4243 final List<PermissionInfo> permissionList = 4244 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()); 4245 return (permissionList == null) ? null : new ParceledListSlice<>(permissionList); 4246 } 4247 4248 @Override 4249 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) { 4250 return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid()); 4251 } 4252 4253 @Override 4254 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4255 final List<PermissionGroupInfo> permissionList = 4256 mPermissionManager.getAllPermissionGroups(flags, getCallingUid()); 4257 return (permissionList == null) 4258 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList); 4259 } 4260 4261 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4262 int filterCallingUid, int userId) { 4263 if (!sUserManager.exists(userId)) return null; 4264 PackageSetting ps = mSettings.mPackages.get(packageName); 4265 if (ps != null) { 4266 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4267 return null; 4268 } 4269 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4270 return null; 4271 } 4272 if (ps.pkg == null) { 4273 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4274 if (pInfo != null) { 4275 return pInfo.applicationInfo; 4276 } 4277 return null; 4278 } 4279 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4280 ps.readUserState(userId), userId); 4281 if (ai != null) { 4282 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4283 } 4284 return ai; 4285 } 4286 return null; 4287 } 4288 4289 @Override 4290 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4291 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4292 } 4293 4294 /** 4295 * Important: The provided filterCallingUid is used exclusively to filter out applications 4296 * that can be seen based on user state. It's typically the original caller uid prior 4297 * to clearing. Because it can only be provided by trusted code, it's value can be 4298 * trusted and will be used as-is; unlike userId which will be validated by this method. 4299 */ 4300 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4301 int filterCallingUid, int userId) { 4302 if (!sUserManager.exists(userId)) return null; 4303 flags = updateFlagsForApplication(flags, userId, packageName); 4304 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4305 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4306 4307 // writer 4308 synchronized (mPackages) { 4309 // Normalize package name to handle renamed packages and static libs 4310 packageName = resolveInternalPackageNameLPr(packageName, 4311 PackageManager.VERSION_CODE_HIGHEST); 4312 4313 PackageParser.Package p = mPackages.get(packageName); 4314 if (DEBUG_PACKAGE_INFO) Log.v( 4315 TAG, "getApplicationInfo " + packageName 4316 + ": " + p); 4317 if (p != null) { 4318 PackageSetting ps = mSettings.mPackages.get(packageName); 4319 if (ps == null) return null; 4320 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4321 return null; 4322 } 4323 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4324 return null; 4325 } 4326 // Note: isEnabledLP() does not apply here - always return info 4327 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4328 p, flags, ps.readUserState(userId), userId); 4329 if (ai != null) { 4330 ai.packageName = resolveExternalPackageNameLPr(p); 4331 } 4332 return ai; 4333 } 4334 if ("android".equals(packageName)||"system".equals(packageName)) { 4335 return mAndroidApplication; 4336 } 4337 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4338 // Already generates the external package name 4339 return generateApplicationInfoFromSettingsLPw(packageName, 4340 flags, filterCallingUid, userId); 4341 } 4342 } 4343 return null; 4344 } 4345 4346 private String normalizePackageNameLPr(String packageName) { 4347 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4348 return normalizedPackageName != null ? normalizedPackageName : packageName; 4349 } 4350 4351 @Override 4352 public void deletePreloadsFileCache() { 4353 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4354 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4355 } 4356 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4357 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4358 FileUtils.deleteContents(dir); 4359 } 4360 4361 @Override 4362 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4363 final int storageFlags, final IPackageDataObserver observer) { 4364 mContext.enforceCallingOrSelfPermission( 4365 android.Manifest.permission.CLEAR_APP_CACHE, null); 4366 mHandler.post(() -> { 4367 boolean success = false; 4368 try { 4369 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4370 success = true; 4371 } catch (IOException e) { 4372 Slog.w(TAG, e); 4373 } 4374 if (observer != null) { 4375 try { 4376 observer.onRemoveCompleted(null, success); 4377 } catch (RemoteException e) { 4378 Slog.w(TAG, e); 4379 } 4380 } 4381 }); 4382 } 4383 4384 @Override 4385 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4386 final int storageFlags, final IntentSender pi) { 4387 mContext.enforceCallingOrSelfPermission( 4388 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4389 mHandler.post(() -> { 4390 boolean success = false; 4391 try { 4392 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4393 success = true; 4394 } catch (IOException e) { 4395 Slog.w(TAG, e); 4396 } 4397 if (pi != null) { 4398 try { 4399 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4400 } catch (SendIntentException e) { 4401 Slog.w(TAG, e); 4402 } 4403 } 4404 }); 4405 } 4406 4407 /** 4408 * Blocking call to clear various types of cached data across the system 4409 * until the requested bytes are available. 4410 */ 4411 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4412 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4413 final File file = storage.findPathForUuid(volumeUuid); 4414 if (file.getUsableSpace() >= bytes) return; 4415 4416 if (ENABLE_FREE_CACHE_V2) { 4417 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4418 volumeUuid); 4419 final boolean aggressive = (storageFlags 4420 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4421 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags); 4422 4423 // 1. Pre-flight to determine if we have any chance to succeed 4424 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4425 if (internalVolume && (aggressive || SystemProperties 4426 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4427 deletePreloadsFileCache(); 4428 if (file.getUsableSpace() >= bytes) return; 4429 } 4430 4431 // 3. Consider parsed APK data (aggressive only) 4432 if (internalVolume && aggressive) { 4433 FileUtils.deleteContents(mCacheDir); 4434 if (file.getUsableSpace() >= bytes) return; 4435 } 4436 4437 // 4. Consider cached app data (above quotas) 4438 try { 4439 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4440 Installer.FLAG_FREE_CACHE_V2); 4441 } catch (InstallerException ignored) { 4442 } 4443 if (file.getUsableSpace() >= bytes) return; 4444 4445 // 5. Consider shared libraries with refcount=0 and age>min cache period 4446 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4447 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4448 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4449 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4450 return; 4451 } 4452 4453 // 6. Consider dexopt output (aggressive only) 4454 // TODO: Implement 4455 4456 // 7. Consider installed instant apps unused longer than min cache period 4457 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4458 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4459 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4460 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4461 return; 4462 } 4463 4464 // 8. Consider cached app data (below quotas) 4465 try { 4466 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4467 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4468 } catch (InstallerException ignored) { 4469 } 4470 if (file.getUsableSpace() >= bytes) return; 4471 4472 // 9. Consider DropBox entries 4473 // TODO: Implement 4474 4475 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4476 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4477 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4478 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4479 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4480 return; 4481 } 4482 } else { 4483 try { 4484 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4485 } catch (InstallerException ignored) { 4486 } 4487 if (file.getUsableSpace() >= bytes) return; 4488 } 4489 4490 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4491 } 4492 4493 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4494 throws IOException { 4495 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4496 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4497 4498 List<VersionedPackage> packagesToDelete = null; 4499 final long now = System.currentTimeMillis(); 4500 4501 synchronized (mPackages) { 4502 final int[] allUsers = sUserManager.getUserIds(); 4503 final int libCount = mSharedLibraries.size(); 4504 for (int i = 0; i < libCount; i++) { 4505 final LongSparseArray<SharedLibraryEntry> versionedLib 4506 = mSharedLibraries.valueAt(i); 4507 if (versionedLib == null) { 4508 continue; 4509 } 4510 final int versionCount = versionedLib.size(); 4511 for (int j = 0; j < versionCount; j++) { 4512 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4513 // Skip packages that are not static shared libs. 4514 if (!libInfo.isStatic()) { 4515 break; 4516 } 4517 // Important: We skip static shared libs used for some user since 4518 // in such a case we need to keep the APK on the device. The check for 4519 // a lib being used for any user is performed by the uninstall call. 4520 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4521 // Resolve the package name - we use synthetic package names internally 4522 final String internalPackageName = resolveInternalPackageNameLPr( 4523 declaringPackage.getPackageName(), 4524 declaringPackage.getLongVersionCode()); 4525 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4526 // Skip unused static shared libs cached less than the min period 4527 // to prevent pruning a lib needed by a subsequently installed package. 4528 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4529 continue; 4530 } 4531 if (packagesToDelete == null) { 4532 packagesToDelete = new ArrayList<>(); 4533 } 4534 packagesToDelete.add(new VersionedPackage(internalPackageName, 4535 declaringPackage.getLongVersionCode())); 4536 } 4537 } 4538 } 4539 4540 if (packagesToDelete != null) { 4541 final int packageCount = packagesToDelete.size(); 4542 for (int i = 0; i < packageCount; i++) { 4543 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4544 // Delete the package synchronously (will fail of the lib used for any user). 4545 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(), 4546 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4547 == PackageManager.DELETE_SUCCEEDED) { 4548 if (volume.getUsableSpace() >= neededSpace) { 4549 return true; 4550 } 4551 } 4552 } 4553 } 4554 4555 return false; 4556 } 4557 4558 /** 4559 * Update given flags based on encryption status of current user. 4560 */ 4561 private int updateFlags(int flags, int userId) { 4562 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4563 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4564 // Caller expressed an explicit opinion about what encryption 4565 // aware/unaware components they want to see, so fall through and 4566 // give them what they want 4567 } else { 4568 // Caller expressed no opinion, so match based on user state 4569 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4570 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4571 } else { 4572 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4573 } 4574 } 4575 return flags; 4576 } 4577 4578 private UserManagerInternal getUserManagerInternal() { 4579 if (mUserManagerInternal == null) { 4580 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4581 } 4582 return mUserManagerInternal; 4583 } 4584 4585 private ActivityManagerInternal getActivityManagerInternal() { 4586 if (mActivityManagerInternal == null) { 4587 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class); 4588 } 4589 return mActivityManagerInternal; 4590 } 4591 4592 4593 private DeviceIdleController.LocalService getDeviceIdleController() { 4594 if (mDeviceIdleController == null) { 4595 mDeviceIdleController = 4596 LocalServices.getService(DeviceIdleController.LocalService.class); 4597 } 4598 return mDeviceIdleController; 4599 } 4600 4601 /** 4602 * Update given flags when being used to request {@link PackageInfo}. 4603 */ 4604 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4605 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4606 boolean triaged = true; 4607 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4608 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4609 // Caller is asking for component details, so they'd better be 4610 // asking for specific encryption matching behavior, or be triaged 4611 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4612 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4613 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4614 triaged = false; 4615 } 4616 } 4617 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4618 | PackageManager.MATCH_SYSTEM_ONLY 4619 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4620 triaged = false; 4621 } 4622 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4623 mPermissionManager.enforceCrossUserPermission( 4624 Binder.getCallingUid(), userId, false, false, 4625 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4626 + Debug.getCallers(5)); 4627 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4628 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4629 // If the caller wants all packages and has a restricted profile associated with it, 4630 // then match all users. This is to make sure that launchers that need to access work 4631 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4632 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4633 flags |= PackageManager.MATCH_ANY_USER; 4634 } 4635 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4636 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4637 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4638 } 4639 return updateFlags(flags, userId); 4640 } 4641 4642 /** 4643 * Update given flags when being used to request {@link ApplicationInfo}. 4644 */ 4645 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4646 return updateFlagsForPackage(flags, userId, cookie); 4647 } 4648 4649 /** 4650 * Update given flags when being used to request {@link ComponentInfo}. 4651 */ 4652 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4653 if (cookie instanceof Intent) { 4654 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4655 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4656 } 4657 } 4658 4659 boolean triaged = true; 4660 // Caller is asking for component details, so they'd better be 4661 // asking for specific encryption matching behavior, or be triaged 4662 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4663 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4664 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4665 triaged = false; 4666 } 4667 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4668 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4669 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4670 } 4671 4672 return updateFlags(flags, userId); 4673 } 4674 4675 /** 4676 * Update given intent when being used to request {@link ResolveInfo}. 4677 */ 4678 private Intent updateIntentForResolve(Intent intent) { 4679 if (intent.getSelector() != null) { 4680 intent = intent.getSelector(); 4681 } 4682 if (DEBUG_PREFERRED) { 4683 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4684 } 4685 return intent; 4686 } 4687 4688 /** 4689 * Update given flags when being used to request {@link ResolveInfo}. 4690 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4691 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4692 * flag set. However, this flag is only honoured in three circumstances: 4693 * <ul> 4694 * <li>when called from a system process</li> 4695 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4696 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4697 * action and a {@code android.intent.category.BROWSABLE} category</li> 4698 * </ul> 4699 */ 4700 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4701 return updateFlagsForResolve(flags, userId, intent, callingUid, 4702 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4703 } 4704 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4705 boolean wantInstantApps) { 4706 return updateFlagsForResolve(flags, userId, intent, callingUid, 4707 wantInstantApps, false /*onlyExposedExplicitly*/); 4708 } 4709 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4710 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4711 // Safe mode means we shouldn't match any third-party components 4712 if (mSafeMode) { 4713 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4714 } 4715 if (getInstantAppPackageName(callingUid) != null) { 4716 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4717 if (onlyExposedExplicitly) { 4718 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4719 } 4720 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4721 flags |= PackageManager.MATCH_INSTANT; 4722 } else { 4723 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 4724 final boolean allowMatchInstant = 4725 (wantInstantApps 4726 && Intent.ACTION_VIEW.equals(intent.getAction()) 4727 && hasWebURI(intent)) 4728 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 4729 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4730 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4731 if (!allowMatchInstant) { 4732 flags &= ~PackageManager.MATCH_INSTANT; 4733 } 4734 } 4735 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4736 } 4737 4738 @Override 4739 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4740 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 4741 } 4742 4743 /** 4744 * Important: The provided filterCallingUid is used exclusively to filter out activities 4745 * that can be seen based on user state. It's typically the original caller uid prior 4746 * to clearing. Because it can only be provided by trusted code, it's value can be 4747 * trusted and will be used as-is; unlike userId which will be validated by this method. 4748 */ 4749 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 4750 int filterCallingUid, int userId) { 4751 if (!sUserManager.exists(userId)) return null; 4752 flags = updateFlagsForComponent(flags, userId, component); 4753 4754 if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) { 4755 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4756 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4757 } 4758 4759 synchronized (mPackages) { 4760 PackageParser.Activity a = mActivities.mActivities.get(component); 4761 4762 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4763 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4764 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4765 if (ps == null) return null; 4766 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 4767 return null; 4768 } 4769 return PackageParser.generateActivityInfo( 4770 a, flags, ps.readUserState(userId), userId); 4771 } 4772 if (mResolveComponentName.equals(component)) { 4773 return PackageParser.generateActivityInfo( 4774 mResolveActivity, flags, new PackageUserState(), userId); 4775 } 4776 } 4777 return null; 4778 } 4779 4780 private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) { 4781 if (!getActivityManagerInternal().isCallerRecents(callingUid)) { 4782 return false; 4783 } 4784 final long token = Binder.clearCallingIdentity(); 4785 try { 4786 final int callingUserId = UserHandle.getUserId(callingUid); 4787 if (ActivityManager.getCurrentUser() != callingUserId) { 4788 return false; 4789 } 4790 return sUserManager.isSameProfileGroup(callingUserId, targetUserId); 4791 } finally { 4792 Binder.restoreCallingIdentity(token); 4793 } 4794 } 4795 4796 @Override 4797 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4798 String resolvedType) { 4799 synchronized (mPackages) { 4800 if (component.equals(mResolveComponentName)) { 4801 // The resolver supports EVERYTHING! 4802 return true; 4803 } 4804 final int callingUid = Binder.getCallingUid(); 4805 final int callingUserId = UserHandle.getUserId(callingUid); 4806 PackageParser.Activity a = mActivities.mActivities.get(component); 4807 if (a == null) { 4808 return false; 4809 } 4810 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4811 if (ps == null) { 4812 return false; 4813 } 4814 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4815 return false; 4816 } 4817 for (int i=0; i<a.intents.size(); i++) { 4818 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4819 intent.getData(), intent.getCategories(), TAG) >= 0) { 4820 return true; 4821 } 4822 } 4823 return false; 4824 } 4825 } 4826 4827 @Override 4828 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4829 if (!sUserManager.exists(userId)) return null; 4830 final int callingUid = Binder.getCallingUid(); 4831 flags = updateFlagsForComponent(flags, userId, component); 4832 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4833 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4834 synchronized (mPackages) { 4835 PackageParser.Activity a = mReceivers.mActivities.get(component); 4836 if (DEBUG_PACKAGE_INFO) Log.v( 4837 TAG, "getReceiverInfo " + component + ": " + a); 4838 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4839 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4840 if (ps == null) return null; 4841 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4842 return null; 4843 } 4844 return PackageParser.generateActivityInfo( 4845 a, flags, ps.readUserState(userId), userId); 4846 } 4847 } 4848 return null; 4849 } 4850 4851 @Override 4852 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4853 int flags, int userId) { 4854 if (!sUserManager.exists(userId)) return null; 4855 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4856 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4857 return null; 4858 } 4859 4860 flags = updateFlagsForPackage(flags, userId, null); 4861 4862 final boolean canSeeStaticLibraries = 4863 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4864 == PERMISSION_GRANTED 4865 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4866 == PERMISSION_GRANTED 4867 || canRequestPackageInstallsInternal(packageName, 4868 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 4869 false /* throwIfPermNotDeclared*/) 4870 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4871 == PERMISSION_GRANTED; 4872 4873 synchronized (mPackages) { 4874 List<SharedLibraryInfo> result = null; 4875 4876 final int libCount = mSharedLibraries.size(); 4877 for (int i = 0; i < libCount; i++) { 4878 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4879 if (versionedLib == null) { 4880 continue; 4881 } 4882 4883 final int versionCount = versionedLib.size(); 4884 for (int j = 0; j < versionCount; j++) { 4885 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4886 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4887 break; 4888 } 4889 final long identity = Binder.clearCallingIdentity(); 4890 try { 4891 PackageInfo packageInfo = getPackageInfoVersioned( 4892 libInfo.getDeclaringPackage(), flags 4893 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 4894 if (packageInfo == null) { 4895 continue; 4896 } 4897 } finally { 4898 Binder.restoreCallingIdentity(identity); 4899 } 4900 4901 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4902 libInfo.getLongVersion(), libInfo.getType(), 4903 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 4904 flags, userId)); 4905 4906 if (result == null) { 4907 result = new ArrayList<>(); 4908 } 4909 result.add(resLibInfo); 4910 } 4911 } 4912 4913 return result != null ? new ParceledListSlice<>(result) : null; 4914 } 4915 } 4916 4917 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4918 SharedLibraryInfo libInfo, int flags, int userId) { 4919 List<VersionedPackage> versionedPackages = null; 4920 final int packageCount = mSettings.mPackages.size(); 4921 for (int i = 0; i < packageCount; i++) { 4922 PackageSetting ps = mSettings.mPackages.valueAt(i); 4923 4924 if (ps == null) { 4925 continue; 4926 } 4927 4928 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4929 continue; 4930 } 4931 4932 final String libName = libInfo.getName(); 4933 if (libInfo.isStatic()) { 4934 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4935 if (libIdx < 0) { 4936 continue; 4937 } 4938 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) { 4939 continue; 4940 } 4941 if (versionedPackages == null) { 4942 versionedPackages = new ArrayList<>(); 4943 } 4944 // If the dependent is a static shared lib, use the public package name 4945 String dependentPackageName = ps.name; 4946 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4947 dependentPackageName = ps.pkg.manifestPackageName; 4948 } 4949 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4950 } else if (ps.pkg != null) { 4951 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4952 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4953 if (versionedPackages == null) { 4954 versionedPackages = new ArrayList<>(); 4955 } 4956 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4957 } 4958 } 4959 } 4960 4961 return versionedPackages; 4962 } 4963 4964 @Override 4965 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4966 if (!sUserManager.exists(userId)) return null; 4967 final int callingUid = Binder.getCallingUid(); 4968 flags = updateFlagsForComponent(flags, userId, component); 4969 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4970 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4971 synchronized (mPackages) { 4972 PackageParser.Service s = mServices.mServices.get(component); 4973 if (DEBUG_PACKAGE_INFO) Log.v( 4974 TAG, "getServiceInfo " + component + ": " + s); 4975 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4976 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4977 if (ps == null) return null; 4978 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 4979 return null; 4980 } 4981 return PackageParser.generateServiceInfo( 4982 s, flags, ps.readUserState(userId), userId); 4983 } 4984 } 4985 return null; 4986 } 4987 4988 @Override 4989 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4990 if (!sUserManager.exists(userId)) return null; 4991 final int callingUid = Binder.getCallingUid(); 4992 flags = updateFlagsForComponent(flags, userId, component); 4993 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4994 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4995 synchronized (mPackages) { 4996 PackageParser.Provider p = mProviders.mProviders.get(component); 4997 if (DEBUG_PACKAGE_INFO) Log.v( 4998 TAG, "getProviderInfo " + component + ": " + p); 4999 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 5000 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5001 if (ps == null) return null; 5002 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 5003 return null; 5004 } 5005 return PackageParser.generateProviderInfo( 5006 p, flags, ps.readUserState(userId), userId); 5007 } 5008 } 5009 return null; 5010 } 5011 5012 @Override 5013 public String[] getSystemSharedLibraryNames() { 5014 // allow instant applications 5015 synchronized (mPackages) { 5016 Set<String> libs = null; 5017 final int libCount = mSharedLibraries.size(); 5018 for (int i = 0; i < libCount; i++) { 5019 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 5020 if (versionedLib == null) { 5021 continue; 5022 } 5023 final int versionCount = versionedLib.size(); 5024 for (int j = 0; j < versionCount; j++) { 5025 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 5026 if (!libEntry.info.isStatic()) { 5027 if (libs == null) { 5028 libs = new ArraySet<>(); 5029 } 5030 libs.add(libEntry.info.getName()); 5031 break; 5032 } 5033 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 5034 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 5035 UserHandle.getUserId(Binder.getCallingUid()), 5036 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 5037 if (libs == null) { 5038 libs = new ArraySet<>(); 5039 } 5040 libs.add(libEntry.info.getName()); 5041 break; 5042 } 5043 } 5044 } 5045 5046 if (libs != null) { 5047 String[] libsArray = new String[libs.size()]; 5048 libs.toArray(libsArray); 5049 return libsArray; 5050 } 5051 5052 return null; 5053 } 5054 } 5055 5056 @Override 5057 public @NonNull String getServicesSystemSharedLibraryPackageName() { 5058 // allow instant applications 5059 synchronized (mPackages) { 5060 return mServicesSystemSharedLibraryPackageName; 5061 } 5062 } 5063 5064 @Override 5065 public @NonNull String getSharedSystemSharedLibraryPackageName() { 5066 // allow instant applications 5067 synchronized (mPackages) { 5068 return mSharedSystemSharedLibraryPackageName; 5069 } 5070 } 5071 5072 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 5073 for (int i = userList.length - 1; i >= 0; --i) { 5074 final int userId = userList[i]; 5075 // don't add instant app to the list of updates 5076 if (pkgSetting.getInstantApp(userId)) { 5077 continue; 5078 } 5079 SparseArray<String> changedPackages = mChangedPackages.get(userId); 5080 if (changedPackages == null) { 5081 changedPackages = new SparseArray<>(); 5082 mChangedPackages.put(userId, changedPackages); 5083 } 5084 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 5085 if (sequenceNumbers == null) { 5086 sequenceNumbers = new HashMap<>(); 5087 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 5088 } 5089 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 5090 if (sequenceNumber != null) { 5091 changedPackages.remove(sequenceNumber); 5092 } 5093 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 5094 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 5095 } 5096 mChangedPackagesSequenceNumber++; 5097 } 5098 5099 @Override 5100 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5101 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5102 return null; 5103 } 5104 synchronized (mPackages) { 5105 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 5106 return null; 5107 } 5108 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 5109 if (changedPackages == null) { 5110 return null; 5111 } 5112 final List<String> packageNames = 5113 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 5114 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 5115 final String packageName = changedPackages.get(i); 5116 if (packageName != null) { 5117 packageNames.add(packageName); 5118 } 5119 } 5120 return packageNames.isEmpty() 5121 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 5122 } 5123 } 5124 5125 @Override 5126 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5127 // allow instant applications 5128 ArrayList<FeatureInfo> res; 5129 synchronized (mAvailableFeatures) { 5130 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5131 res.addAll(mAvailableFeatures.values()); 5132 } 5133 final FeatureInfo fi = new FeatureInfo(); 5134 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5135 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5136 res.add(fi); 5137 5138 return new ParceledListSlice<>(res); 5139 } 5140 5141 @Override 5142 public boolean hasSystemFeature(String name, int version) { 5143 // allow instant applications 5144 synchronized (mAvailableFeatures) { 5145 final FeatureInfo feat = mAvailableFeatures.get(name); 5146 if (feat == null) { 5147 return false; 5148 } else { 5149 return feat.version >= version; 5150 } 5151 } 5152 } 5153 5154 @Override 5155 public int checkPermission(String permName, String pkgName, int userId) { 5156 return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId); 5157 } 5158 5159 @Override 5160 public int checkUidPermission(String permName, int uid) { 5161 return mPermissionManager.checkUidPermission(permName, uid, getCallingUid()); 5162 } 5163 5164 @Override 5165 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5166 if (UserHandle.getCallingUserId() != userId) { 5167 mContext.enforceCallingPermission( 5168 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5169 "isPermissionRevokedByPolicy for user " + userId); 5170 } 5171 5172 if (checkPermission(permission, packageName, userId) 5173 == PackageManager.PERMISSION_GRANTED) { 5174 return false; 5175 } 5176 5177 final int callingUid = Binder.getCallingUid(); 5178 if (getInstantAppPackageName(callingUid) != null) { 5179 if (!isCallerSameApp(packageName, callingUid)) { 5180 return false; 5181 } 5182 } else { 5183 if (isInstantApp(packageName, userId)) { 5184 return false; 5185 } 5186 } 5187 5188 final long identity = Binder.clearCallingIdentity(); 5189 try { 5190 final int flags = getPermissionFlags(permission, packageName, userId); 5191 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5192 } finally { 5193 Binder.restoreCallingIdentity(identity); 5194 } 5195 } 5196 5197 @Override 5198 public String getPermissionControllerPackageName() { 5199 synchronized (mPackages) { 5200 return mRequiredInstallerPackage; 5201 } 5202 } 5203 5204 private boolean addDynamicPermission(PermissionInfo info, final boolean async) { 5205 return mPermissionManager.addDynamicPermission( 5206 info, async, getCallingUid(), new PermissionCallback() { 5207 @Override 5208 public void onPermissionChanged() { 5209 if (!async) { 5210 mSettings.writeLPr(); 5211 } else { 5212 scheduleWriteSettingsLocked(); 5213 } 5214 } 5215 }); 5216 } 5217 5218 @Override 5219 public boolean addPermission(PermissionInfo info) { 5220 synchronized (mPackages) { 5221 return addDynamicPermission(info, false); 5222 } 5223 } 5224 5225 @Override 5226 public boolean addPermissionAsync(PermissionInfo info) { 5227 synchronized (mPackages) { 5228 return addDynamicPermission(info, true); 5229 } 5230 } 5231 5232 @Override 5233 public void removePermission(String permName) { 5234 mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback); 5235 } 5236 5237 @Override 5238 public void grantRuntimePermission(String packageName, String permName, final int userId) { 5239 mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/, 5240 getCallingUid(), userId, mPermissionCallback); 5241 } 5242 5243 @Override 5244 public void revokeRuntimePermission(String packageName, String permName, int userId) { 5245 mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/, 5246 getCallingUid(), userId, mPermissionCallback); 5247 } 5248 5249 @Override 5250 public void resetRuntimePermissions() { 5251 mContext.enforceCallingOrSelfPermission( 5252 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5253 "revokeRuntimePermission"); 5254 5255 int callingUid = Binder.getCallingUid(); 5256 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5257 mContext.enforceCallingOrSelfPermission( 5258 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5259 "resetRuntimePermissions"); 5260 } 5261 5262 synchronized (mPackages) { 5263 mPermissionManager.updateAllPermissions( 5264 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 5265 mPermissionCallback); 5266 for (int userId : UserManagerService.getInstance().getUserIds()) { 5267 final int packageCount = mPackages.size(); 5268 for (int i = 0; i < packageCount; i++) { 5269 PackageParser.Package pkg = mPackages.valueAt(i); 5270 if (!(pkg.mExtras instanceof PackageSetting)) { 5271 continue; 5272 } 5273 PackageSetting ps = (PackageSetting) pkg.mExtras; 5274 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5275 } 5276 } 5277 } 5278 } 5279 5280 @Override 5281 public int getPermissionFlags(String permName, String packageName, int userId) { 5282 return mPermissionManager.getPermissionFlags( 5283 permName, packageName, getCallingUid(), userId); 5284 } 5285 5286 @Override 5287 public void updatePermissionFlags(String permName, String packageName, int flagMask, 5288 int flagValues, int userId) { 5289 mPermissionManager.updatePermissionFlags( 5290 permName, packageName, flagMask, flagValues, getCallingUid(), userId, 5291 mPermissionCallback); 5292 } 5293 5294 /** 5295 * Update the permission flags for all packages and runtime permissions of a user in order 5296 * to allow device or profile owner to remove POLICY_FIXED. 5297 */ 5298 @Override 5299 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5300 synchronized (mPackages) { 5301 final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps( 5302 flagMask, flagValues, getCallingUid(), userId, mPackages.values(), 5303 mPermissionCallback); 5304 if (changed) { 5305 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5306 } 5307 } 5308 } 5309 5310 @Override 5311 public boolean shouldShowRequestPermissionRationale(String permissionName, 5312 String packageName, int userId) { 5313 if (UserHandle.getCallingUserId() != userId) { 5314 mContext.enforceCallingPermission( 5315 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5316 "canShowRequestPermissionRationale for user " + userId); 5317 } 5318 5319 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5320 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5321 return false; 5322 } 5323 5324 if (checkPermission(permissionName, packageName, userId) 5325 == PackageManager.PERMISSION_GRANTED) { 5326 return false; 5327 } 5328 5329 final int flags; 5330 5331 final long identity = Binder.clearCallingIdentity(); 5332 try { 5333 flags = getPermissionFlags(permissionName, 5334 packageName, userId); 5335 } finally { 5336 Binder.restoreCallingIdentity(identity); 5337 } 5338 5339 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5340 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5341 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5342 5343 if ((flags & fixedFlags) != 0) { 5344 return false; 5345 } 5346 5347 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5348 } 5349 5350 @Override 5351 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5352 mContext.enforceCallingOrSelfPermission( 5353 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5354 "addOnPermissionsChangeListener"); 5355 5356 synchronized (mPackages) { 5357 mOnPermissionChangeListeners.addListenerLocked(listener); 5358 } 5359 } 5360 5361 @Override 5362 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5363 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5364 throw new SecurityException("Instant applications don't have access to this method"); 5365 } 5366 synchronized (mPackages) { 5367 mOnPermissionChangeListeners.removeListenerLocked(listener); 5368 } 5369 } 5370 5371 @Override 5372 public boolean isProtectedBroadcast(String actionName) { 5373 // allow instant applications 5374 synchronized (mProtectedBroadcasts) { 5375 if (mProtectedBroadcasts.contains(actionName)) { 5376 return true; 5377 } else if (actionName != null) { 5378 // TODO: remove these terrible hacks 5379 if (actionName.startsWith("android.net.netmon.lingerExpired") 5380 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5381 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5382 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5383 return true; 5384 } 5385 } 5386 } 5387 return false; 5388 } 5389 5390 @Override 5391 public int checkSignatures(String pkg1, String pkg2) { 5392 synchronized (mPackages) { 5393 final PackageParser.Package p1 = mPackages.get(pkg1); 5394 final PackageParser.Package p2 = mPackages.get(pkg2); 5395 if (p1 == null || p1.mExtras == null 5396 || p2 == null || p2.mExtras == null) { 5397 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5398 } 5399 final int callingUid = Binder.getCallingUid(); 5400 final int callingUserId = UserHandle.getUserId(callingUid); 5401 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 5402 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 5403 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 5404 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 5405 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5406 } 5407 return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures); 5408 } 5409 } 5410 5411 @Override 5412 public int checkUidSignatures(int uid1, int uid2) { 5413 final int callingUid = Binder.getCallingUid(); 5414 final int callingUserId = UserHandle.getUserId(callingUid); 5415 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5416 // Map to base uids. 5417 uid1 = UserHandle.getAppId(uid1); 5418 uid2 = UserHandle.getAppId(uid2); 5419 // reader 5420 synchronized (mPackages) { 5421 Signature[] s1; 5422 Signature[] s2; 5423 Object obj = mSettings.getUserIdLPr(uid1); 5424 if (obj != null) { 5425 if (obj instanceof SharedUserSetting) { 5426 if (isCallerInstantApp) { 5427 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5428 } 5429 s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5430 } else if (obj instanceof PackageSetting) { 5431 final PackageSetting ps = (PackageSetting) obj; 5432 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5433 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5434 } 5435 s1 = ps.signatures.mSigningDetails.signatures; 5436 } else { 5437 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5438 } 5439 } else { 5440 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5441 } 5442 obj = mSettings.getUserIdLPr(uid2); 5443 if (obj != null) { 5444 if (obj instanceof SharedUserSetting) { 5445 if (isCallerInstantApp) { 5446 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5447 } 5448 s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5449 } else if (obj instanceof PackageSetting) { 5450 final PackageSetting ps = (PackageSetting) obj; 5451 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5452 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5453 } 5454 s2 = ps.signatures.mSigningDetails.signatures; 5455 } else { 5456 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5457 } 5458 } else { 5459 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5460 } 5461 return compareSignatures(s1, s2); 5462 } 5463 } 5464 5465 @Override 5466 public boolean hasSigningCertificate( 5467 String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) { 5468 5469 synchronized (mPackages) { 5470 final PackageParser.Package p = mPackages.get(packageName); 5471 if (p == null || p.mExtras == null) { 5472 return false; 5473 } 5474 final int callingUid = Binder.getCallingUid(); 5475 final int callingUserId = UserHandle.getUserId(callingUid); 5476 final PackageSetting ps = (PackageSetting) p.mExtras; 5477 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5478 return false; 5479 } 5480 switch (type) { 5481 case CERT_INPUT_RAW_X509: 5482 return signingDetailsHasCertificate(certificate, p.mSigningDetails); 5483 case CERT_INPUT_SHA256: 5484 return signingDetailsHasSha256Certificate(certificate, p.mSigningDetails); 5485 default: 5486 return false; 5487 } 5488 } 5489 } 5490 5491 @Override 5492 public boolean hasUidSigningCertificate( 5493 int uid, byte[] certificate, @PackageManager.CertificateInputType int type) { 5494 final int callingUid = Binder.getCallingUid(); 5495 final int callingUserId = UserHandle.getUserId(callingUid); 5496 // Map to base uids. 5497 uid = UserHandle.getAppId(uid); 5498 // reader 5499 synchronized (mPackages) { 5500 final PackageParser.SigningDetails signingDetails; 5501 final Object obj = mSettings.getUserIdLPr(uid); 5502 if (obj != null) { 5503 if (obj instanceof SharedUserSetting) { 5504 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5505 if (isCallerInstantApp) { 5506 return false; 5507 } 5508 signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails; 5509 } else if (obj instanceof PackageSetting) { 5510 final PackageSetting ps = (PackageSetting) obj; 5511 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5512 return false; 5513 } 5514 signingDetails = ps.signatures.mSigningDetails; 5515 } else { 5516 return false; 5517 } 5518 } else { 5519 return false; 5520 } 5521 switch (type) { 5522 case CERT_INPUT_RAW_X509: 5523 return signingDetailsHasCertificate(certificate, signingDetails); 5524 case CERT_INPUT_SHA256: 5525 return signingDetailsHasSha256Certificate(certificate, signingDetails); 5526 default: 5527 return false; 5528 } 5529 } 5530 } 5531 5532 /** 5533 * This method should typically only be used when granting or revoking 5534 * permissions, since the app may immediately restart after this call. 5535 * <p> 5536 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5537 * guard your work against the app being relaunched. 5538 */ 5539 private void killUid(int appId, int userId, String reason) { 5540 final long identity = Binder.clearCallingIdentity(); 5541 try { 5542 IActivityManager am = ActivityManager.getService(); 5543 if (am != null) { 5544 try { 5545 am.killUid(appId, userId, reason); 5546 } catch (RemoteException e) { 5547 /* ignore - same process */ 5548 } 5549 } 5550 } finally { 5551 Binder.restoreCallingIdentity(identity); 5552 } 5553 } 5554 5555 /** 5556 * If the database version for this type of package (internal storage or 5557 * external storage) is less than the version where package signatures 5558 * were updated, return true. 5559 */ 5560 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5561 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5562 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5563 } 5564 5565 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5566 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5567 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5568 } 5569 5570 @Override 5571 public List<String> getAllPackages() { 5572 final int callingUid = Binder.getCallingUid(); 5573 final int callingUserId = UserHandle.getUserId(callingUid); 5574 synchronized (mPackages) { 5575 if (canViewInstantApps(callingUid, callingUserId)) { 5576 return new ArrayList<String>(mPackages.keySet()); 5577 } 5578 final String instantAppPkgName = getInstantAppPackageName(callingUid); 5579 final List<String> result = new ArrayList<>(); 5580 if (instantAppPkgName != null) { 5581 // caller is an instant application; filter unexposed applications 5582 for (PackageParser.Package pkg : mPackages.values()) { 5583 if (!pkg.visibleToInstantApps) { 5584 continue; 5585 } 5586 result.add(pkg.packageName); 5587 } 5588 } else { 5589 // caller is a normal application; filter instant applications 5590 for (PackageParser.Package pkg : mPackages.values()) { 5591 final PackageSetting ps = 5592 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 5593 if (ps != null 5594 && ps.getInstantApp(callingUserId) 5595 && !mInstantAppRegistry.isInstantAccessGranted( 5596 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 5597 continue; 5598 } 5599 result.add(pkg.packageName); 5600 } 5601 } 5602 return result; 5603 } 5604 } 5605 5606 @Override 5607 public String[] getPackagesForUid(int uid) { 5608 final int callingUid = Binder.getCallingUid(); 5609 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5610 final int userId = UserHandle.getUserId(uid); 5611 uid = UserHandle.getAppId(uid); 5612 // reader 5613 synchronized (mPackages) { 5614 Object obj = mSettings.getUserIdLPr(uid); 5615 if (obj instanceof SharedUserSetting) { 5616 if (isCallerInstantApp) { 5617 return null; 5618 } 5619 final SharedUserSetting sus = (SharedUserSetting) obj; 5620 final int N = sus.packages.size(); 5621 String[] res = new String[N]; 5622 final Iterator<PackageSetting> it = sus.packages.iterator(); 5623 int i = 0; 5624 while (it.hasNext()) { 5625 PackageSetting ps = it.next(); 5626 if (ps.getInstalled(userId)) { 5627 res[i++] = ps.name; 5628 } else { 5629 res = ArrayUtils.removeElement(String.class, res, res[i]); 5630 } 5631 } 5632 return res; 5633 } else if (obj instanceof PackageSetting) { 5634 final PackageSetting ps = (PackageSetting) obj; 5635 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 5636 return new String[]{ps.name}; 5637 } 5638 } 5639 } 5640 return null; 5641 } 5642 5643 @Override 5644 public String getNameForUid(int uid) { 5645 final int callingUid = Binder.getCallingUid(); 5646 if (getInstantAppPackageName(callingUid) != null) { 5647 return null; 5648 } 5649 synchronized (mPackages) { 5650 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5651 if (obj instanceof SharedUserSetting) { 5652 final SharedUserSetting sus = (SharedUserSetting) obj; 5653 return sus.name + ":" + sus.userId; 5654 } else if (obj instanceof PackageSetting) { 5655 final PackageSetting ps = (PackageSetting) obj; 5656 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5657 return null; 5658 } 5659 return ps.name; 5660 } 5661 return null; 5662 } 5663 } 5664 5665 @Override 5666 public String[] getNamesForUids(int[] uids) { 5667 if (uids == null || uids.length == 0) { 5668 return null; 5669 } 5670 final int callingUid = Binder.getCallingUid(); 5671 if (getInstantAppPackageName(callingUid) != null) { 5672 return null; 5673 } 5674 final String[] names = new String[uids.length]; 5675 synchronized (mPackages) { 5676 for (int i = uids.length - 1; i >= 0; i--) { 5677 final int uid = uids[i]; 5678 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5679 if (obj instanceof SharedUserSetting) { 5680 final SharedUserSetting sus = (SharedUserSetting) obj; 5681 names[i] = "shared:" + sus.name; 5682 } else if (obj instanceof PackageSetting) { 5683 final PackageSetting ps = (PackageSetting) obj; 5684 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5685 names[i] = null; 5686 } else { 5687 names[i] = ps.name; 5688 } 5689 } else { 5690 names[i] = null; 5691 } 5692 } 5693 } 5694 return names; 5695 } 5696 5697 @Override 5698 public int getUidForSharedUser(String sharedUserName) { 5699 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5700 return -1; 5701 } 5702 if (sharedUserName == null) { 5703 return -1; 5704 } 5705 // reader 5706 synchronized (mPackages) { 5707 SharedUserSetting suid; 5708 try { 5709 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5710 if (suid != null) { 5711 return suid.userId; 5712 } 5713 } catch (PackageManagerException ignore) { 5714 // can't happen, but, still need to catch it 5715 } 5716 return -1; 5717 } 5718 } 5719 5720 @Override 5721 public int getFlagsForUid(int uid) { 5722 final int callingUid = Binder.getCallingUid(); 5723 if (getInstantAppPackageName(callingUid) != null) { 5724 return 0; 5725 } 5726 synchronized (mPackages) { 5727 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5728 if (obj instanceof SharedUserSetting) { 5729 final SharedUserSetting sus = (SharedUserSetting) obj; 5730 return sus.pkgFlags; 5731 } else if (obj instanceof PackageSetting) { 5732 final PackageSetting ps = (PackageSetting) obj; 5733 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5734 return 0; 5735 } 5736 return ps.pkgFlags; 5737 } 5738 } 5739 return 0; 5740 } 5741 5742 @Override 5743 public int getPrivateFlagsForUid(int uid) { 5744 final int callingUid = Binder.getCallingUid(); 5745 if (getInstantAppPackageName(callingUid) != null) { 5746 return 0; 5747 } 5748 synchronized (mPackages) { 5749 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5750 if (obj instanceof SharedUserSetting) { 5751 final SharedUserSetting sus = (SharedUserSetting) obj; 5752 return sus.pkgPrivateFlags; 5753 } else if (obj instanceof PackageSetting) { 5754 final PackageSetting ps = (PackageSetting) obj; 5755 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5756 return 0; 5757 } 5758 return ps.pkgPrivateFlags; 5759 } 5760 } 5761 return 0; 5762 } 5763 5764 @Override 5765 public boolean isUidPrivileged(int uid) { 5766 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5767 return false; 5768 } 5769 uid = UserHandle.getAppId(uid); 5770 // reader 5771 synchronized (mPackages) { 5772 Object obj = mSettings.getUserIdLPr(uid); 5773 if (obj instanceof SharedUserSetting) { 5774 final SharedUserSetting sus = (SharedUserSetting) obj; 5775 final Iterator<PackageSetting> it = sus.packages.iterator(); 5776 while (it.hasNext()) { 5777 if (it.next().isPrivileged()) { 5778 return true; 5779 } 5780 } 5781 } else if (obj instanceof PackageSetting) { 5782 final PackageSetting ps = (PackageSetting) obj; 5783 return ps.isPrivileged(); 5784 } 5785 } 5786 return false; 5787 } 5788 5789 @Override 5790 public String[] getAppOpPermissionPackages(String permName) { 5791 return mPermissionManager.getAppOpPermissionPackages(permName); 5792 } 5793 5794 @Override 5795 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5796 int flags, int userId) { 5797 return resolveIntentInternal( 5798 intent, resolvedType, flags, userId, false /*resolveForStart*/); 5799 } 5800 5801 /** 5802 * Normally instant apps can only be resolved when they're visible to the caller. 5803 * However, if {@code resolveForStart} is {@code true}, all instant apps are visible 5804 * since we need to allow the system to start any installed application. 5805 */ 5806 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5807 int flags, int userId, boolean resolveForStart) { 5808 try { 5809 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5810 5811 if (!sUserManager.exists(userId)) return null; 5812 final int callingUid = Binder.getCallingUid(); 5813 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 5814 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5815 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5816 5817 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5818 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5819 flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/); 5820 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5821 5822 final ResolveInfo bestChoice = 5823 chooseBestActivity(intent, resolvedType, flags, query, userId); 5824 return bestChoice; 5825 } finally { 5826 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5827 } 5828 } 5829 5830 @Override 5831 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5832 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5833 throw new SecurityException( 5834 "findPersistentPreferredActivity can only be run by the system"); 5835 } 5836 if (!sUserManager.exists(userId)) { 5837 return null; 5838 } 5839 final int callingUid = Binder.getCallingUid(); 5840 intent = updateIntentForResolve(intent); 5841 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5842 final int flags = updateFlagsForResolve( 5843 0, userId, intent, callingUid, false /*includeInstantApps*/); 5844 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5845 userId); 5846 synchronized (mPackages) { 5847 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5848 userId); 5849 } 5850 } 5851 5852 @Override 5853 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5854 IntentFilter filter, int match, ComponentName activity) { 5855 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5856 return; 5857 } 5858 final int userId = UserHandle.getCallingUserId(); 5859 if (DEBUG_PREFERRED) { 5860 Log.v(TAG, "setLastChosenActivity intent=" + intent 5861 + " resolvedType=" + resolvedType 5862 + " flags=" + flags 5863 + " filter=" + filter 5864 + " match=" + match 5865 + " activity=" + activity); 5866 filter.dump(new PrintStreamPrinter(System.out), " "); 5867 } 5868 intent.setComponent(null); 5869 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5870 userId); 5871 // Find any earlier preferred or last chosen entries and nuke them 5872 findPreferredActivity(intent, resolvedType, 5873 flags, query, 0, false, true, false, userId); 5874 // Add the new activity as the last chosen for this filter 5875 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5876 "Setting last chosen"); 5877 } 5878 5879 @Override 5880 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5881 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5882 return null; 5883 } 5884 final int userId = UserHandle.getCallingUserId(); 5885 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5886 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5887 userId); 5888 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5889 false, false, false, userId); 5890 } 5891 5892 /** 5893 * Returns whether or not instant apps have been disabled remotely. 5894 */ 5895 private boolean isEphemeralDisabled() { 5896 return mEphemeralAppsDisabled; 5897 } 5898 5899 private boolean isInstantAppAllowed( 5900 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5901 boolean skipPackageCheck) { 5902 if (mInstantAppResolverConnection == null) { 5903 return false; 5904 } 5905 if (mInstantAppInstallerActivity == null) { 5906 return false; 5907 } 5908 if (intent.getComponent() != null) { 5909 return false; 5910 } 5911 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5912 return false; 5913 } 5914 if (!skipPackageCheck && intent.getPackage() != null) { 5915 return false; 5916 } 5917 final boolean isWebUri = hasWebURI(intent); 5918 if (!isWebUri || intent.getData().getHost() == null) { 5919 return false; 5920 } 5921 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5922 // Or if there's already an ephemeral app installed that handles the action 5923 synchronized (mPackages) { 5924 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5925 for (int n = 0; n < count; n++) { 5926 final ResolveInfo info = resolvedActivities.get(n); 5927 final String packageName = info.activityInfo.packageName; 5928 final PackageSetting ps = mSettings.mPackages.get(packageName); 5929 if (ps != null) { 5930 // only check domain verification status if the app is not a browser 5931 if (!info.handleAllWebDataURI) { 5932 // Try to get the status from User settings first 5933 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5934 final int status = (int) (packedStatus >> 32); 5935 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5936 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5937 if (DEBUG_EPHEMERAL) { 5938 Slog.v(TAG, "DENY instant app;" 5939 + " pkg: " + packageName + ", status: " + status); 5940 } 5941 return false; 5942 } 5943 } 5944 if (ps.getInstantApp(userId)) { 5945 if (DEBUG_EPHEMERAL) { 5946 Slog.v(TAG, "DENY instant app installed;" 5947 + " pkg: " + packageName); 5948 } 5949 return false; 5950 } 5951 } 5952 } 5953 } 5954 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5955 return true; 5956 } 5957 5958 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5959 Intent origIntent, String resolvedType, String callingPackage, 5960 Bundle verificationBundle, int userId) { 5961 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5962 new InstantAppRequest(responseObj, origIntent, resolvedType, 5963 callingPackage, userId, verificationBundle, false /*resolveForStart*/)); 5964 mHandler.sendMessage(msg); 5965 } 5966 5967 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5968 int flags, List<ResolveInfo> query, int userId) { 5969 if (query != null) { 5970 final int N = query.size(); 5971 if (N == 1) { 5972 return query.get(0); 5973 } else if (N > 1) { 5974 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5975 // If there is more than one activity with the same priority, 5976 // then let the user decide between them. 5977 ResolveInfo r0 = query.get(0); 5978 ResolveInfo r1 = query.get(1); 5979 if (DEBUG_INTENT_MATCHING || debug) { 5980 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5981 + r1.activityInfo.name + "=" + r1.priority); 5982 } 5983 // If the first activity has a higher priority, or a different 5984 // default, then it is always desirable to pick it. 5985 if (r0.priority != r1.priority 5986 || r0.preferredOrder != r1.preferredOrder 5987 || r0.isDefault != r1.isDefault) { 5988 return query.get(0); 5989 } 5990 // If we have saved a preference for a preferred activity for 5991 // this Intent, use that. 5992 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5993 flags, query, r0.priority, true, false, debug, userId); 5994 if (ri != null) { 5995 return ri; 5996 } 5997 // If we have an ephemeral app, use it 5998 for (int i = 0; i < N; i++) { 5999 ri = query.get(i); 6000 if (ri.activityInfo.applicationInfo.isInstantApp()) { 6001 final String packageName = ri.activityInfo.packageName; 6002 final PackageSetting ps = mSettings.mPackages.get(packageName); 6003 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6004 final int status = (int)(packedStatus >> 32); 6005 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6006 return ri; 6007 } 6008 } 6009 } 6010 ri = new ResolveInfo(mResolveInfo); 6011 ri.activityInfo = new ActivityInfo(ri.activityInfo); 6012 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 6013 // If all of the options come from the same package, show the application's 6014 // label and icon instead of the generic resolver's. 6015 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 6016 // and then throw away the ResolveInfo itself, meaning that the caller loses 6017 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 6018 // a fallback for this case; we only set the target package's resources on 6019 // the ResolveInfo, not the ActivityInfo. 6020 final String intentPackage = intent.getPackage(); 6021 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 6022 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 6023 ri.resolvePackageName = intentPackage; 6024 if (userNeedsBadging(userId)) { 6025 ri.noResourceId = true; 6026 } else { 6027 ri.icon = appi.icon; 6028 } 6029 ri.iconResourceId = appi.icon; 6030 ri.labelRes = appi.labelRes; 6031 } 6032 ri.activityInfo.applicationInfo = new ApplicationInfo( 6033 ri.activityInfo.applicationInfo); 6034 if (userId != 0) { 6035 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6036 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6037 } 6038 // Make sure that the resolver is displayable in car mode 6039 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6040 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6041 return ri; 6042 } 6043 } 6044 return null; 6045 } 6046 6047 /** 6048 * Return true if the given list is not empty and all of its contents have 6049 * an activityInfo with the given package name. 6050 */ 6051 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6052 if (ArrayUtils.isEmpty(list)) { 6053 return false; 6054 } 6055 for (int i = 0, N = list.size(); i < N; i++) { 6056 final ResolveInfo ri = list.get(i); 6057 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6058 if (ai == null || !packageName.equals(ai.packageName)) { 6059 return false; 6060 } 6061 } 6062 return true; 6063 } 6064 6065 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6066 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6067 final int N = query.size(); 6068 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6069 .get(userId); 6070 // Get the list of persistent preferred activities that handle the intent 6071 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6072 List<PersistentPreferredActivity> pprefs = ppir != null 6073 ? ppir.queryIntent(intent, resolvedType, 6074 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6075 userId) 6076 : null; 6077 if (pprefs != null && pprefs.size() > 0) { 6078 final int M = pprefs.size(); 6079 for (int i=0; i<M; i++) { 6080 final PersistentPreferredActivity ppa = pprefs.get(i); 6081 if (DEBUG_PREFERRED || debug) { 6082 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6083 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6084 + "\n component=" + ppa.mComponent); 6085 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6086 } 6087 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6088 flags | MATCH_DISABLED_COMPONENTS, userId); 6089 if (DEBUG_PREFERRED || debug) { 6090 Slog.v(TAG, "Found persistent preferred activity:"); 6091 if (ai != null) { 6092 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6093 } else { 6094 Slog.v(TAG, " null"); 6095 } 6096 } 6097 if (ai == null) { 6098 // This previously registered persistent preferred activity 6099 // component is no longer known. Ignore it and do NOT remove it. 6100 continue; 6101 } 6102 for (int j=0; j<N; j++) { 6103 final ResolveInfo ri = query.get(j); 6104 if (!ri.activityInfo.applicationInfo.packageName 6105 .equals(ai.applicationInfo.packageName)) { 6106 continue; 6107 } 6108 if (!ri.activityInfo.name.equals(ai.name)) { 6109 continue; 6110 } 6111 // Found a persistent preference that can handle the intent. 6112 if (DEBUG_PREFERRED || debug) { 6113 Slog.v(TAG, "Returning persistent preferred activity: " + 6114 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6115 } 6116 return ri; 6117 } 6118 } 6119 } 6120 return null; 6121 } 6122 6123 // TODO: handle preferred activities missing while user has amnesia 6124 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6125 List<ResolveInfo> query, int priority, boolean always, 6126 boolean removeMatches, boolean debug, int userId) { 6127 if (!sUserManager.exists(userId)) return null; 6128 final int callingUid = Binder.getCallingUid(); 6129 flags = updateFlagsForResolve( 6130 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6131 intent = updateIntentForResolve(intent); 6132 // writer 6133 synchronized (mPackages) { 6134 // Try to find a matching persistent preferred activity. 6135 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6136 debug, userId); 6137 6138 // If a persistent preferred activity matched, use it. 6139 if (pri != null) { 6140 return pri; 6141 } 6142 6143 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6144 // Get the list of preferred activities that handle the intent 6145 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6146 List<PreferredActivity> prefs = pir != null 6147 ? pir.queryIntent(intent, resolvedType, 6148 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6149 userId) 6150 : null; 6151 if (prefs != null && prefs.size() > 0) { 6152 boolean changed = false; 6153 try { 6154 // First figure out how good the original match set is. 6155 // We will only allow preferred activities that came 6156 // from the same match quality. 6157 int match = 0; 6158 6159 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6160 6161 final int N = query.size(); 6162 for (int j=0; j<N; j++) { 6163 final ResolveInfo ri = query.get(j); 6164 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6165 + ": 0x" + Integer.toHexString(match)); 6166 if (ri.match > match) { 6167 match = ri.match; 6168 } 6169 } 6170 6171 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6172 + Integer.toHexString(match)); 6173 6174 match &= IntentFilter.MATCH_CATEGORY_MASK; 6175 final int M = prefs.size(); 6176 for (int i=0; i<M; i++) { 6177 final PreferredActivity pa = prefs.get(i); 6178 if (DEBUG_PREFERRED || debug) { 6179 Slog.v(TAG, "Checking PreferredActivity ds=" 6180 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6181 + "\n component=" + pa.mPref.mComponent); 6182 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6183 } 6184 if (pa.mPref.mMatch != match) { 6185 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6186 + Integer.toHexString(pa.mPref.mMatch)); 6187 continue; 6188 } 6189 // If it's not an "always" type preferred activity and that's what we're 6190 // looking for, skip it. 6191 if (always && !pa.mPref.mAlways) { 6192 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6193 continue; 6194 } 6195 final ActivityInfo ai = getActivityInfo( 6196 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6197 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6198 userId); 6199 if (DEBUG_PREFERRED || debug) { 6200 Slog.v(TAG, "Found preferred activity:"); 6201 if (ai != null) { 6202 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6203 } else { 6204 Slog.v(TAG, " null"); 6205 } 6206 } 6207 if (ai == null) { 6208 // This previously registered preferred activity 6209 // component is no longer known. Most likely an update 6210 // to the app was installed and in the new version this 6211 // component no longer exists. Clean it up by removing 6212 // it from the preferred activities list, and skip it. 6213 Slog.w(TAG, "Removing dangling preferred activity: " 6214 + pa.mPref.mComponent); 6215 pir.removeFilter(pa); 6216 changed = true; 6217 continue; 6218 } 6219 for (int j=0; j<N; j++) { 6220 final ResolveInfo ri = query.get(j); 6221 if (!ri.activityInfo.applicationInfo.packageName 6222 .equals(ai.applicationInfo.packageName)) { 6223 continue; 6224 } 6225 if (!ri.activityInfo.name.equals(ai.name)) { 6226 continue; 6227 } 6228 6229 if (removeMatches) { 6230 pir.removeFilter(pa); 6231 changed = true; 6232 if (DEBUG_PREFERRED) { 6233 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6234 } 6235 break; 6236 } 6237 6238 // Okay we found a previously set preferred or last chosen app. 6239 // If the result set is different from when this 6240 // was created, and is not a subset of the preferred set, we need to 6241 // clear it and re-ask the user their preference, if we're looking for 6242 // an "always" type entry. 6243 if (always && !pa.mPref.sameSet(query)) { 6244 if (pa.mPref.isSuperset(query)) { 6245 // some components of the set are no longer present in 6246 // the query, but the preferred activity can still be reused 6247 if (DEBUG_PREFERRED) { 6248 Slog.i(TAG, "Result set changed, but PreferredActivity is" 6249 + " still valid as only non-preferred components" 6250 + " were removed for " + intent + " type " 6251 + resolvedType); 6252 } 6253 // remove obsolete components and re-add the up-to-date filter 6254 PreferredActivity freshPa = new PreferredActivity(pa, 6255 pa.mPref.mMatch, 6256 pa.mPref.discardObsoleteComponents(query), 6257 pa.mPref.mComponent, 6258 pa.mPref.mAlways); 6259 pir.removeFilter(pa); 6260 pir.addFilter(freshPa); 6261 changed = true; 6262 } else { 6263 Slog.i(TAG, 6264 "Result set changed, dropping preferred activity for " 6265 + intent + " type " + resolvedType); 6266 if (DEBUG_PREFERRED) { 6267 Slog.v(TAG, "Removing preferred activity since set changed " 6268 + pa.mPref.mComponent); 6269 } 6270 pir.removeFilter(pa); 6271 // Re-add the filter as a "last chosen" entry (!always) 6272 PreferredActivity lastChosen = new PreferredActivity( 6273 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6274 pir.addFilter(lastChosen); 6275 changed = true; 6276 return null; 6277 } 6278 } 6279 6280 // Yay! Either the set matched or we're looking for the last chosen 6281 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6282 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6283 return ri; 6284 } 6285 } 6286 } finally { 6287 if (changed) { 6288 if (DEBUG_PREFERRED) { 6289 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6290 } 6291 scheduleWritePackageRestrictionsLocked(userId); 6292 } 6293 } 6294 } 6295 } 6296 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6297 return null; 6298 } 6299 6300 /* 6301 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6302 */ 6303 @Override 6304 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6305 int targetUserId) { 6306 mContext.enforceCallingOrSelfPermission( 6307 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6308 List<CrossProfileIntentFilter> matches = 6309 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6310 if (matches != null) { 6311 int size = matches.size(); 6312 for (int i = 0; i < size; i++) { 6313 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6314 } 6315 } 6316 if (hasWebURI(intent)) { 6317 // cross-profile app linking works only towards the parent. 6318 final int callingUid = Binder.getCallingUid(); 6319 final UserInfo parent = getProfileParent(sourceUserId); 6320 synchronized(mPackages) { 6321 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6322 false /*includeInstantApps*/); 6323 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6324 intent, resolvedType, flags, sourceUserId, parent.id); 6325 return xpDomainInfo != null; 6326 } 6327 } 6328 return false; 6329 } 6330 6331 private UserInfo getProfileParent(int userId) { 6332 final long identity = Binder.clearCallingIdentity(); 6333 try { 6334 return sUserManager.getProfileParent(userId); 6335 } finally { 6336 Binder.restoreCallingIdentity(identity); 6337 } 6338 } 6339 6340 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6341 String resolvedType, int userId) { 6342 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6343 if (resolver != null) { 6344 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6345 } 6346 return null; 6347 } 6348 6349 @Override 6350 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6351 String resolvedType, int flags, int userId) { 6352 try { 6353 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6354 6355 return new ParceledListSlice<>( 6356 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6357 } finally { 6358 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6359 } 6360 } 6361 6362 /** 6363 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6364 * instant, returns {@code null}. 6365 */ 6366 private String getInstantAppPackageName(int callingUid) { 6367 synchronized (mPackages) { 6368 // If the caller is an isolated app use the owner's uid for the lookup. 6369 if (Process.isIsolated(callingUid)) { 6370 callingUid = mIsolatedOwners.get(callingUid); 6371 } 6372 final int appId = UserHandle.getAppId(callingUid); 6373 final Object obj = mSettings.getUserIdLPr(appId); 6374 if (obj instanceof PackageSetting) { 6375 final PackageSetting ps = (PackageSetting) obj; 6376 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6377 return isInstantApp ? ps.pkg.packageName : null; 6378 } 6379 } 6380 return null; 6381 } 6382 6383 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6384 String resolvedType, int flags, int userId) { 6385 return queryIntentActivitiesInternal( 6386 intent, resolvedType, flags, Binder.getCallingUid(), userId, 6387 false /*resolveForStart*/, true /*allowDynamicSplits*/); 6388 } 6389 6390 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6391 String resolvedType, int flags, int filterCallingUid, int userId, 6392 boolean resolveForStart, boolean allowDynamicSplits) { 6393 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6394 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 6395 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 6396 false /* requireFullPermission */, false /* checkShell */, 6397 "query intent activities"); 6398 final String pkgName = intent.getPackage(); 6399 ComponentName comp = intent.getComponent(); 6400 if (comp == null) { 6401 if (intent.getSelector() != null) { 6402 intent = intent.getSelector(); 6403 comp = intent.getComponent(); 6404 } 6405 } 6406 6407 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 6408 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6409 if (comp != null) { 6410 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6411 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6412 if (ai != null) { 6413 // When specifying an explicit component, we prevent the activity from being 6414 // used when either 1) the calling package is normal and the activity is within 6415 // an ephemeral application or 2) the calling package is ephemeral and the 6416 // activity is not visible to ephemeral applications. 6417 final boolean matchInstantApp = 6418 (flags & PackageManager.MATCH_INSTANT) != 0; 6419 final boolean matchVisibleToInstantAppOnly = 6420 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6421 final boolean matchExplicitlyVisibleOnly = 6422 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6423 final boolean isCallerInstantApp = 6424 instantAppPkgName != null; 6425 final boolean isTargetSameInstantApp = 6426 comp.getPackageName().equals(instantAppPkgName); 6427 final boolean isTargetInstantApp = 6428 (ai.applicationInfo.privateFlags 6429 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6430 final boolean isTargetVisibleToInstantApp = 6431 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6432 final boolean isTargetExplicitlyVisibleToInstantApp = 6433 isTargetVisibleToInstantApp 6434 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6435 final boolean isTargetHiddenFromInstantApp = 6436 !isTargetVisibleToInstantApp 6437 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6438 final boolean blockResolution = 6439 !isTargetSameInstantApp 6440 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6441 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6442 && isTargetHiddenFromInstantApp)); 6443 if (!blockResolution) { 6444 final ResolveInfo ri = new ResolveInfo(); 6445 ri.activityInfo = ai; 6446 list.add(ri); 6447 } 6448 } 6449 return applyPostResolutionFilter( 6450 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6451 } 6452 6453 // reader 6454 boolean sortResult = false; 6455 boolean addEphemeral = false; 6456 List<ResolveInfo> result; 6457 final boolean ephemeralDisabled = isEphemeralDisabled(); 6458 synchronized (mPackages) { 6459 if (pkgName == null) { 6460 List<CrossProfileIntentFilter> matchingFilters = 6461 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6462 // Check for results that need to skip the current profile. 6463 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6464 resolvedType, flags, userId); 6465 if (xpResolveInfo != null) { 6466 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6467 xpResult.add(xpResolveInfo); 6468 return applyPostResolutionFilter( 6469 filterIfNotSystemUser(xpResult, userId), instantAppPkgName, 6470 allowDynamicSplits, filterCallingUid, userId); 6471 } 6472 6473 // Check for results in the current profile. 6474 result = filterIfNotSystemUser(mActivities.queryIntent( 6475 intent, resolvedType, flags, userId), userId); 6476 addEphemeral = !ephemeralDisabled 6477 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/); 6478 // Check for cross profile results. 6479 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6480 xpResolveInfo = queryCrossProfileIntents( 6481 matchingFilters, intent, resolvedType, flags, userId, 6482 hasNonNegativePriorityResult); 6483 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6484 boolean isVisibleToUser = filterIfNotSystemUser( 6485 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6486 if (isVisibleToUser) { 6487 result.add(xpResolveInfo); 6488 sortResult = true; 6489 } 6490 } 6491 if (hasWebURI(intent)) { 6492 CrossProfileDomainInfo xpDomainInfo = null; 6493 final UserInfo parent = getProfileParent(userId); 6494 if (parent != null) { 6495 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6496 flags, userId, parent.id); 6497 } 6498 if (xpDomainInfo != null) { 6499 if (xpResolveInfo != null) { 6500 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6501 // in the result. 6502 result.remove(xpResolveInfo); 6503 } 6504 if (result.size() == 0 && !addEphemeral) { 6505 // No result in current profile, but found candidate in parent user. 6506 // And we are not going to add emphemeral app, so we can return the 6507 // result straight away. 6508 result.add(xpDomainInfo.resolveInfo); 6509 return applyPostResolutionFilter(result, instantAppPkgName, 6510 allowDynamicSplits, filterCallingUid, userId); 6511 } 6512 } else if (result.size() <= 1 && !addEphemeral) { 6513 // No result in parent user and <= 1 result in current profile, and we 6514 // are not going to add emphemeral app, so we can return the result without 6515 // further processing. 6516 return applyPostResolutionFilter(result, instantAppPkgName, 6517 allowDynamicSplits, filterCallingUid, userId); 6518 } 6519 // We have more than one candidate (combining results from current and parent 6520 // profile), so we need filtering and sorting. 6521 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6522 intent, flags, result, xpDomainInfo, userId); 6523 sortResult = true; 6524 } 6525 } else { 6526 final PackageParser.Package pkg = mPackages.get(pkgName); 6527 result = null; 6528 if (pkg != null) { 6529 result = filterIfNotSystemUser( 6530 mActivities.queryIntentForPackage( 6531 intent, resolvedType, flags, pkg.activities, userId), 6532 userId); 6533 } 6534 if (result == null || result.size() == 0) { 6535 // the caller wants to resolve for a particular package; however, there 6536 // were no installed results, so, try to find an ephemeral result 6537 addEphemeral = !ephemeralDisabled 6538 && isInstantAppAllowed( 6539 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6540 if (result == null) { 6541 result = new ArrayList<>(); 6542 } 6543 } 6544 } 6545 } 6546 if (addEphemeral) { 6547 result = maybeAddInstantAppInstaller( 6548 result, intent, resolvedType, flags, userId, resolveForStart); 6549 } 6550 if (sortResult) { 6551 Collections.sort(result, mResolvePrioritySorter); 6552 } 6553 return applyPostResolutionFilter( 6554 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6555 } 6556 6557 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 6558 String resolvedType, int flags, int userId, boolean resolveForStart) { 6559 // first, check to see if we've got an instant app already installed 6560 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 6561 ResolveInfo localInstantApp = null; 6562 boolean blockResolution = false; 6563 if (!alreadyResolvedLocally) { 6564 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 6565 flags 6566 | PackageManager.GET_RESOLVED_FILTER 6567 | PackageManager.MATCH_INSTANT 6568 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 6569 userId); 6570 for (int i = instantApps.size() - 1; i >= 0; --i) { 6571 final ResolveInfo info = instantApps.get(i); 6572 final String packageName = info.activityInfo.packageName; 6573 final PackageSetting ps = mSettings.mPackages.get(packageName); 6574 if (ps.getInstantApp(userId)) { 6575 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6576 final int status = (int)(packedStatus >> 32); 6577 final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6578 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6579 // there's a local instant application installed, but, the user has 6580 // chosen to never use it; skip resolution and don't acknowledge 6581 // an instant application is even available 6582 if (DEBUG_EPHEMERAL) { 6583 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 6584 } 6585 blockResolution = true; 6586 break; 6587 } else { 6588 // we have a locally installed instant application; skip resolution 6589 // but acknowledge there's an instant application available 6590 if (DEBUG_EPHEMERAL) { 6591 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 6592 } 6593 localInstantApp = info; 6594 break; 6595 } 6596 } 6597 } 6598 } 6599 // no app installed, let's see if one's available 6600 AuxiliaryResolveInfo auxiliaryResponse = null; 6601 if (!blockResolution) { 6602 if (localInstantApp == null) { 6603 // we don't have an instant app locally, resolve externally 6604 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6605 final InstantAppRequest requestObject = new InstantAppRequest( 6606 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6607 null /*callingPackage*/, userId, null /*verificationBundle*/, 6608 resolveForStart); 6609 auxiliaryResponse = 6610 InstantAppResolver.doInstantAppResolutionPhaseOne( 6611 mContext, mInstantAppResolverConnection, requestObject); 6612 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6613 } else { 6614 // we have an instant application locally, but, we can't admit that since 6615 // callers shouldn't be able to determine prior browsing. create a dummy 6616 // auxiliary response so the downstream code behaves as if there's an 6617 // instant application available externally. when it comes time to start 6618 // the instant application, we'll do the right thing. 6619 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 6620 auxiliaryResponse = new AuxiliaryResolveInfo( 6621 ai.packageName, null /*splitName*/, null /*failureActivity*/, 6622 ai.versionCode, null /*failureIntent*/); 6623 } 6624 } 6625 if (auxiliaryResponse != null) { 6626 if (DEBUG_EPHEMERAL) { 6627 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6628 } 6629 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6630 final PackageSetting ps = 6631 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6632 if (ps != null) { 6633 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6634 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6635 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6636 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6637 // make sure this resolver is the default 6638 ephemeralInstaller.isDefault = true; 6639 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6640 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6641 // add a non-generic filter 6642 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6643 ephemeralInstaller.filter.addDataPath( 6644 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6645 ephemeralInstaller.isInstantAppAvailable = true; 6646 result.add(ephemeralInstaller); 6647 } 6648 } 6649 return result; 6650 } 6651 6652 private static class CrossProfileDomainInfo { 6653 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6654 ResolveInfo resolveInfo; 6655 /* Best domain verification status of the activities found in the other profile */ 6656 int bestDomainVerificationStatus; 6657 } 6658 6659 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6660 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6661 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6662 sourceUserId)) { 6663 return null; 6664 } 6665 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6666 resolvedType, flags, parentUserId); 6667 6668 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6669 return null; 6670 } 6671 CrossProfileDomainInfo result = null; 6672 int size = resultTargetUser.size(); 6673 for (int i = 0; i < size; i++) { 6674 ResolveInfo riTargetUser = resultTargetUser.get(i); 6675 // Intent filter verification is only for filters that specify a host. So don't return 6676 // those that handle all web uris. 6677 if (riTargetUser.handleAllWebDataURI) { 6678 continue; 6679 } 6680 String packageName = riTargetUser.activityInfo.packageName; 6681 PackageSetting ps = mSettings.mPackages.get(packageName); 6682 if (ps == null) { 6683 continue; 6684 } 6685 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6686 int status = (int)(verificationState >> 32); 6687 if (result == null) { 6688 result = new CrossProfileDomainInfo(); 6689 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6690 sourceUserId, parentUserId); 6691 result.bestDomainVerificationStatus = status; 6692 } else { 6693 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6694 result.bestDomainVerificationStatus); 6695 } 6696 } 6697 // Don't consider matches with status NEVER across profiles. 6698 if (result != null && result.bestDomainVerificationStatus 6699 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6700 return null; 6701 } 6702 return result; 6703 } 6704 6705 /** 6706 * Verification statuses are ordered from the worse to the best, except for 6707 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6708 */ 6709 private int bestDomainVerificationStatus(int status1, int status2) { 6710 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6711 return status2; 6712 } 6713 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6714 return status1; 6715 } 6716 return (int) MathUtils.max(status1, status2); 6717 } 6718 6719 private boolean isUserEnabled(int userId) { 6720 long callingId = Binder.clearCallingIdentity(); 6721 try { 6722 UserInfo userInfo = sUserManager.getUserInfo(userId); 6723 return userInfo != null && userInfo.isEnabled(); 6724 } finally { 6725 Binder.restoreCallingIdentity(callingId); 6726 } 6727 } 6728 6729 /** 6730 * Filter out activities with systemUserOnly flag set, when current user is not System. 6731 * 6732 * @return filtered list 6733 */ 6734 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6735 if (userId == UserHandle.USER_SYSTEM) { 6736 return resolveInfos; 6737 } 6738 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6739 ResolveInfo info = resolveInfos.get(i); 6740 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6741 resolveInfos.remove(i); 6742 } 6743 } 6744 return resolveInfos; 6745 } 6746 6747 /** 6748 * Filters out ephemeral activities. 6749 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6750 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6751 * 6752 * @param resolveInfos The pre-filtered list of resolved activities 6753 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6754 * is performed. 6755 * @return A filtered list of resolved activities. 6756 */ 6757 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6758 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) { 6759 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6760 final ResolveInfo info = resolveInfos.get(i); 6761 // allow activities that are defined in the provided package 6762 if (allowDynamicSplits 6763 && info.activityInfo.splitName != null 6764 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6765 info.activityInfo.splitName)) { 6766 if (mInstantAppInstallerInfo == null) { 6767 if (DEBUG_INSTALL) { 6768 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 6769 } 6770 resolveInfos.remove(i); 6771 continue; 6772 } 6773 // requested activity is defined in a split that hasn't been installed yet. 6774 // add the installer to the resolve list 6775 if (DEBUG_INSTALL) { 6776 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 6777 } 6778 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6779 final ComponentName installFailureActivity = findInstallFailureActivity( 6780 info.activityInfo.packageName, filterCallingUid, userId); 6781 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6782 info.activityInfo.packageName, info.activityInfo.splitName, 6783 installFailureActivity, 6784 info.activityInfo.applicationInfo.versionCode, 6785 null /*failureIntent*/); 6786 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6787 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6788 // add a non-generic filter 6789 installerInfo.filter = new IntentFilter(); 6790 6791 // This resolve info may appear in the chooser UI, so let us make it 6792 // look as the one it replaces as far as the user is concerned which 6793 // requires loading the correct label and icon for the resolve info. 6794 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6795 installerInfo.labelRes = info.resolveLabelResId(); 6796 installerInfo.icon = info.resolveIconResId(); 6797 6798 // propagate priority/preferred order/default 6799 installerInfo.priority = info.priority; 6800 installerInfo.preferredOrder = info.preferredOrder; 6801 installerInfo.isDefault = info.isDefault; 6802 resolveInfos.set(i, installerInfo); 6803 continue; 6804 } 6805 // caller is a full app, don't need to apply any other filtering 6806 if (ephemeralPkgName == null) { 6807 continue; 6808 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 6809 // caller is same app; don't need to apply any other filtering 6810 continue; 6811 } 6812 // allow activities that have been explicitly exposed to ephemeral apps 6813 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6814 if (!isEphemeralApp 6815 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 6816 continue; 6817 } 6818 resolveInfos.remove(i); 6819 } 6820 return resolveInfos; 6821 } 6822 6823 /** 6824 * Returns the activity component that can handle install failures. 6825 * <p>By default, the instant application installer handles failures. However, an 6826 * application may want to handle failures on its own. Applications do this by 6827 * creating an activity with an intent filter that handles the action 6828 * {@link Intent#ACTION_INSTALL_FAILURE}. 6829 */ 6830 private @Nullable ComponentName findInstallFailureActivity( 6831 String packageName, int filterCallingUid, int userId) { 6832 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 6833 failureActivityIntent.setPackage(packageName); 6834 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 6835 final List<ResolveInfo> result = queryIntentActivitiesInternal( 6836 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId, 6837 false /*resolveForStart*/, false /*allowDynamicSplits*/); 6838 final int NR = result.size(); 6839 if (NR > 0) { 6840 for (int i = 0; i < NR; i++) { 6841 final ResolveInfo info = result.get(i); 6842 if (info.activityInfo.splitName != null) { 6843 continue; 6844 } 6845 return new ComponentName(packageName, info.activityInfo.name); 6846 } 6847 } 6848 return null; 6849 } 6850 6851 /** 6852 * @param resolveInfos list of resolve infos in descending priority order 6853 * @return if the list contains a resolve info with non-negative priority 6854 */ 6855 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6856 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6857 } 6858 6859 private static boolean hasWebURI(Intent intent) { 6860 if (intent.getData() == null) { 6861 return false; 6862 } 6863 final String scheme = intent.getScheme(); 6864 if (TextUtils.isEmpty(scheme)) { 6865 return false; 6866 } 6867 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6868 } 6869 6870 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6871 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6872 int userId) { 6873 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6874 6875 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6876 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6877 candidates.size()); 6878 } 6879 6880 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6881 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6882 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6883 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6884 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6885 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6886 6887 synchronized (mPackages) { 6888 final int count = candidates.size(); 6889 // First, try to use linked apps. Partition the candidates into four lists: 6890 // one for the final results, one for the "do not use ever", one for "undefined status" 6891 // and finally one for "browser app type". 6892 for (int n=0; n<count; n++) { 6893 ResolveInfo info = candidates.get(n); 6894 String packageName = info.activityInfo.packageName; 6895 PackageSetting ps = mSettings.mPackages.get(packageName); 6896 if (ps != null) { 6897 // Add to the special match all list (Browser use case) 6898 if (info.handleAllWebDataURI) { 6899 matchAllList.add(info); 6900 continue; 6901 } 6902 // Try to get the status from User settings first 6903 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6904 int status = (int)(packedStatus >> 32); 6905 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6906 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6907 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6908 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6909 + " : linkgen=" + linkGeneration); 6910 } 6911 // Use link-enabled generation as preferredOrder, i.e. 6912 // prefer newly-enabled over earlier-enabled. 6913 info.preferredOrder = linkGeneration; 6914 alwaysList.add(info); 6915 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6916 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6917 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6918 } 6919 neverList.add(info); 6920 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6921 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6922 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6923 } 6924 alwaysAskList.add(info); 6925 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6926 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6927 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6928 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6929 } 6930 undefinedList.add(info); 6931 } 6932 } 6933 } 6934 6935 // We'll want to include browser possibilities in a few cases 6936 boolean includeBrowser = false; 6937 6938 // First try to add the "always" resolution(s) for the current user, if any 6939 if (alwaysList.size() > 0) { 6940 result.addAll(alwaysList); 6941 } else { 6942 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6943 result.addAll(undefinedList); 6944 // Maybe add one for the other profile. 6945 if (xpDomainInfo != null && ( 6946 xpDomainInfo.bestDomainVerificationStatus 6947 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6948 result.add(xpDomainInfo.resolveInfo); 6949 } 6950 includeBrowser = true; 6951 } 6952 6953 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6954 // If there were 'always' entries their preferred order has been set, so we also 6955 // back that off to make the alternatives equivalent 6956 if (alwaysAskList.size() > 0) { 6957 for (ResolveInfo i : result) { 6958 i.preferredOrder = 0; 6959 } 6960 result.addAll(alwaysAskList); 6961 includeBrowser = true; 6962 } 6963 6964 if (includeBrowser) { 6965 // Also add browsers (all of them or only the default one) 6966 if (DEBUG_DOMAIN_VERIFICATION) { 6967 Slog.v(TAG, " ...including browsers in candidate set"); 6968 } 6969 if ((matchFlags & MATCH_ALL) != 0) { 6970 result.addAll(matchAllList); 6971 } else { 6972 // Browser/generic handling case. If there's a default browser, go straight 6973 // to that (but only if there is no other higher-priority match). 6974 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6975 int maxMatchPrio = 0; 6976 ResolveInfo defaultBrowserMatch = null; 6977 final int numCandidates = matchAllList.size(); 6978 for (int n = 0; n < numCandidates; n++) { 6979 ResolveInfo info = matchAllList.get(n); 6980 // track the highest overall match priority... 6981 if (info.priority > maxMatchPrio) { 6982 maxMatchPrio = info.priority; 6983 } 6984 // ...and the highest-priority default browser match 6985 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6986 if (defaultBrowserMatch == null 6987 || (defaultBrowserMatch.priority < info.priority)) { 6988 if (debug) { 6989 Slog.v(TAG, "Considering default browser match " + info); 6990 } 6991 defaultBrowserMatch = info; 6992 } 6993 } 6994 } 6995 if (defaultBrowserMatch != null 6996 && defaultBrowserMatch.priority >= maxMatchPrio 6997 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6998 { 6999 if (debug) { 7000 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 7001 } 7002 result.add(defaultBrowserMatch); 7003 } else { 7004 result.addAll(matchAllList); 7005 } 7006 } 7007 7008 // If there is nothing selected, add all candidates and remove the ones that the user 7009 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 7010 if (result.size() == 0) { 7011 result.addAll(candidates); 7012 result.removeAll(neverList); 7013 } 7014 } 7015 } 7016 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7017 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 7018 result.size()); 7019 for (ResolveInfo info : result) { 7020 Slog.v(TAG, " + " + info.activityInfo); 7021 } 7022 } 7023 return result; 7024 } 7025 7026 // Returns a packed value as a long: 7027 // 7028 // high 'int'-sized word: link status: undefined/ask/never/always. 7029 // low 'int'-sized word: relative priority among 'always' results. 7030 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 7031 long result = ps.getDomainVerificationStatusForUser(userId); 7032 // if none available, get the master status 7033 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 7034 if (ps.getIntentFilterVerificationInfo() != null) { 7035 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 7036 } 7037 } 7038 return result; 7039 } 7040 7041 private ResolveInfo querySkipCurrentProfileIntents( 7042 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7043 int flags, int sourceUserId) { 7044 if (matchingFilters != null) { 7045 int size = matchingFilters.size(); 7046 for (int i = 0; i < size; i ++) { 7047 CrossProfileIntentFilter filter = matchingFilters.get(i); 7048 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 7049 // Checking if there are activities in the target user that can handle the 7050 // intent. 7051 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7052 resolvedType, flags, sourceUserId); 7053 if (resolveInfo != null) { 7054 return resolveInfo; 7055 } 7056 } 7057 } 7058 } 7059 return null; 7060 } 7061 7062 // Return matching ResolveInfo in target user if any. 7063 private ResolveInfo queryCrossProfileIntents( 7064 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7065 int flags, int sourceUserId, boolean matchInCurrentProfile) { 7066 if (matchingFilters != null) { 7067 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 7068 // match the same intent. For performance reasons, it is better not to 7069 // run queryIntent twice for the same userId 7070 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 7071 int size = matchingFilters.size(); 7072 for (int i = 0; i < size; i++) { 7073 CrossProfileIntentFilter filter = matchingFilters.get(i); 7074 int targetUserId = filter.getTargetUserId(); 7075 boolean skipCurrentProfile = 7076 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 7077 boolean skipCurrentProfileIfNoMatchFound = 7078 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 7079 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 7080 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 7081 // Checking if there are activities in the target user that can handle the 7082 // intent. 7083 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7084 resolvedType, flags, sourceUserId); 7085 if (resolveInfo != null) return resolveInfo; 7086 alreadyTriedUserIds.put(targetUserId, true); 7087 } 7088 } 7089 } 7090 return null; 7091 } 7092 7093 /** 7094 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 7095 * will forward the intent to the filter's target user. 7096 * Otherwise, returns null. 7097 */ 7098 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 7099 String resolvedType, int flags, int sourceUserId) { 7100 int targetUserId = filter.getTargetUserId(); 7101 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7102 resolvedType, flags, targetUserId); 7103 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7104 // If all the matches in the target profile are suspended, return null. 7105 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7106 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7107 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7108 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7109 targetUserId); 7110 } 7111 } 7112 } 7113 return null; 7114 } 7115 7116 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7117 int sourceUserId, int targetUserId) { 7118 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7119 long ident = Binder.clearCallingIdentity(); 7120 boolean targetIsProfile; 7121 try { 7122 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7123 } finally { 7124 Binder.restoreCallingIdentity(ident); 7125 } 7126 String className; 7127 if (targetIsProfile) { 7128 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7129 } else { 7130 className = FORWARD_INTENT_TO_PARENT; 7131 } 7132 ComponentName forwardingActivityComponentName = new ComponentName( 7133 mAndroidApplication.packageName, className); 7134 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7135 sourceUserId); 7136 if (!targetIsProfile) { 7137 forwardingActivityInfo.showUserIcon = targetUserId; 7138 forwardingResolveInfo.noResourceId = true; 7139 } 7140 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7141 forwardingResolveInfo.priority = 0; 7142 forwardingResolveInfo.preferredOrder = 0; 7143 forwardingResolveInfo.match = 0; 7144 forwardingResolveInfo.isDefault = true; 7145 forwardingResolveInfo.filter = filter; 7146 forwardingResolveInfo.targetUserId = targetUserId; 7147 return forwardingResolveInfo; 7148 } 7149 7150 @Override 7151 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7152 Intent[] specifics, String[] specificTypes, Intent intent, 7153 String resolvedType, int flags, int userId) { 7154 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7155 specificTypes, intent, resolvedType, flags, userId)); 7156 } 7157 7158 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7159 Intent[] specifics, String[] specificTypes, Intent intent, 7160 String resolvedType, int flags, int userId) { 7161 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7162 final int callingUid = Binder.getCallingUid(); 7163 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7164 false /*includeInstantApps*/); 7165 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7166 false /*requireFullPermission*/, false /*checkShell*/, 7167 "query intent activity options"); 7168 final String resultsAction = intent.getAction(); 7169 7170 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7171 | PackageManager.GET_RESOLVED_FILTER, userId); 7172 7173 if (DEBUG_INTENT_MATCHING) { 7174 Log.v(TAG, "Query " + intent + ": " + results); 7175 } 7176 7177 int specificsPos = 0; 7178 int N; 7179 7180 // todo: note that the algorithm used here is O(N^2). This 7181 // isn't a problem in our current environment, but if we start running 7182 // into situations where we have more than 5 or 10 matches then this 7183 // should probably be changed to something smarter... 7184 7185 // First we go through and resolve each of the specific items 7186 // that were supplied, taking care of removing any corresponding 7187 // duplicate items in the generic resolve list. 7188 if (specifics != null) { 7189 for (int i=0; i<specifics.length; i++) { 7190 final Intent sintent = specifics[i]; 7191 if (sintent == null) { 7192 continue; 7193 } 7194 7195 if (DEBUG_INTENT_MATCHING) { 7196 Log.v(TAG, "Specific #" + i + ": " + sintent); 7197 } 7198 7199 String action = sintent.getAction(); 7200 if (resultsAction != null && resultsAction.equals(action)) { 7201 // If this action was explicitly requested, then don't 7202 // remove things that have it. 7203 action = null; 7204 } 7205 7206 ResolveInfo ri = null; 7207 ActivityInfo ai = null; 7208 7209 ComponentName comp = sintent.getComponent(); 7210 if (comp == null) { 7211 ri = resolveIntent( 7212 sintent, 7213 specificTypes != null ? specificTypes[i] : null, 7214 flags, userId); 7215 if (ri == null) { 7216 continue; 7217 } 7218 if (ri == mResolveInfo) { 7219 // ACK! Must do something better with this. 7220 } 7221 ai = ri.activityInfo; 7222 comp = new ComponentName(ai.applicationInfo.packageName, 7223 ai.name); 7224 } else { 7225 ai = getActivityInfo(comp, flags, userId); 7226 if (ai == null) { 7227 continue; 7228 } 7229 } 7230 7231 // Look for any generic query activities that are duplicates 7232 // of this specific one, and remove them from the results. 7233 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7234 N = results.size(); 7235 int j; 7236 for (j=specificsPos; j<N; j++) { 7237 ResolveInfo sri = results.get(j); 7238 if ((sri.activityInfo.name.equals(comp.getClassName()) 7239 && sri.activityInfo.applicationInfo.packageName.equals( 7240 comp.getPackageName())) 7241 || (action != null && sri.filter.matchAction(action))) { 7242 results.remove(j); 7243 if (DEBUG_INTENT_MATCHING) Log.v( 7244 TAG, "Removing duplicate item from " + j 7245 + " due to specific " + specificsPos); 7246 if (ri == null) { 7247 ri = sri; 7248 } 7249 j--; 7250 N--; 7251 } 7252 } 7253 7254 // Add this specific item to its proper place. 7255 if (ri == null) { 7256 ri = new ResolveInfo(); 7257 ri.activityInfo = ai; 7258 } 7259 results.add(specificsPos, ri); 7260 ri.specificIndex = i; 7261 specificsPos++; 7262 } 7263 } 7264 7265 // Now we go through the remaining generic results and remove any 7266 // duplicate actions that are found here. 7267 N = results.size(); 7268 for (int i=specificsPos; i<N-1; i++) { 7269 final ResolveInfo rii = results.get(i); 7270 if (rii.filter == null) { 7271 continue; 7272 } 7273 7274 // Iterate over all of the actions of this result's intent 7275 // filter... typically this should be just one. 7276 final Iterator<String> it = rii.filter.actionsIterator(); 7277 if (it == null) { 7278 continue; 7279 } 7280 while (it.hasNext()) { 7281 final String action = it.next(); 7282 if (resultsAction != null && resultsAction.equals(action)) { 7283 // If this action was explicitly requested, then don't 7284 // remove things that have it. 7285 continue; 7286 } 7287 for (int j=i+1; j<N; j++) { 7288 final ResolveInfo rij = results.get(j); 7289 if (rij.filter != null && rij.filter.hasAction(action)) { 7290 results.remove(j); 7291 if (DEBUG_INTENT_MATCHING) Log.v( 7292 TAG, "Removing duplicate item from " + j 7293 + " due to action " + action + " at " + i); 7294 j--; 7295 N--; 7296 } 7297 } 7298 } 7299 7300 // If the caller didn't request filter information, drop it now 7301 // so we don't have to marshall/unmarshall it. 7302 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7303 rii.filter = null; 7304 } 7305 } 7306 7307 // Filter out the caller activity if so requested. 7308 if (caller != null) { 7309 N = results.size(); 7310 for (int i=0; i<N; i++) { 7311 ActivityInfo ainfo = results.get(i).activityInfo; 7312 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7313 && caller.getClassName().equals(ainfo.name)) { 7314 results.remove(i); 7315 break; 7316 } 7317 } 7318 } 7319 7320 // If the caller didn't request filter information, 7321 // drop them now so we don't have to 7322 // marshall/unmarshall it. 7323 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7324 N = results.size(); 7325 for (int i=0; i<N; i++) { 7326 results.get(i).filter = null; 7327 } 7328 } 7329 7330 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7331 return results; 7332 } 7333 7334 @Override 7335 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7336 String resolvedType, int flags, int userId) { 7337 return new ParceledListSlice<>( 7338 queryIntentReceiversInternal(intent, resolvedType, flags, userId, 7339 false /*allowDynamicSplits*/)); 7340 } 7341 7342 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7343 String resolvedType, int flags, int userId, boolean allowDynamicSplits) { 7344 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7345 final int callingUid = Binder.getCallingUid(); 7346 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7347 false /*requireFullPermission*/, false /*checkShell*/, 7348 "query intent receivers"); 7349 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7350 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7351 false /*includeInstantApps*/); 7352 ComponentName comp = intent.getComponent(); 7353 if (comp == null) { 7354 if (intent.getSelector() != null) { 7355 intent = intent.getSelector(); 7356 comp = intent.getComponent(); 7357 } 7358 } 7359 if (comp != null) { 7360 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7361 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7362 if (ai != null) { 7363 // When specifying an explicit component, we prevent the activity from being 7364 // used when either 1) the calling package is normal and the activity is within 7365 // an instant application or 2) the calling package is ephemeral and the 7366 // activity is not visible to instant applications. 7367 final boolean matchInstantApp = 7368 (flags & PackageManager.MATCH_INSTANT) != 0; 7369 final boolean matchVisibleToInstantAppOnly = 7370 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7371 final boolean matchExplicitlyVisibleOnly = 7372 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7373 final boolean isCallerInstantApp = 7374 instantAppPkgName != null; 7375 final boolean isTargetSameInstantApp = 7376 comp.getPackageName().equals(instantAppPkgName); 7377 final boolean isTargetInstantApp = 7378 (ai.applicationInfo.privateFlags 7379 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7380 final boolean isTargetVisibleToInstantApp = 7381 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7382 final boolean isTargetExplicitlyVisibleToInstantApp = 7383 isTargetVisibleToInstantApp 7384 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7385 final boolean isTargetHiddenFromInstantApp = 7386 !isTargetVisibleToInstantApp 7387 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7388 final boolean blockResolution = 7389 !isTargetSameInstantApp 7390 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7391 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7392 && isTargetHiddenFromInstantApp)); 7393 if (!blockResolution) { 7394 ResolveInfo ri = new ResolveInfo(); 7395 ri.activityInfo = ai; 7396 list.add(ri); 7397 } 7398 } 7399 return applyPostResolutionFilter( 7400 list, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7401 } 7402 7403 // reader 7404 synchronized (mPackages) { 7405 String pkgName = intent.getPackage(); 7406 if (pkgName == null) { 7407 final List<ResolveInfo> result = 7408 mReceivers.queryIntent(intent, resolvedType, flags, userId); 7409 return applyPostResolutionFilter( 7410 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7411 } 7412 final PackageParser.Package pkg = mPackages.get(pkgName); 7413 if (pkg != null) { 7414 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 7415 intent, resolvedType, flags, pkg.receivers, userId); 7416 return applyPostResolutionFilter( 7417 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7418 } 7419 return Collections.emptyList(); 7420 } 7421 } 7422 7423 @Override 7424 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7425 final int callingUid = Binder.getCallingUid(); 7426 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7427 } 7428 7429 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7430 int userId, int callingUid) { 7431 if (!sUserManager.exists(userId)) return null; 7432 flags = updateFlagsForResolve( 7433 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7434 List<ResolveInfo> query = queryIntentServicesInternal( 7435 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7436 if (query != null) { 7437 if (query.size() >= 1) { 7438 // If there is more than one service with the same priority, 7439 // just arbitrarily pick the first one. 7440 return query.get(0); 7441 } 7442 } 7443 return null; 7444 } 7445 7446 @Override 7447 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7448 String resolvedType, int flags, int userId) { 7449 final int callingUid = Binder.getCallingUid(); 7450 return new ParceledListSlice<>(queryIntentServicesInternal( 7451 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7452 } 7453 7454 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7455 String resolvedType, int flags, int userId, int callingUid, 7456 boolean includeInstantApps) { 7457 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7458 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7459 false /*requireFullPermission*/, false /*checkShell*/, 7460 "query intent receivers"); 7461 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7462 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7463 ComponentName comp = intent.getComponent(); 7464 if (comp == null) { 7465 if (intent.getSelector() != null) { 7466 intent = intent.getSelector(); 7467 comp = intent.getComponent(); 7468 } 7469 } 7470 if (comp != null) { 7471 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7472 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7473 if (si != null) { 7474 // When specifying an explicit component, we prevent the service from being 7475 // used when either 1) the service is in an instant application and the 7476 // caller is not the same instant application or 2) the calling package is 7477 // ephemeral and the activity is not visible to ephemeral applications. 7478 final boolean matchInstantApp = 7479 (flags & PackageManager.MATCH_INSTANT) != 0; 7480 final boolean matchVisibleToInstantAppOnly = 7481 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7482 final boolean isCallerInstantApp = 7483 instantAppPkgName != null; 7484 final boolean isTargetSameInstantApp = 7485 comp.getPackageName().equals(instantAppPkgName); 7486 final boolean isTargetInstantApp = 7487 (si.applicationInfo.privateFlags 7488 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7489 final boolean isTargetHiddenFromInstantApp = 7490 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7491 final boolean blockResolution = 7492 !isTargetSameInstantApp 7493 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7494 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7495 && isTargetHiddenFromInstantApp)); 7496 if (!blockResolution) { 7497 final ResolveInfo ri = new ResolveInfo(); 7498 ri.serviceInfo = si; 7499 list.add(ri); 7500 } 7501 } 7502 return list; 7503 } 7504 7505 // reader 7506 synchronized (mPackages) { 7507 String pkgName = intent.getPackage(); 7508 if (pkgName == null) { 7509 return applyPostServiceResolutionFilter( 7510 mServices.queryIntent(intent, resolvedType, flags, userId), 7511 instantAppPkgName); 7512 } 7513 final PackageParser.Package pkg = mPackages.get(pkgName); 7514 if (pkg != null) { 7515 return applyPostServiceResolutionFilter( 7516 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7517 userId), 7518 instantAppPkgName); 7519 } 7520 return Collections.emptyList(); 7521 } 7522 } 7523 7524 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7525 String instantAppPkgName) { 7526 if (instantAppPkgName == null) { 7527 return resolveInfos; 7528 } 7529 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7530 final ResolveInfo info = resolveInfos.get(i); 7531 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7532 // allow services that are defined in the provided package 7533 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7534 if (info.serviceInfo.splitName != null 7535 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7536 info.serviceInfo.splitName)) { 7537 // requested service is defined in a split that hasn't been installed yet. 7538 // add the installer to the resolve list 7539 if (DEBUG_EPHEMERAL) { 7540 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7541 } 7542 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7543 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7544 info.serviceInfo.packageName, info.serviceInfo.splitName, 7545 null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode, 7546 null /*failureIntent*/); 7547 // make sure this resolver is the default 7548 installerInfo.isDefault = true; 7549 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7550 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7551 // add a non-generic filter 7552 installerInfo.filter = new IntentFilter(); 7553 // load resources from the correct package 7554 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7555 resolveInfos.set(i, installerInfo); 7556 } 7557 continue; 7558 } 7559 // allow services that have been explicitly exposed to ephemeral apps 7560 if (!isEphemeralApp 7561 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7562 continue; 7563 } 7564 resolveInfos.remove(i); 7565 } 7566 return resolveInfos; 7567 } 7568 7569 @Override 7570 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7571 String resolvedType, int flags, int userId) { 7572 return new ParceledListSlice<>( 7573 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7574 } 7575 7576 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7577 Intent intent, String resolvedType, int flags, int userId) { 7578 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7579 final int callingUid = Binder.getCallingUid(); 7580 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7581 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7582 false /*includeInstantApps*/); 7583 ComponentName comp = intent.getComponent(); 7584 if (comp == null) { 7585 if (intent.getSelector() != null) { 7586 intent = intent.getSelector(); 7587 comp = intent.getComponent(); 7588 } 7589 } 7590 if (comp != null) { 7591 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7592 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7593 if (pi != null) { 7594 // When specifying an explicit component, we prevent the provider from being 7595 // used when either 1) the provider is in an instant application and the 7596 // caller is not the same instant application or 2) the calling package is an 7597 // instant application and the provider is not visible to instant applications. 7598 final boolean matchInstantApp = 7599 (flags & PackageManager.MATCH_INSTANT) != 0; 7600 final boolean matchVisibleToInstantAppOnly = 7601 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7602 final boolean isCallerInstantApp = 7603 instantAppPkgName != null; 7604 final boolean isTargetSameInstantApp = 7605 comp.getPackageName().equals(instantAppPkgName); 7606 final boolean isTargetInstantApp = 7607 (pi.applicationInfo.privateFlags 7608 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7609 final boolean isTargetHiddenFromInstantApp = 7610 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7611 final boolean blockResolution = 7612 !isTargetSameInstantApp 7613 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7614 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7615 && isTargetHiddenFromInstantApp)); 7616 if (!blockResolution) { 7617 final ResolveInfo ri = new ResolveInfo(); 7618 ri.providerInfo = pi; 7619 list.add(ri); 7620 } 7621 } 7622 return list; 7623 } 7624 7625 // reader 7626 synchronized (mPackages) { 7627 String pkgName = intent.getPackage(); 7628 if (pkgName == null) { 7629 return applyPostContentProviderResolutionFilter( 7630 mProviders.queryIntent(intent, resolvedType, flags, userId), 7631 instantAppPkgName); 7632 } 7633 final PackageParser.Package pkg = mPackages.get(pkgName); 7634 if (pkg != null) { 7635 return applyPostContentProviderResolutionFilter( 7636 mProviders.queryIntentForPackage( 7637 intent, resolvedType, flags, pkg.providers, userId), 7638 instantAppPkgName); 7639 } 7640 return Collections.emptyList(); 7641 } 7642 } 7643 7644 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7645 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7646 if (instantAppPkgName == null) { 7647 return resolveInfos; 7648 } 7649 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7650 final ResolveInfo info = resolveInfos.get(i); 7651 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7652 // allow providers that are defined in the provided package 7653 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7654 if (info.providerInfo.splitName != null 7655 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7656 info.providerInfo.splitName)) { 7657 // requested provider is defined in a split that hasn't been installed yet. 7658 // add the installer to the resolve list 7659 if (DEBUG_EPHEMERAL) { 7660 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7661 } 7662 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7663 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7664 info.providerInfo.packageName, info.providerInfo.splitName, 7665 null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode, 7666 null /*failureIntent*/); 7667 // make sure this resolver is the default 7668 installerInfo.isDefault = true; 7669 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7670 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7671 // add a non-generic filter 7672 installerInfo.filter = new IntentFilter(); 7673 // load resources from the correct package 7674 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7675 resolveInfos.set(i, installerInfo); 7676 } 7677 continue; 7678 } 7679 // allow providers that have been explicitly exposed to instant applications 7680 if (!isEphemeralApp 7681 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7682 continue; 7683 } 7684 resolveInfos.remove(i); 7685 } 7686 return resolveInfos; 7687 } 7688 7689 @Override 7690 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7691 final int callingUid = Binder.getCallingUid(); 7692 if (getInstantAppPackageName(callingUid) != null) { 7693 return ParceledListSlice.emptyList(); 7694 } 7695 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7696 flags = updateFlagsForPackage(flags, userId, null); 7697 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7698 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7699 true /* requireFullPermission */, false /* checkShell */, 7700 "get installed packages"); 7701 7702 // writer 7703 synchronized (mPackages) { 7704 ArrayList<PackageInfo> list; 7705 if (listUninstalled) { 7706 list = new ArrayList<>(mSettings.mPackages.size()); 7707 for (PackageSetting ps : mSettings.mPackages.values()) { 7708 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7709 continue; 7710 } 7711 if (filterAppAccessLPr(ps, callingUid, userId)) { 7712 continue; 7713 } 7714 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7715 if (pi != null) { 7716 list.add(pi); 7717 } 7718 } 7719 } else { 7720 list = new ArrayList<>(mPackages.size()); 7721 for (PackageParser.Package p : mPackages.values()) { 7722 final PackageSetting ps = (PackageSetting) p.mExtras; 7723 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7724 continue; 7725 } 7726 if (filterAppAccessLPr(ps, callingUid, userId)) { 7727 continue; 7728 } 7729 final PackageInfo pi = generatePackageInfo((PackageSetting) 7730 p.mExtras, flags, userId); 7731 if (pi != null) { 7732 list.add(pi); 7733 } 7734 } 7735 } 7736 7737 return new ParceledListSlice<>(list); 7738 } 7739 } 7740 7741 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7742 String[] permissions, boolean[] tmp, int flags, int userId) { 7743 int numMatch = 0; 7744 final PermissionsState permissionsState = ps.getPermissionsState(); 7745 for (int i=0; i<permissions.length; i++) { 7746 final String permission = permissions[i]; 7747 if (permissionsState.hasPermission(permission, userId)) { 7748 tmp[i] = true; 7749 numMatch++; 7750 } else { 7751 tmp[i] = false; 7752 } 7753 } 7754 if (numMatch == 0) { 7755 return; 7756 } 7757 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7758 7759 // The above might return null in cases of uninstalled apps or install-state 7760 // skew across users/profiles. 7761 if (pi != null) { 7762 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7763 if (numMatch == permissions.length) { 7764 pi.requestedPermissions = permissions; 7765 } else { 7766 pi.requestedPermissions = new String[numMatch]; 7767 numMatch = 0; 7768 for (int i=0; i<permissions.length; i++) { 7769 if (tmp[i]) { 7770 pi.requestedPermissions[numMatch] = permissions[i]; 7771 numMatch++; 7772 } 7773 } 7774 } 7775 } 7776 list.add(pi); 7777 } 7778 } 7779 7780 @Override 7781 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7782 String[] permissions, int flags, int userId) { 7783 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7784 flags = updateFlagsForPackage(flags, userId, permissions); 7785 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7786 true /* requireFullPermission */, false /* checkShell */, 7787 "get packages holding permissions"); 7788 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7789 7790 // writer 7791 synchronized (mPackages) { 7792 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7793 boolean[] tmpBools = new boolean[permissions.length]; 7794 if (listUninstalled) { 7795 for (PackageSetting ps : mSettings.mPackages.values()) { 7796 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7797 userId); 7798 } 7799 } else { 7800 for (PackageParser.Package pkg : mPackages.values()) { 7801 PackageSetting ps = (PackageSetting)pkg.mExtras; 7802 if (ps != null) { 7803 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7804 userId); 7805 } 7806 } 7807 } 7808 7809 return new ParceledListSlice<PackageInfo>(list); 7810 } 7811 } 7812 7813 @Override 7814 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7815 final int callingUid = Binder.getCallingUid(); 7816 if (getInstantAppPackageName(callingUid) != null) { 7817 return ParceledListSlice.emptyList(); 7818 } 7819 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7820 flags = updateFlagsForApplication(flags, userId, null); 7821 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7822 7823 // writer 7824 synchronized (mPackages) { 7825 ArrayList<ApplicationInfo> list; 7826 if (listUninstalled) { 7827 list = new ArrayList<>(mSettings.mPackages.size()); 7828 for (PackageSetting ps : mSettings.mPackages.values()) { 7829 ApplicationInfo ai; 7830 int effectiveFlags = flags; 7831 if (ps.isSystem()) { 7832 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7833 } 7834 if (ps.pkg != null) { 7835 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7836 continue; 7837 } 7838 if (filterAppAccessLPr(ps, callingUid, userId)) { 7839 continue; 7840 } 7841 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7842 ps.readUserState(userId), userId); 7843 if (ai != null) { 7844 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7845 } 7846 } else { 7847 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7848 // and already converts to externally visible package name 7849 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7850 callingUid, effectiveFlags, userId); 7851 } 7852 if (ai != null) { 7853 list.add(ai); 7854 } 7855 } 7856 } else { 7857 list = new ArrayList<>(mPackages.size()); 7858 for (PackageParser.Package p : mPackages.values()) { 7859 if (p.mExtras != null) { 7860 PackageSetting ps = (PackageSetting) p.mExtras; 7861 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 7862 continue; 7863 } 7864 if (filterAppAccessLPr(ps, callingUid, userId)) { 7865 continue; 7866 } 7867 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7868 ps.readUserState(userId), userId); 7869 if (ai != null) { 7870 ai.packageName = resolveExternalPackageNameLPr(p); 7871 list.add(ai); 7872 } 7873 } 7874 } 7875 } 7876 7877 return new ParceledListSlice<>(list); 7878 } 7879 } 7880 7881 @Override 7882 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7883 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7884 return null; 7885 } 7886 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 7887 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7888 "getEphemeralApplications"); 7889 } 7890 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7891 true /* requireFullPermission */, false /* checkShell */, 7892 "getEphemeralApplications"); 7893 synchronized (mPackages) { 7894 List<InstantAppInfo> instantApps = mInstantAppRegistry 7895 .getInstantAppsLPr(userId); 7896 if (instantApps != null) { 7897 return new ParceledListSlice<>(instantApps); 7898 } 7899 } 7900 return null; 7901 } 7902 7903 @Override 7904 public boolean isInstantApp(String packageName, int userId) { 7905 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7906 true /* requireFullPermission */, false /* checkShell */, 7907 "isInstantApp"); 7908 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7909 return false; 7910 } 7911 7912 synchronized (mPackages) { 7913 int callingUid = Binder.getCallingUid(); 7914 if (Process.isIsolated(callingUid)) { 7915 callingUid = mIsolatedOwners.get(callingUid); 7916 } 7917 final PackageSetting ps = mSettings.mPackages.get(packageName); 7918 PackageParser.Package pkg = mPackages.get(packageName); 7919 final boolean returnAllowed = 7920 ps != null 7921 && (isCallerSameApp(packageName, callingUid) 7922 || canViewInstantApps(callingUid, userId) 7923 || mInstantAppRegistry.isInstantAccessGranted( 7924 userId, UserHandle.getAppId(callingUid), ps.appId)); 7925 if (returnAllowed) { 7926 return ps.getInstantApp(userId); 7927 } 7928 } 7929 return false; 7930 } 7931 7932 @Override 7933 public byte[] getInstantAppCookie(String packageName, int userId) { 7934 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7935 return null; 7936 } 7937 7938 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7939 true /* requireFullPermission */, false /* checkShell */, 7940 "getInstantAppCookie"); 7941 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7942 return null; 7943 } 7944 synchronized (mPackages) { 7945 return mInstantAppRegistry.getInstantAppCookieLPw( 7946 packageName, userId); 7947 } 7948 } 7949 7950 @Override 7951 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7952 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7953 return true; 7954 } 7955 7956 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7957 true /* requireFullPermission */, true /* checkShell */, 7958 "setInstantAppCookie"); 7959 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7960 return false; 7961 } 7962 synchronized (mPackages) { 7963 return mInstantAppRegistry.setInstantAppCookieLPw( 7964 packageName, cookie, userId); 7965 } 7966 } 7967 7968 @Override 7969 public Bitmap getInstantAppIcon(String packageName, int userId) { 7970 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7971 return null; 7972 } 7973 7974 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 7975 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7976 "getInstantAppIcon"); 7977 } 7978 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7979 true /* requireFullPermission */, false /* checkShell */, 7980 "getInstantAppIcon"); 7981 7982 synchronized (mPackages) { 7983 return mInstantAppRegistry.getInstantAppIconLPw( 7984 packageName, userId); 7985 } 7986 } 7987 7988 private boolean isCallerSameApp(String packageName, int uid) { 7989 PackageParser.Package pkg = mPackages.get(packageName); 7990 return pkg != null 7991 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 7992 } 7993 7994 @Override 7995 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7996 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 7997 return ParceledListSlice.emptyList(); 7998 } 7999 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 8000 } 8001 8002 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 8003 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 8004 8005 // reader 8006 synchronized (mPackages) { 8007 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 8008 final int userId = UserHandle.getCallingUserId(); 8009 while (i.hasNext()) { 8010 final PackageParser.Package p = i.next(); 8011 if (p.applicationInfo == null) continue; 8012 8013 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 8014 && !p.applicationInfo.isDirectBootAware(); 8015 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 8016 && p.applicationInfo.isDirectBootAware(); 8017 8018 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 8019 && (!mSafeMode || isSystemApp(p)) 8020 && (matchesUnaware || matchesAware)) { 8021 PackageSetting ps = mSettings.mPackages.get(p.packageName); 8022 if (ps != null) { 8023 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8024 ps.readUserState(userId), userId); 8025 if (ai != null) { 8026 finalList.add(ai); 8027 } 8028 } 8029 } 8030 } 8031 } 8032 8033 return finalList; 8034 } 8035 8036 @Override 8037 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 8038 return resolveContentProviderInternal(name, flags, userId); 8039 } 8040 8041 private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) { 8042 if (!sUserManager.exists(userId)) return null; 8043 flags = updateFlagsForComponent(flags, userId, name); 8044 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 8045 // reader 8046 synchronized (mPackages) { 8047 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 8048 PackageSetting ps = provider != null 8049 ? mSettings.mPackages.get(provider.owner.packageName) 8050 : null; 8051 if (ps != null) { 8052 final boolean isInstantApp = ps.getInstantApp(userId); 8053 // normal application; filter out instant application provider 8054 if (instantAppPkgName == null && isInstantApp) { 8055 return null; 8056 } 8057 // instant application; filter out other instant applications 8058 if (instantAppPkgName != null 8059 && isInstantApp 8060 && !provider.owner.packageName.equals(instantAppPkgName)) { 8061 return null; 8062 } 8063 // instant application; filter out non-exposed provider 8064 if (instantAppPkgName != null 8065 && !isInstantApp 8066 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 8067 return null; 8068 } 8069 // provider not enabled 8070 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 8071 return null; 8072 } 8073 return PackageParser.generateProviderInfo( 8074 provider, flags, ps.readUserState(userId), userId); 8075 } 8076 return null; 8077 } 8078 } 8079 8080 /** 8081 * @deprecated 8082 */ 8083 @Deprecated 8084 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 8085 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8086 return; 8087 } 8088 // reader 8089 synchronized (mPackages) { 8090 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 8091 .entrySet().iterator(); 8092 final int userId = UserHandle.getCallingUserId(); 8093 while (i.hasNext()) { 8094 Map.Entry<String, PackageParser.Provider> entry = i.next(); 8095 PackageParser.Provider p = entry.getValue(); 8096 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8097 8098 if (ps != null && p.syncable 8099 && (!mSafeMode || (p.info.applicationInfo.flags 8100 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 8101 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 8102 ps.readUserState(userId), userId); 8103 if (info != null) { 8104 outNames.add(entry.getKey()); 8105 outInfo.add(info); 8106 } 8107 } 8108 } 8109 } 8110 } 8111 8112 @Override 8113 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8114 int uid, int flags, String metaDataKey) { 8115 final int callingUid = Binder.getCallingUid(); 8116 final int userId = processName != null ? UserHandle.getUserId(uid) 8117 : UserHandle.getCallingUserId(); 8118 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8119 flags = updateFlagsForComponent(flags, userId, processName); 8120 ArrayList<ProviderInfo> finalList = null; 8121 // reader 8122 synchronized (mPackages) { 8123 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 8124 while (i.hasNext()) { 8125 final PackageParser.Provider p = i.next(); 8126 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8127 if (ps != null && p.info.authority != null 8128 && (processName == null 8129 || (p.info.processName.equals(processName) 8130 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 8131 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 8132 8133 // See PM.queryContentProviders()'s javadoc for why we have the metaData 8134 // parameter. 8135 if (metaDataKey != null 8136 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 8137 continue; 8138 } 8139 final ComponentName component = 8140 new ComponentName(p.info.packageName, p.info.name); 8141 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8142 continue; 8143 } 8144 if (finalList == null) { 8145 finalList = new ArrayList<ProviderInfo>(3); 8146 } 8147 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8148 ps.readUserState(userId), userId); 8149 if (info != null) { 8150 finalList.add(info); 8151 } 8152 } 8153 } 8154 } 8155 8156 if (finalList != null) { 8157 Collections.sort(finalList, mProviderInitOrderSorter); 8158 return new ParceledListSlice<ProviderInfo>(finalList); 8159 } 8160 8161 return ParceledListSlice.emptyList(); 8162 } 8163 8164 @Override 8165 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8166 // reader 8167 synchronized (mPackages) { 8168 final int callingUid = Binder.getCallingUid(); 8169 final int callingUserId = UserHandle.getUserId(callingUid); 8170 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8171 if (ps == null) return null; 8172 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8173 return null; 8174 } 8175 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8176 return PackageParser.generateInstrumentationInfo(i, flags); 8177 } 8178 } 8179 8180 @Override 8181 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8182 String targetPackage, int flags) { 8183 final int callingUid = Binder.getCallingUid(); 8184 final int callingUserId = UserHandle.getUserId(callingUid); 8185 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8186 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8187 return ParceledListSlice.emptyList(); 8188 } 8189 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8190 } 8191 8192 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8193 int flags) { 8194 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 8195 8196 // reader 8197 synchronized (mPackages) { 8198 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8199 while (i.hasNext()) { 8200 final PackageParser.Instrumentation p = i.next(); 8201 if (targetPackage == null 8202 || targetPackage.equals(p.info.targetPackage)) { 8203 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8204 flags); 8205 if (ii != null) { 8206 finalList.add(ii); 8207 } 8208 } 8209 } 8210 } 8211 8212 return finalList; 8213 } 8214 8215 private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) { 8216 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]"); 8217 try { 8218 scanDirLI(scanDir, parseFlags, scanFlags, currentTime); 8219 } finally { 8220 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8221 } 8222 } 8223 8224 private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) { 8225 final File[] files = scanDir.listFiles(); 8226 if (ArrayUtils.isEmpty(files)) { 8227 Log.d(TAG, "No files in app dir " + scanDir); 8228 return; 8229 } 8230 8231 if (DEBUG_PACKAGE_SCANNING) { 8232 Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags 8233 + " flags=0x" + Integer.toHexString(parseFlags)); 8234 } 8235 try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8236 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8237 mParallelPackageParserCallback)) { 8238 // Submit files for parsing in parallel 8239 int fileCount = 0; 8240 for (File file : files) { 8241 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8242 && !PackageInstallerService.isStageName(file.getName()); 8243 if (!isPackage) { 8244 // Ignore entries which are not packages 8245 continue; 8246 } 8247 parallelPackageParser.submit(file, parseFlags); 8248 fileCount++; 8249 } 8250 8251 // Process results one by one 8252 for (; fileCount > 0; fileCount--) { 8253 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8254 Throwable throwable = parseResult.throwable; 8255 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8256 8257 if (throwable == null) { 8258 // TODO(toddke): move lower in the scan chain 8259 // Static shared libraries have synthetic package names 8260 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8261 renameStaticSharedLibraryPackage(parseResult.pkg); 8262 } 8263 try { 8264 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8265 scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags, 8266 currentTime, null); 8267 } 8268 } catch (PackageManagerException e) { 8269 errorCode = e.error; 8270 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8271 } 8272 } else if (throwable instanceof PackageParser.PackageParserException) { 8273 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8274 throwable; 8275 errorCode = e.error; 8276 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8277 } else { 8278 throw new IllegalStateException("Unexpected exception occurred while parsing " 8279 + parseResult.scanFile, throwable); 8280 } 8281 8282 // Delete invalid userdata apps 8283 if ((scanFlags & SCAN_AS_SYSTEM) == 0 && 8284 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8285 logCriticalInfo(Log.WARN, 8286 "Deleting invalid package at " + parseResult.scanFile); 8287 removeCodePathLI(parseResult.scanFile); 8288 } 8289 } 8290 } 8291 } 8292 8293 public static void reportSettingsProblem(int priority, String msg) { 8294 logCriticalInfo(priority, msg); 8295 } 8296 8297 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, 8298 final @ParseFlags int parseFlags, boolean forceCollect) throws PackageManagerException { 8299 // When upgrading from pre-N MR1, verify the package time stamp using the package 8300 // directory and not the APK file. 8301 final long lastModifiedTime = mIsPreNMR1Upgrade 8302 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg); 8303 if (ps != null && !forceCollect 8304 && ps.codePathString.equals(pkg.codePath) 8305 && ps.timeStamp == lastModifiedTime 8306 && !isCompatSignatureUpdateNeeded(pkg) 8307 && !isRecoverSignatureUpdateNeeded(pkg)) { 8308 if (ps.signatures.mSigningDetails.signatures != null 8309 && ps.signatures.mSigningDetails.signatures.length != 0 8310 && ps.signatures.mSigningDetails.signatureSchemeVersion 8311 != SignatureSchemeVersion.UNKNOWN) { 8312 // Optimization: reuse the existing cached signing data 8313 // if the package appears to be unchanged. 8314 pkg.mSigningDetails = 8315 new PackageParser.SigningDetails(ps.signatures.mSigningDetails); 8316 return; 8317 } 8318 8319 Slog.w(TAG, "PackageSetting for " + ps.name 8320 + " is missing signatures. Collecting certs again to recover them."); 8321 } else { 8322 Slog.i(TAG, pkg.codePath + " changed; collecting certs" + 8323 (forceCollect ? " (forced)" : "")); 8324 } 8325 8326 try { 8327 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8328 PackageParser.collectCertificates(pkg, parseFlags); 8329 } catch (PackageParserException e) { 8330 throw PackageManagerException.from(e); 8331 } finally { 8332 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8333 } 8334 } 8335 8336 /** 8337 * Traces a package scan. 8338 * @see #scanPackageLI(File, int, int, long, UserHandle) 8339 */ 8340 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8341 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8342 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8343 try { 8344 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8345 } finally { 8346 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8347 } 8348 } 8349 8350 /** 8351 * Scans a package and returns the newly parsed package. 8352 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8353 */ 8354 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8355 long currentTime, UserHandle user) throws PackageManagerException { 8356 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8357 PackageParser pp = new PackageParser(); 8358 pp.setSeparateProcesses(mSeparateProcesses); 8359 pp.setOnlyCoreApps(mOnlyCore); 8360 pp.setDisplayMetrics(mMetrics); 8361 pp.setCallback(mPackageParserCallback); 8362 8363 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8364 final PackageParser.Package pkg; 8365 try { 8366 pkg = pp.parsePackage(scanFile, parseFlags); 8367 } catch (PackageParserException e) { 8368 throw PackageManagerException.from(e); 8369 } finally { 8370 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8371 } 8372 8373 // Static shared libraries have synthetic package names 8374 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8375 renameStaticSharedLibraryPackage(pkg); 8376 } 8377 8378 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8379 } 8380 8381 /** 8382 * Scans a package and returns the newly parsed package. 8383 * @throws PackageManagerException on a parse error. 8384 */ 8385 private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg, 8386 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8387 @Nullable UserHandle user) 8388 throws PackageManagerException { 8389 // If the package has children and this is the first dive in the function 8390 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8391 // packages (parent and children) would be successfully scanned before the 8392 // actual scan since scanning mutates internal state and we want to atomically 8393 // install the package and its children. 8394 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8395 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8396 scanFlags |= SCAN_CHECK_ONLY; 8397 } 8398 } else { 8399 scanFlags &= ~SCAN_CHECK_ONLY; 8400 } 8401 8402 // Scan the parent 8403 PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags, 8404 scanFlags, currentTime, user); 8405 8406 // Scan the children 8407 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8408 for (int i = 0; i < childCount; i++) { 8409 PackageParser.Package childPackage = pkg.childPackages.get(i); 8410 addForInitLI(childPackage, parseFlags, scanFlags, 8411 currentTime, user); 8412 } 8413 8414 8415 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8416 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8417 } 8418 8419 return scannedPkg; 8420 } 8421 8422 // Temporary to catch potential issues with refactoring 8423 private static boolean REFACTOR_DEBUG = true; 8424 /** 8425 * Adds a new package to the internal data structures during platform initialization. 8426 * <p>After adding, the package is known to the system and available for querying. 8427 * <p>For packages located on the device ROM [eg. packages located in /system, /vendor, 8428 * etc...], additional checks are performed. Basic verification [such as ensuring 8429 * matching signatures, checking version codes, etc...] occurs if the package is 8430 * identical to a previously known package. If the package fails a signature check, 8431 * the version installed on /data will be removed. If the version of the new package 8432 * is less than or equal than the version on /data, it will be ignored. 8433 * <p>Regardless of the package location, the results are applied to the internal 8434 * structures and the package is made available to the rest of the system. 8435 * <p>NOTE: The return value should be removed. It's the passed in package object. 8436 */ 8437 private PackageParser.Package addForInitLI(PackageParser.Package pkg, 8438 @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8439 @Nullable UserHandle user) 8440 throws PackageManagerException { 8441 final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0; 8442 final String renamedPkgName; 8443 final PackageSetting disabledPkgSetting; 8444 final boolean isSystemPkgUpdated; 8445 final boolean pkgAlreadyExists; 8446 PackageSetting pkgSetting; 8447 8448 // NOTE: installPackageLI() has the same code to setup the package's 8449 // application info. This probably should be done lower in the call 8450 // stack [such as scanPackageOnly()]. However, we verify the application 8451 // info prior to that [in scanPackageNew()] and thus have to setup 8452 // the application info early. 8453 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8454 pkg.setApplicationInfoCodePath(pkg.codePath); 8455 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8456 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8457 pkg.setApplicationInfoResourcePath(pkg.codePath); 8458 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 8459 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8460 8461 synchronized (mPackages) { 8462 renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8463 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 8464if (REFACTOR_DEBUG) { 8465Slog.e("TODD", 8466 "Add pkg: " + pkg.packageName + (realPkgName==null?"":", realName: " + realPkgName)); 8467} 8468 if (realPkgName != null) { 8469 ensurePackageRenamed(pkg, renamedPkgName); 8470 } 8471 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 8472 final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName); 8473 pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting; 8474 pkgAlreadyExists = pkgSetting != null; 8475 final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName; 8476 disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName); 8477 isSystemPkgUpdated = disabledPkgSetting != null; 8478 8479 if (DEBUG_INSTALL && isSystemPkgUpdated) { 8480 Slog.d(TAG, "updatedPkg = " + disabledPkgSetting); 8481 } 8482if (REFACTOR_DEBUG) { 8483Slog.e("TODD", 8484 "SSP? " + scanSystemPartition 8485 + ", exists? " + pkgAlreadyExists + (pkgAlreadyExists?" "+pkgSetting.toString():"") 8486 + ", upgraded? " + isSystemPkgUpdated + (isSystemPkgUpdated?" "+disabledPkgSetting.toString():"")); 8487} 8488 8489 final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null) 8490 ? mSettings.getSharedUserLPw(pkg.mSharedUserId, 8491 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true) 8492 : null; 8493 if (DEBUG_PACKAGE_SCANNING 8494 && (parseFlags & PackageParser.PARSE_CHATTY) != 0 8495 && sharedUserSetting != null) { 8496 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 8497 + " (uid=" + sharedUserSetting.userId + "):" 8498 + " packages=" + sharedUserSetting.packages); 8499if (REFACTOR_DEBUG) { 8500Slog.e("TODD", 8501 "Shared UserID " + pkg.mSharedUserId 8502 + " (uid=" + sharedUserSetting.userId + "):" 8503 + " packages=" + sharedUserSetting.packages); 8504} 8505 } 8506 8507 if (scanSystemPartition) { 8508 // Potentially prune child packages. If the application on the /system 8509 // partition has been updated via OTA, but, is still disabled by a 8510 // version on /data, cycle through all of its children packages and 8511 // remove children that are no longer defined. 8512 if (isSystemPkgUpdated) { 8513if (REFACTOR_DEBUG) { 8514Slog.e("TODD", 8515 "Disable child packages"); 8516} 8517 final int scannedChildCount = (pkg.childPackages != null) 8518 ? pkg.childPackages.size() : 0; 8519 final int disabledChildCount = disabledPkgSetting.childPackageNames != null 8520 ? disabledPkgSetting.childPackageNames.size() : 0; 8521 for (int i = 0; i < disabledChildCount; i++) { 8522 String disabledChildPackageName = 8523 disabledPkgSetting.childPackageNames.get(i); 8524 boolean disabledPackageAvailable = false; 8525 for (int j = 0; j < scannedChildCount; j++) { 8526 PackageParser.Package childPkg = pkg.childPackages.get(j); 8527 if (childPkg.packageName.equals(disabledChildPackageName)) { 8528if (REFACTOR_DEBUG) { 8529Slog.e("TODD", 8530 "Ignore " + disabledChildPackageName); 8531} 8532 disabledPackageAvailable = true; 8533 break; 8534 } 8535 } 8536 if (!disabledPackageAvailable) { 8537if (REFACTOR_DEBUG) { 8538Slog.e("TODD", 8539 "Disable " + disabledChildPackageName); 8540} 8541 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8542 } 8543 } 8544 // we're updating the disabled package, so, scan it as the package setting 8545 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, 8546 disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */, 8547 null /* originalPkgSetting */, null, parseFlags, scanFlags, 8548 (pkg == mPlatformPackage), user); 8549if (REFACTOR_DEBUG) { 8550Slog.e("TODD", 8551 "Scan disabled system package"); 8552Slog.e("TODD", 8553 "Pre: " + request.pkgSetting.dumpState_temp()); 8554} 8555final ScanResult result = 8556 scanPackageOnlyLI(request, mFactoryTest, -1L); 8557if (REFACTOR_DEBUG) { 8558Slog.e("TODD", 8559 "Post: " + (result.success?result.pkgSetting.dumpState_temp():"FAILED scan")); 8560} 8561 } 8562 } 8563 } 8564 8565 final boolean newPkgChangedPaths = 8566 pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath); 8567if (REFACTOR_DEBUG) { 8568Slog.e("TODD", 8569 "paths changed? " + newPkgChangedPaths 8570 + "; old: " + pkg.codePath 8571 + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.codePathString)); 8572} 8573 final boolean newPkgVersionGreater = 8574 pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode; 8575if (REFACTOR_DEBUG) { 8576Slog.e("TODD", 8577 "version greater? " + newPkgVersionGreater 8578 + "; old: " + pkg.getLongVersionCode() 8579 + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.versionCode)); 8580} 8581 final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated 8582 && newPkgChangedPaths && newPkgVersionGreater; 8583if (REFACTOR_DEBUG) { 8584 Slog.e("TODD", 8585 "system better? " + isSystemPkgBetter); 8586} 8587 if (isSystemPkgBetter) { 8588 // The version of the application on /system is greater than the version on 8589 // /data. Switch back to the application on /system. 8590 // It's safe to assume the application on /system will correctly scan. If not, 8591 // there won't be a working copy of the application. 8592 synchronized (mPackages) { 8593 // just remove the loaded entries from package lists 8594 mPackages.remove(pkgSetting.name); 8595 } 8596 8597 logCriticalInfo(Log.WARN, 8598 "System package updated;" 8599 + " name: " + pkgSetting.name 8600 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8601 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8602if (REFACTOR_DEBUG) { 8603Slog.e("TODD", 8604 "System package changed;" 8605 + " name: " + pkgSetting.name 8606 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8607 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8608} 8609 8610 final InstallArgs args = createInstallArgsForExisting( 8611 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8612 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8613 args.cleanUpResourcesLI(); 8614 synchronized (mPackages) { 8615 mSettings.enableSystemPackageLPw(pkgSetting.name); 8616 } 8617 } 8618 8619 if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) { 8620if (REFACTOR_DEBUG) { 8621Slog.e("TODD", 8622 "THROW exception; system pkg version not good enough"); 8623} 8624 // The version of the application on the /system partition is less than or 8625 // equal to the version on the /data partition. Throw an exception and use 8626 // the application already installed on the /data partition. 8627 throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at " 8628 + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode 8629 + " better than this " + pkg.getLongVersionCode()); 8630 } 8631 8632 // Verify certificates against what was last scanned. If it is an updated priv app, we will 8633 // force the verification. Full apk verification will happen unless apk verity is set up for 8634 // the file. In that case, only small part of the apk is verified upfront. 8635 collectCertificatesLI(pkgSetting, pkg, parseFlags, 8636 PackageManagerServiceUtils.isApkVerificationForced(disabledPkgSetting)); 8637 8638 boolean shouldHideSystemApp = false; 8639 // A new application appeared on /system, but, we already have a copy of 8640 // the application installed on /data. 8641 if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists 8642 && !pkgSetting.isSystem()) { 8643 // if the signatures don't match, wipe the installed application and its data 8644 if (compareSignatures(pkgSetting.signatures.mSigningDetails.signatures, 8645 pkg.mSigningDetails.signatures) 8646 != PackageManager.SIGNATURE_MATCH) { 8647 logCriticalInfo(Log.WARN, 8648 "System package signature mismatch;" 8649 + " name: " + pkgSetting.name); 8650if (REFACTOR_DEBUG) { 8651Slog.e("TODD", 8652 "System package signature mismatch;" 8653 + " name: " + pkgSetting.name); 8654} 8655 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8656 "scanPackageInternalLI")) { 8657 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8658 } 8659 pkgSetting = null; 8660 } else if (newPkgVersionGreater) { 8661 // The application on /system is newer than the application on /data. 8662 // Simply remove the application on /data [keeping application data] 8663 // and replace it with the version on /system. 8664 logCriticalInfo(Log.WARN, 8665 "System package enabled;" 8666 + " name: " + pkgSetting.name 8667 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8668 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8669if (REFACTOR_DEBUG) { 8670Slog.e("TODD", 8671 "System package enabled;" 8672 + " name: " + pkgSetting.name 8673 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8674 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8675} 8676 InstallArgs args = createInstallArgsForExisting( 8677 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8678 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8679 synchronized (mInstallLock) { 8680 args.cleanUpResourcesLI(); 8681 } 8682 } else { 8683 // The application on /system is older than the application on /data. Hide 8684 // the application on /system and the version on /data will be scanned later 8685 // and re-added like an update. 8686 shouldHideSystemApp = true; 8687 logCriticalInfo(Log.INFO, 8688 "System package disabled;" 8689 + " name: " + pkgSetting.name 8690 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8691 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8692if (REFACTOR_DEBUG) { 8693Slog.e("TODD", 8694 "System package disabled;" 8695 + " name: " + pkgSetting.name 8696 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8697 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8698} 8699 } 8700 } 8701 8702if (REFACTOR_DEBUG) { 8703Slog.e("TODD", 8704 "Scan package"); 8705Slog.e("TODD", 8706 "Pre: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp())); 8707} 8708 final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags 8709 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8710if (REFACTOR_DEBUG) { 8711pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8712Slog.e("TODD", 8713 "Post: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp())); 8714} 8715 8716 if (shouldHideSystemApp) { 8717if (REFACTOR_DEBUG) { 8718Slog.e("TODD", 8719 "Disable package: " + pkg.packageName); 8720} 8721 synchronized (mPackages) { 8722 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8723 } 8724 } 8725 return scannedPkg; 8726 } 8727 8728 private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8729 // Derive the new package synthetic package name 8730 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8731 + pkg.staticSharedLibVersion); 8732 } 8733 8734 private static String fixProcessName(String defProcessName, 8735 String processName) { 8736 if (processName == null) { 8737 return defProcessName; 8738 } 8739 return processName; 8740 } 8741 8742 /** 8743 * Enforces that only the system UID or root's UID can call a method exposed 8744 * via Binder. 8745 * 8746 * @param message used as message if SecurityException is thrown 8747 * @throws SecurityException if the caller is not system or root 8748 */ 8749 private static final void enforceSystemOrRoot(String message) { 8750 final int uid = Binder.getCallingUid(); 8751 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 8752 throw new SecurityException(message); 8753 } 8754 } 8755 8756 @Override 8757 public void performFstrimIfNeeded() { 8758 enforceSystemOrRoot("Only the system can request fstrim"); 8759 8760 // Before everything else, see whether we need to fstrim. 8761 try { 8762 IStorageManager sm = PackageHelper.getStorageManager(); 8763 if (sm != null) { 8764 boolean doTrim = false; 8765 final long interval = android.provider.Settings.Global.getLong( 8766 mContext.getContentResolver(), 8767 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8768 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8769 if (interval > 0) { 8770 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8771 if (timeSinceLast > interval) { 8772 doTrim = true; 8773 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8774 + "; running immediately"); 8775 } 8776 } 8777 if (doTrim) { 8778 final boolean dexOptDialogShown; 8779 synchronized (mPackages) { 8780 dexOptDialogShown = mDexOptDialogShown; 8781 } 8782 if (!isFirstBoot() && dexOptDialogShown) { 8783 try { 8784 ActivityManager.getService().showBootMessage( 8785 mContext.getResources().getString( 8786 R.string.android_upgrading_fstrim), true); 8787 } catch (RemoteException e) { 8788 } 8789 } 8790 sm.runMaintenance(); 8791 } 8792 } else { 8793 Slog.e(TAG, "storageManager service unavailable!"); 8794 } 8795 } catch (RemoteException e) { 8796 // Can't happen; StorageManagerService is local 8797 } 8798 } 8799 8800 @Override 8801 public void updatePackagesIfNeeded() { 8802 enforceSystemOrRoot("Only the system can request package update"); 8803 8804 // We need to re-extract after an OTA. 8805 boolean causeUpgrade = isUpgrade(); 8806 8807 // First boot or factory reset. 8808 // Note: we also handle devices that are upgrading to N right now as if it is their 8809 // first boot, as they do not have profile data. 8810 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8811 8812 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8813 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8814 8815 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8816 return; 8817 } 8818 8819 List<PackageParser.Package> pkgs; 8820 synchronized (mPackages) { 8821 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8822 } 8823 8824 final long startTime = System.nanoTime(); 8825 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8826 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 8827 false /* bootComplete */); 8828 8829 final int elapsedTimeSeconds = 8830 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8831 8832 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8833 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8834 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8835 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8836 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8837 } 8838 8839 /* 8840 * Return the prebuilt profile path given a package base code path. 8841 */ 8842 private static String getPrebuildProfilePath(PackageParser.Package pkg) { 8843 return pkg.baseCodePath + ".prof"; 8844 } 8845 8846 /** 8847 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8848 * containing statistics about the invocation. The array consists of three elements, 8849 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8850 * and {@code numberOfPackagesFailed}. 8851 */ 8852 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8853 final String compilerFilter, boolean bootComplete) { 8854 8855 int numberOfPackagesVisited = 0; 8856 int numberOfPackagesOptimized = 0; 8857 int numberOfPackagesSkipped = 0; 8858 int numberOfPackagesFailed = 0; 8859 final int numberOfPackagesToDexopt = pkgs.size(); 8860 8861 for (PackageParser.Package pkg : pkgs) { 8862 numberOfPackagesVisited++; 8863 8864 boolean useProfileForDexopt = false; 8865 8866 if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) { 8867 // Copy over initial preopt profiles since we won't get any JIT samples for methods 8868 // that are already compiled. 8869 File profileFile = new File(getPrebuildProfilePath(pkg)); 8870 // Copy profile if it exists. 8871 if (profileFile.exists()) { 8872 try { 8873 // We could also do this lazily before calling dexopt in 8874 // PackageDexOptimizer to prevent this happening on first boot. The issue 8875 // is that we don't have a good way to say "do this only once". 8876 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8877 pkg.applicationInfo.uid, pkg.packageName)) { 8878 Log.e(TAG, "Installer failed to copy system profile!"); 8879 } else { 8880 // Disabled as this causes speed-profile compilation during first boot 8881 // even if things are already compiled. 8882 // useProfileForDexopt = true; 8883 } 8884 } catch (Exception e) { 8885 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", 8886 e); 8887 } 8888 } else { 8889 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8890 // Handle compressed APKs in this path. Only do this for stubs with profiles to 8891 // minimize the number off apps being speed-profile compiled during first boot. 8892 // The other paths will not change the filter. 8893 if (disabledPs != null && disabledPs.pkg.isStub) { 8894 // The package is the stub one, remove the stub suffix to get the normal 8895 // package and APK names. 8896 String systemProfilePath = 8897 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, ""); 8898 profileFile = new File(systemProfilePath); 8899 // If we have a profile for a compressed APK, copy it to the reference 8900 // location. 8901 // Note that copying the profile here will cause it to override the 8902 // reference profile every OTA even though the existing reference profile 8903 // may have more data. We can't copy during decompression since the 8904 // directories are not set up at that point. 8905 if (profileFile.exists()) { 8906 try { 8907 // We could also do this lazily before calling dexopt in 8908 // PackageDexOptimizer to prevent this happening on first boot. The 8909 // issue is that we don't have a good way to say "do this only 8910 // once". 8911 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8912 pkg.applicationInfo.uid, pkg.packageName)) { 8913 Log.e(TAG, "Failed to copy system profile for stub package!"); 8914 } else { 8915 useProfileForDexopt = true; 8916 } 8917 } catch (Exception e) { 8918 Log.e(TAG, "Failed to copy profile " + 8919 profileFile.getAbsolutePath() + " ", e); 8920 } 8921 } 8922 } 8923 } 8924 } 8925 8926 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8927 if (DEBUG_DEXOPT) { 8928 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8929 } 8930 numberOfPackagesSkipped++; 8931 continue; 8932 } 8933 8934 if (DEBUG_DEXOPT) { 8935 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8936 numberOfPackagesToDexopt + ": " + pkg.packageName); 8937 } 8938 8939 if (showDialog) { 8940 try { 8941 ActivityManager.getService().showBootMessage( 8942 mContext.getResources().getString(R.string.android_upgrading_apk, 8943 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8944 } catch (RemoteException e) { 8945 } 8946 synchronized (mPackages) { 8947 mDexOptDialogShown = true; 8948 } 8949 } 8950 8951 String pkgCompilerFilter = compilerFilter; 8952 if (useProfileForDexopt) { 8953 // Use background dexopt mode to try and use the profile. Note that this does not 8954 // guarantee usage of the profile. 8955 pkgCompilerFilter = 8956 PackageManagerServiceCompilerMapping.getCompilerFilterForReason( 8957 PackageManagerService.REASON_BACKGROUND_DEXOPT); 8958 } 8959 8960 // checkProfiles is false to avoid merging profiles during boot which 8961 // might interfere with background compilation (b/28612421). 8962 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8963 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8964 // trade-off worth doing to save boot time work. 8965 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0; 8966 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions( 8967 pkg.packageName, 8968 pkgCompilerFilter, 8969 dexoptFlags)); 8970 8971 switch (primaryDexOptStaus) { 8972 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8973 numberOfPackagesOptimized++; 8974 break; 8975 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8976 numberOfPackagesSkipped++; 8977 break; 8978 case PackageDexOptimizer.DEX_OPT_FAILED: 8979 numberOfPackagesFailed++; 8980 break; 8981 default: 8982 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus); 8983 break; 8984 } 8985 } 8986 8987 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8988 numberOfPackagesFailed }; 8989 } 8990 8991 @Override 8992 public void notifyPackageUse(String packageName, int reason) { 8993 synchronized (mPackages) { 8994 final int callingUid = Binder.getCallingUid(); 8995 final int callingUserId = UserHandle.getUserId(callingUid); 8996 if (getInstantAppPackageName(callingUid) != null) { 8997 if (!isCallerSameApp(packageName, callingUid)) { 8998 return; 8999 } 9000 } else { 9001 if (isInstantApp(packageName, callingUserId)) { 9002 return; 9003 } 9004 } 9005 notifyPackageUseLocked(packageName, reason); 9006 } 9007 } 9008 9009 private void notifyPackageUseLocked(String packageName, int reason) { 9010 final PackageParser.Package p = mPackages.get(packageName); 9011 if (p == null) { 9012 return; 9013 } 9014 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 9015 } 9016 9017 @Override 9018 public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames, 9019 List<String> classPaths, String loaderIsa) { 9020 int userId = UserHandle.getCallingUserId(); 9021 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 9022 if (ai == null) { 9023 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 9024 + loadingPackageName + ", user=" + userId); 9025 return; 9026 } 9027 mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId); 9028 } 9029 9030 @Override 9031 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule, 9032 IDexModuleRegisterCallback callback) { 9033 int userId = UserHandle.getCallingUserId(); 9034 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId); 9035 DexManager.RegisterDexModuleResult result; 9036 if (ai == null) { 9037 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" + 9038 " calling user. package=" + packageName + ", user=" + userId); 9039 result = new DexManager.RegisterDexModuleResult(false, "Package not installed"); 9040 } else { 9041 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId); 9042 } 9043 9044 if (callback != null) { 9045 mHandler.post(() -> { 9046 try { 9047 callback.onDexModuleRegistered(dexModulePath, result.success, result.message); 9048 } catch (RemoteException e) { 9049 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e); 9050 } 9051 }); 9052 } 9053 } 9054 9055 /** 9056 * Ask the package manager to perform a dex-opt with the given compiler filter. 9057 * 9058 * Note: exposed only for the shell command to allow moving packages explicitly to a 9059 * definite state. 9060 */ 9061 @Override 9062 public boolean performDexOptMode(String packageName, 9063 boolean checkProfiles, String targetCompilerFilter, boolean force, 9064 boolean bootComplete, String splitName) { 9065 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) | 9066 (force ? DexoptOptions.DEXOPT_FORCE : 0) | 9067 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0); 9068 return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter, 9069 splitName, flags)); 9070 } 9071 9072 /** 9073 * Ask the package manager to perform a dex-opt with the given compiler filter on the 9074 * secondary dex files belonging to the given package. 9075 * 9076 * Note: exposed only for the shell command to allow moving packages explicitly to a 9077 * definite state. 9078 */ 9079 @Override 9080 public boolean performDexOptSecondary(String packageName, String compilerFilter, 9081 boolean force) { 9082 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX | 9083 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES | 9084 DexoptOptions.DEXOPT_BOOT_COMPLETE | 9085 (force ? DexoptOptions.DEXOPT_FORCE : 0); 9086 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags)); 9087 } 9088 9089 /*package*/ boolean performDexOpt(DexoptOptions options) { 9090 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9091 return false; 9092 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) { 9093 return false; 9094 } 9095 9096 if (options.isDexoptOnlySecondaryDex()) { 9097 return mDexManager.dexoptSecondaryDex(options); 9098 } else { 9099 int dexoptStatus = performDexOptWithStatus(options); 9100 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9101 } 9102 } 9103 9104 /** 9105 * Perform dexopt on the given package and return one of following result: 9106 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9107 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9108 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9109 */ 9110 /* package */ int performDexOptWithStatus(DexoptOptions options) { 9111 return performDexOptTraced(options); 9112 } 9113 9114 private int performDexOptTraced(DexoptOptions options) { 9115 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9116 try { 9117 return performDexOptInternal(options); 9118 } finally { 9119 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9120 } 9121 } 9122 9123 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9124 // if the package can now be considered up to date for the given filter. 9125 private int performDexOptInternal(DexoptOptions options) { 9126 PackageParser.Package p; 9127 synchronized (mPackages) { 9128 p = mPackages.get(options.getPackageName()); 9129 if (p == null) { 9130 // Package could not be found. Report failure. 9131 return PackageDexOptimizer.DEX_OPT_FAILED; 9132 } 9133 mPackageUsage.maybeWriteAsync(mPackages); 9134 mCompilerStats.maybeWriteAsync(); 9135 } 9136 long callingId = Binder.clearCallingIdentity(); 9137 try { 9138 synchronized (mInstallLock) { 9139 return performDexOptInternalWithDependenciesLI(p, options); 9140 } 9141 } finally { 9142 Binder.restoreCallingIdentity(callingId); 9143 } 9144 } 9145 9146 public ArraySet<String> getOptimizablePackages() { 9147 ArraySet<String> pkgs = new ArraySet<String>(); 9148 synchronized (mPackages) { 9149 for (PackageParser.Package p : mPackages.values()) { 9150 if (PackageDexOptimizer.canOptimizePackage(p)) { 9151 pkgs.add(p.packageName); 9152 } 9153 } 9154 } 9155 return pkgs; 9156 } 9157 9158 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9159 DexoptOptions options) { 9160 // Select the dex optimizer based on the force parameter. 9161 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9162 // allocate an object here. 9163 PackageDexOptimizer pdo = options.isForce() 9164 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9165 : mPackageDexOptimizer; 9166 9167 // Dexopt all dependencies first. Note: we ignore the return value and march on 9168 // on errors. 9169 // Note that we are going to call performDexOpt on those libraries as many times as 9170 // they are referenced in packages. When we do a batch of performDexOpt (for example 9171 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9172 // and the first package that uses the library will dexopt it. The 9173 // others will see that the compiled code for the library is up to date. 9174 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 9175 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9176 if (!deps.isEmpty()) { 9177 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(), 9178 options.getCompilerFilter(), options.getSplitName(), 9179 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY); 9180 for (PackageParser.Package depPackage : deps) { 9181 // TODO: Analyze and investigate if we (should) profile libraries. 9182 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 9183 getOrCreateCompilerPackageStats(depPackage), 9184 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions); 9185 } 9186 } 9187 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, 9188 getOrCreateCompilerPackageStats(p), 9189 mDexManager.getPackageUseInfoOrDefault(p.packageName), options); 9190 } 9191 9192 /** 9193 * Reconcile the information we have about the secondary dex files belonging to 9194 * {@code packagName} and the actual dex files. For all dex files that were 9195 * deleted, update the internal records and delete the generated oat files. 9196 */ 9197 @Override 9198 public void reconcileSecondaryDexFiles(String packageName) { 9199 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9200 return; 9201 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9202 return; 9203 } 9204 mDexManager.reconcileSecondaryDexFiles(packageName); 9205 } 9206 9207 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 9208 // a reference there. 9209 /*package*/ DexManager getDexManager() { 9210 return mDexManager; 9211 } 9212 9213 /** 9214 * Execute the background dexopt job immediately. 9215 */ 9216 @Override 9217 public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) { 9218 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9219 return false; 9220 } 9221 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames); 9222 } 9223 9224 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 9225 if (p.usesLibraries != null || p.usesOptionalLibraries != null 9226 || p.usesStaticLibraries != null) { 9227 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 9228 Set<String> collectedNames = new HashSet<>(); 9229 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 9230 9231 retValue.remove(p); 9232 9233 return retValue; 9234 } else { 9235 return Collections.emptyList(); 9236 } 9237 } 9238 9239 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 9240 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9241 if (!collectedNames.contains(p.packageName)) { 9242 collectedNames.add(p.packageName); 9243 collected.add(p); 9244 9245 if (p.usesLibraries != null) { 9246 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 9247 null, collected, collectedNames); 9248 } 9249 if (p.usesOptionalLibraries != null) { 9250 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 9251 null, collected, collectedNames); 9252 } 9253 if (p.usesStaticLibraries != null) { 9254 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 9255 p.usesStaticLibrariesVersions, collected, collectedNames); 9256 } 9257 } 9258 } 9259 9260 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions, 9261 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9262 final int libNameCount = libs.size(); 9263 for (int i = 0; i < libNameCount; i++) { 9264 String libName = libs.get(i); 9265 long version = (versions != null && versions.length == libNameCount) 9266 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 9267 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 9268 if (libPkg != null) { 9269 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 9270 } 9271 } 9272 } 9273 9274 private PackageParser.Package findSharedNonSystemLibrary(String name, long version) { 9275 synchronized (mPackages) { 9276 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 9277 if (libEntry != null) { 9278 return mPackages.get(libEntry.apk); 9279 } 9280 return null; 9281 } 9282 } 9283 9284 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) { 9285 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9286 if (versionedLib == null) { 9287 return null; 9288 } 9289 return versionedLib.get(version); 9290 } 9291 9292 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9293 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9294 pkg.staticSharedLibName); 9295 if (versionedLib == null) { 9296 return null; 9297 } 9298 long previousLibVersion = -1; 9299 final int versionCount = versionedLib.size(); 9300 for (int i = 0; i < versionCount; i++) { 9301 final long libVersion = versionedLib.keyAt(i); 9302 if (libVersion < pkg.staticSharedLibVersion) { 9303 previousLibVersion = Math.max(previousLibVersion, libVersion); 9304 } 9305 } 9306 if (previousLibVersion >= 0) { 9307 return versionedLib.get(previousLibVersion); 9308 } 9309 return null; 9310 } 9311 9312 public void shutdown() { 9313 mPackageUsage.writeNow(mPackages); 9314 mCompilerStats.writeNow(); 9315 mDexManager.writePackageDexUsageNow(); 9316 } 9317 9318 @Override 9319 public void dumpProfiles(String packageName) { 9320 PackageParser.Package pkg; 9321 synchronized (mPackages) { 9322 pkg = mPackages.get(packageName); 9323 if (pkg == null) { 9324 throw new IllegalArgumentException("Unknown package: " + packageName); 9325 } 9326 } 9327 /* Only the shell, root, or the app user should be able to dump profiles. */ 9328 int callingUid = Binder.getCallingUid(); 9329 if (callingUid != Process.SHELL_UID && 9330 callingUid != Process.ROOT_UID && 9331 callingUid != pkg.applicationInfo.uid) { 9332 throw new SecurityException("dumpProfiles"); 9333 } 9334 9335 synchronized (mInstallLock) { 9336 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9337 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 9338 try { 9339 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 9340 String codePaths = TextUtils.join(";", allCodePaths); 9341 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 9342 } catch (InstallerException e) { 9343 Slog.w(TAG, "Failed to dump profiles", e); 9344 } 9345 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9346 } 9347 } 9348 9349 @Override 9350 public void forceDexOpt(String packageName) { 9351 enforceSystemOrRoot("forceDexOpt"); 9352 9353 PackageParser.Package pkg; 9354 synchronized (mPackages) { 9355 pkg = mPackages.get(packageName); 9356 if (pkg == null) { 9357 throw new IllegalArgumentException("Unknown package: " + packageName); 9358 } 9359 } 9360 9361 synchronized (mInstallLock) { 9362 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9363 9364 // Whoever is calling forceDexOpt wants a compiled package. 9365 // Don't use profiles since that may cause compilation to be skipped. 9366 final int res = performDexOptInternalWithDependenciesLI( 9367 pkg, 9368 new DexoptOptions(packageName, 9369 getDefaultCompilerFilter(), 9370 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE)); 9371 9372 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9373 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9374 throw new IllegalStateException("Failed to dexopt: " + res); 9375 } 9376 } 9377 } 9378 9379 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9380 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9381 Slog.w(TAG, "Unable to update from " + oldPkg.name 9382 + " to " + newPkg.packageName 9383 + ": old package not in system partition"); 9384 return false; 9385 } else if (mPackages.get(oldPkg.name) != null) { 9386 Slog.w(TAG, "Unable to update from " + oldPkg.name 9387 + " to " + newPkg.packageName 9388 + ": old package still exists"); 9389 return false; 9390 } 9391 return true; 9392 } 9393 9394 void removeCodePathLI(File codePath) { 9395 if (codePath.isDirectory()) { 9396 try { 9397 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9398 } catch (InstallerException e) { 9399 Slog.w(TAG, "Failed to remove code path", e); 9400 } 9401 } else { 9402 codePath.delete(); 9403 } 9404 } 9405 9406 private int[] resolveUserIds(int userId) { 9407 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9408 } 9409 9410 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9411 if (pkg == null) { 9412 Slog.wtf(TAG, "Package was null!", new Throwable()); 9413 return; 9414 } 9415 clearAppDataLeafLIF(pkg, userId, flags); 9416 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9417 for (int i = 0; i < childCount; i++) { 9418 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9419 } 9420 } 9421 9422 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9423 final PackageSetting ps; 9424 synchronized (mPackages) { 9425 ps = mSettings.mPackages.get(pkg.packageName); 9426 } 9427 for (int realUserId : resolveUserIds(userId)) { 9428 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9429 try { 9430 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9431 ceDataInode); 9432 } catch (InstallerException e) { 9433 Slog.w(TAG, String.valueOf(e)); 9434 } 9435 } 9436 } 9437 9438 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9439 if (pkg == null) { 9440 Slog.wtf(TAG, "Package was null!", new Throwable()); 9441 return; 9442 } 9443 destroyAppDataLeafLIF(pkg, userId, flags); 9444 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9445 for (int i = 0; i < childCount; i++) { 9446 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9447 } 9448 } 9449 9450 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9451 final PackageSetting ps; 9452 synchronized (mPackages) { 9453 ps = mSettings.mPackages.get(pkg.packageName); 9454 } 9455 for (int realUserId : resolveUserIds(userId)) { 9456 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9457 try { 9458 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9459 ceDataInode); 9460 } catch (InstallerException e) { 9461 Slog.w(TAG, String.valueOf(e)); 9462 } 9463 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9464 } 9465 } 9466 9467 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9468 if (pkg == null) { 9469 Slog.wtf(TAG, "Package was null!", new Throwable()); 9470 return; 9471 } 9472 destroyAppProfilesLeafLIF(pkg); 9473 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9474 for (int i = 0; i < childCount; i++) { 9475 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9476 } 9477 } 9478 9479 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9480 try { 9481 mInstaller.destroyAppProfiles(pkg.packageName); 9482 } catch (InstallerException e) { 9483 Slog.w(TAG, String.valueOf(e)); 9484 } 9485 } 9486 9487 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9488 if (pkg == null) { 9489 Slog.wtf(TAG, "Package was null!", new Throwable()); 9490 return; 9491 } 9492 clearAppProfilesLeafLIF(pkg); 9493 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9494 for (int i = 0; i < childCount; i++) { 9495 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 9496 } 9497 } 9498 9499 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 9500 try { 9501 mInstaller.clearAppProfiles(pkg.packageName); 9502 } catch (InstallerException e) { 9503 Slog.w(TAG, String.valueOf(e)); 9504 } 9505 } 9506 9507 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9508 long lastUpdateTime) { 9509 // Set parent install/update time 9510 PackageSetting ps = (PackageSetting) pkg.mExtras; 9511 if (ps != null) { 9512 ps.firstInstallTime = firstInstallTime; 9513 ps.lastUpdateTime = lastUpdateTime; 9514 } 9515 // Set children install/update time 9516 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9517 for (int i = 0; i < childCount; i++) { 9518 PackageParser.Package childPkg = pkg.childPackages.get(i); 9519 ps = (PackageSetting) childPkg.mExtras; 9520 if (ps != null) { 9521 ps.firstInstallTime = firstInstallTime; 9522 ps.lastUpdateTime = lastUpdateTime; 9523 } 9524 } 9525 } 9526 9527 private void addSharedLibraryLPr(Set<String> usesLibraryFiles, 9528 SharedLibraryEntry file, 9529 PackageParser.Package changingLib) { 9530 if (file.path != null) { 9531 usesLibraryFiles.add(file.path); 9532 return; 9533 } 9534 PackageParser.Package p = mPackages.get(file.apk); 9535 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9536 // If we are doing this while in the middle of updating a library apk, 9537 // then we need to make sure to use that new apk for determining the 9538 // dependencies here. (We haven't yet finished committing the new apk 9539 // to the package manager state.) 9540 if (p == null || p.packageName.equals(changingLib.packageName)) { 9541 p = changingLib; 9542 } 9543 } 9544 if (p != null) { 9545 usesLibraryFiles.addAll(p.getAllCodePaths()); 9546 if (p.usesLibraryFiles != null) { 9547 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 9548 } 9549 } 9550 } 9551 9552 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9553 PackageParser.Package changingLib) throws PackageManagerException { 9554 if (pkg == null) { 9555 return; 9556 } 9557 // The collection used here must maintain the order of addition (so 9558 // that libraries are searched in the correct order) and must have no 9559 // duplicates. 9560 Set<String> usesLibraryFiles = null; 9561 if (pkg.usesLibraries != null) { 9562 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9563 null, null, pkg.packageName, changingLib, true, 9564 pkg.applicationInfo.targetSdkVersion, null); 9565 } 9566 if (pkg.usesStaticLibraries != null) { 9567 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9568 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9569 pkg.packageName, changingLib, true, 9570 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9571 } 9572 if (pkg.usesOptionalLibraries != null) { 9573 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9574 null, null, pkg.packageName, changingLib, false, 9575 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9576 } 9577 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9578 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9579 } else { 9580 pkg.usesLibraryFiles = null; 9581 } 9582 } 9583 9584 private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9585 @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests, 9586 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9587 boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries) 9588 throws PackageManagerException { 9589 final int libCount = requestedLibraries.size(); 9590 for (int i = 0; i < libCount; i++) { 9591 final String libName = requestedLibraries.get(i); 9592 final long libVersion = requiredVersions != null ? requiredVersions[i] 9593 : SharedLibraryInfo.VERSION_UNDEFINED; 9594 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9595 if (libEntry == null) { 9596 if (required) { 9597 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9598 "Package " + packageName + " requires unavailable shared library " 9599 + libName + "; failing!"); 9600 } else if (DEBUG_SHARED_LIBRARIES) { 9601 Slog.i(TAG, "Package " + packageName 9602 + " desires unavailable shared library " 9603 + libName + "; ignoring!"); 9604 } 9605 } else { 9606 if (requiredVersions != null && requiredCertDigests != null) { 9607 if (libEntry.info.getLongVersion() != requiredVersions[i]) { 9608 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9609 "Package " + packageName + " requires unavailable static shared" 9610 + " library " + libName + " version " 9611 + libEntry.info.getLongVersion() + "; failing!"); 9612 } 9613 9614 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9615 if (libPkg == null) { 9616 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9617 "Package " + packageName + " requires unavailable static shared" 9618 + " library; failing!"); 9619 } 9620 9621 final String[] expectedCertDigests = requiredCertDigests[i]; 9622 // For apps targeting O MR1 we require explicit enumeration of all certs. 9623 final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O) 9624 ? PackageUtils.computeSignaturesSha256Digests( 9625 libPkg.mSigningDetails.signatures) 9626 : PackageUtils.computeSignaturesSha256Digests( 9627 new Signature[]{libPkg.mSigningDetails.signatures[0]}); 9628 9629 // Take a shortcut if sizes don't match. Note that if an app doesn't 9630 // target O we don't parse the "additional-certificate" tags similarly 9631 // how we only consider all certs only for apps targeting O (see above). 9632 // Therefore, the size check is safe to make. 9633 if (expectedCertDigests.length != libCertDigests.length) { 9634 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9635 "Package " + packageName + " requires differently signed" + 9636 " static shared library; failing!"); 9637 } 9638 9639 // Use a predictable order as signature order may vary 9640 Arrays.sort(libCertDigests); 9641 Arrays.sort(expectedCertDigests); 9642 9643 final int certCount = libCertDigests.length; 9644 for (int j = 0; j < certCount; j++) { 9645 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) { 9646 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9647 "Package " + packageName + " requires differently signed" + 9648 " static shared library; failing!"); 9649 } 9650 } 9651 } 9652 9653 if (outUsedLibraries == null) { 9654 // Use LinkedHashSet to preserve the order of files added to 9655 // usesLibraryFiles while eliminating duplicates. 9656 outUsedLibraries = new LinkedHashSet<>(); 9657 } 9658 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9659 } 9660 } 9661 return outUsedLibraries; 9662 } 9663 9664 private static boolean hasString(List<String> list, List<String> which) { 9665 if (list == null) { 9666 return false; 9667 } 9668 for (int i=list.size()-1; i>=0; i--) { 9669 for (int j=which.size()-1; j>=0; j--) { 9670 if (which.get(j).equals(list.get(i))) { 9671 return true; 9672 } 9673 } 9674 } 9675 return false; 9676 } 9677 9678 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9679 PackageParser.Package changingPkg) { 9680 ArrayList<PackageParser.Package> res = null; 9681 for (PackageParser.Package pkg : mPackages.values()) { 9682 if (changingPkg != null 9683 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9684 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9685 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9686 changingPkg.staticSharedLibName)) { 9687 return null; 9688 } 9689 if (res == null) { 9690 res = new ArrayList<>(); 9691 } 9692 res.add(pkg); 9693 try { 9694 updateSharedLibrariesLPr(pkg, changingPkg); 9695 } catch (PackageManagerException e) { 9696 // If a system app update or an app and a required lib missing we 9697 // delete the package and for updated system apps keep the data as 9698 // it is better for the user to reinstall than to be in an limbo 9699 // state. Also libs disappearing under an app should never happen 9700 // - just in case. 9701 if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) { 9702 final int flags = pkg.isUpdatedSystemApp() 9703 ? PackageManager.DELETE_KEEP_DATA : 0; 9704 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9705 flags , null, true, null); 9706 } 9707 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9708 } 9709 } 9710 return res; 9711 } 9712 9713 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9714 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9715 @Nullable UserHandle user) throws PackageManagerException { 9716 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9717 // If the package has children and this is the first dive in the function 9718 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9719 // whether all packages (parent and children) would be successfully scanned 9720 // before the actual scan since scanning mutates internal state and we want 9721 // to atomically install the package and its children. 9722 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9723 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9724 scanFlags |= SCAN_CHECK_ONLY; 9725 } 9726 } else { 9727 scanFlags &= ~SCAN_CHECK_ONLY; 9728 } 9729 9730 final PackageParser.Package scannedPkg; 9731 try { 9732 // Scan the parent 9733 scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user); 9734 // Scan the children 9735 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9736 for (int i = 0; i < childCount; i++) { 9737 PackageParser.Package childPkg = pkg.childPackages.get(i); 9738 scanPackageNewLI(childPkg, parseFlags, 9739 scanFlags, currentTime, user); 9740 } 9741 } finally { 9742 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9743 } 9744 9745 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9746 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 9747 } 9748 9749 return scannedPkg; 9750 } 9751 9752 /** The result of a package scan. */ 9753 private static class ScanResult { 9754 /** Whether or not the package scan was successful */ 9755 public final boolean success; 9756 /** 9757 * The final package settings. This may be the same object passed in 9758 * the {@link ScanRequest}, but, with modified values. 9759 */ 9760 @Nullable public final PackageSetting pkgSetting; 9761 /** ABI code paths that have changed in the package scan */ 9762 @Nullable public final List<String> changedAbiCodePath; 9763 public ScanResult( 9764 boolean success, 9765 @Nullable PackageSetting pkgSetting, 9766 @Nullable List<String> changedAbiCodePath) { 9767 this.success = success; 9768 this.pkgSetting = pkgSetting; 9769 this.changedAbiCodePath = changedAbiCodePath; 9770 } 9771 } 9772 9773 /** A package to be scanned */ 9774 private static class ScanRequest { 9775 /** The parsed package */ 9776 @NonNull public final PackageParser.Package pkg; 9777 /** Shared user settings, if the package has a shared user */ 9778 @Nullable public final SharedUserSetting sharedUserSetting; 9779 /** 9780 * Package settings of the currently installed version. 9781 * <p><em>IMPORTANT:</em> The contents of this object may be modified 9782 * during scan. 9783 */ 9784 @Nullable public final PackageSetting pkgSetting; 9785 /** A copy of the settings for the currently installed version */ 9786 @Nullable public final PackageSetting oldPkgSetting; 9787 /** Package settings for the disabled version on the /system partition */ 9788 @Nullable public final PackageSetting disabledPkgSetting; 9789 /** Package settings for the installed version under its original package name */ 9790 @Nullable public final PackageSetting originalPkgSetting; 9791 /** The real package name of a renamed application */ 9792 @Nullable public final String realPkgName; 9793 public final @ParseFlags int parseFlags; 9794 public final @ScanFlags int scanFlags; 9795 /** The user for which the package is being scanned */ 9796 @Nullable public final UserHandle user; 9797 /** Whether or not the platform package is being scanned */ 9798 public final boolean isPlatformPackage; 9799 public ScanRequest( 9800 @NonNull PackageParser.Package pkg, 9801 @Nullable SharedUserSetting sharedUserSetting, 9802 @Nullable PackageSetting pkgSetting, 9803 @Nullable PackageSetting disabledPkgSetting, 9804 @Nullable PackageSetting originalPkgSetting, 9805 @Nullable String realPkgName, 9806 @ParseFlags int parseFlags, 9807 @ScanFlags int scanFlags, 9808 boolean isPlatformPackage, 9809 @Nullable UserHandle user) { 9810 this.pkg = pkg; 9811 this.pkgSetting = pkgSetting; 9812 this.sharedUserSetting = sharedUserSetting; 9813 this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting); 9814 this.disabledPkgSetting = disabledPkgSetting; 9815 this.originalPkgSetting = originalPkgSetting; 9816 this.realPkgName = realPkgName; 9817 this.parseFlags = parseFlags; 9818 this.scanFlags = scanFlags; 9819 this.isPlatformPackage = isPlatformPackage; 9820 this.user = user; 9821 } 9822 } 9823 9824 /** 9825 * Returns the actual scan flags depending upon the state of the other settings. 9826 * <p>Updated system applications will not have the following flags set 9827 * by default and need to be adjusted after the fact: 9828 * <ul> 9829 * <li>{@link #SCAN_AS_SYSTEM}</li> 9830 * <li>{@link #SCAN_AS_PRIVILEGED}</li> 9831 * <li>{@link #SCAN_AS_OEM}</li> 9832 * <li>{@link #SCAN_AS_VENDOR}</li> 9833 * <li>{@link #SCAN_AS_INSTANT_APP}</li> 9834 * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li> 9835 * </ul> 9836 */ 9837 private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags, 9838 PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user, 9839 PackageParser.Package pkg) { 9840 if (disabledPkgSetting != null) { 9841 // updated system application, must at least have SCAN_AS_SYSTEM 9842 scanFlags |= SCAN_AS_SYSTEM; 9843 if ((disabledPkgSetting.pkgPrivateFlags 9844 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 9845 scanFlags |= SCAN_AS_PRIVILEGED; 9846 } 9847 if ((disabledPkgSetting.pkgPrivateFlags 9848 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) { 9849 scanFlags |= SCAN_AS_OEM; 9850 } 9851 if ((disabledPkgSetting.pkgPrivateFlags 9852 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) { 9853 scanFlags |= SCAN_AS_VENDOR; 9854 } 9855 } 9856 if (pkgSetting != null) { 9857 final int userId = ((user == null) ? 0 : user.getIdentifier()); 9858 if (pkgSetting.getInstantApp(userId)) { 9859 scanFlags |= SCAN_AS_INSTANT_APP; 9860 } 9861 if (pkgSetting.getVirtulalPreload(userId)) { 9862 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 9863 } 9864 } 9865 9866 // Scan as privileged apps that share a user with a priv-app. 9867 if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged() 9868 && (pkg.mSharedUserId != null)) { 9869 SharedUserSetting sharedUserSetting = null; 9870 try { 9871 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 9872 } catch (PackageManagerException ignore) {} 9873 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 9874 // Exempt SharedUsers signed with the platform key. 9875 // TODO(b/72378145) Fix this exemption. Force signature apps 9876 // to whitelist their privileged permissions just like other 9877 // priv-apps. 9878 synchronized (mPackages) { 9879 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 9880 if (!pkg.packageName.equals("android") 9881 && (compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures, 9882 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) { 9883 scanFlags |= SCAN_AS_PRIVILEGED; 9884 } 9885 } 9886 } 9887 } 9888 9889 return scanFlags; 9890 } 9891 9892 @GuardedBy("mInstallLock") 9893 private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg, 9894 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9895 @Nullable UserHandle user) throws PackageManagerException { 9896 9897 final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9898 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 9899 if (realPkgName != null) { 9900 ensurePackageRenamed(pkg, renamedPkgName); 9901 } 9902 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 9903 final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9904 final PackageSetting disabledPkgSetting = 9905 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9906 9907 if (mTransferedPackages.contains(pkg.packageName)) { 9908 Slog.w(TAG, "Package " + pkg.packageName 9909 + " was transferred to another, but its .apk remains"); 9910 } 9911 9912 scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg); 9913 synchronized (mPackages) { 9914 applyPolicy(pkg, parseFlags, scanFlags); 9915 assertPackageIsValid(pkg, parseFlags, scanFlags); 9916 9917 SharedUserSetting sharedUserSetting = null; 9918 if (pkg.mSharedUserId != null) { 9919 // SIDE EFFECTS; may potentially allocate a new shared user 9920 sharedUserSetting = mSettings.getSharedUserLPw( 9921 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9922 if (DEBUG_PACKAGE_SCANNING) { 9923 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 9924 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 9925 + " (uid=" + sharedUserSetting.userId + "):" 9926 + " packages=" + sharedUserSetting.packages); 9927 } 9928 } 9929 9930 boolean scanSucceeded = false; 9931 try { 9932 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting, 9933 disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags, 9934 (pkg == mPlatformPackage), user); 9935 final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime); 9936 if (result.success) { 9937 commitScanResultsLocked(request, result); 9938 } 9939 scanSucceeded = true; 9940 } finally { 9941 if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9942 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9943 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9944 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9945 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9946 } 9947 } 9948 } 9949 return pkg; 9950 } 9951 9952 /** 9953 * Commits the package scan and modifies system state. 9954 * <p><em>WARNING:</em> The method may throw an excpetion in the middle 9955 * of committing the package, leaving the system in an inconsistent state. 9956 * This needs to be fixed so, once we get to this point, no errors are 9957 * possible and the system is not left in an inconsistent state. 9958 */ 9959 @GuardedBy("mPackages") 9960 private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result) 9961 throws PackageManagerException { 9962 final PackageParser.Package pkg = request.pkg; 9963 final @ParseFlags int parseFlags = request.parseFlags; 9964 final @ScanFlags int scanFlags = request.scanFlags; 9965 final PackageSetting oldPkgSetting = request.oldPkgSetting; 9966 final PackageSetting originalPkgSetting = request.originalPkgSetting; 9967 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 9968 final UserHandle user = request.user; 9969 final String realPkgName = request.realPkgName; 9970 final PackageSetting pkgSetting = result.pkgSetting; 9971 final List<String> changedAbiCodePath = result.changedAbiCodePath; 9972 final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting); 9973 9974 if (newPkgSettingCreated) { 9975 if (originalPkgSetting != null) { 9976 mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name); 9977 } 9978 // THROWS: when we can't allocate a user id. add call to check if there's 9979 // enough space to ensure we won't throw; otherwise, don't modify state 9980 mSettings.addUserToSettingLPw(pkgSetting); 9981 9982 if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) { 9983 mTransferedPackages.add(originalPkgSetting.name); 9984 } 9985 } 9986 // TODO(toddke): Consider a method specifically for modifying the Package object 9987 // post scan; or, moving this stuff out of the Package object since it has nothing 9988 // to do with the package on disk. 9989 // We need to have this here because addUserToSettingLPw() is sometimes responsible 9990 // for creating the application ID. If we did this earlier, we would be saving the 9991 // correct ID. 9992 pkg.applicationInfo.uid = pkgSetting.appId; 9993 9994 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9995 9996 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) { 9997 mTransferedPackages.add(pkg.packageName); 9998 } 9999 10000 // THROWS: when requested libraries that can't be found. it only changes 10001 // the state of the passed in pkg object, so, move to the top of the method 10002 // and allow it to abort 10003 if ((scanFlags & SCAN_BOOTING) == 0 10004 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10005 // Check all shared libraries and map to their actual file path. 10006 // We only do this here for apps not on a system dir, because those 10007 // are the only ones that can fail an install due to this. We 10008 // will take care of the system apps by updating all of their 10009 // library paths after the scan is done. Also during the initial 10010 // scan don't update any libs as we do this wholesale after all 10011 // apps are scanned to avoid dependency based scanning. 10012 updateSharedLibrariesLPr(pkg, null); 10013 } 10014 10015 // All versions of a static shared library are referenced with the same 10016 // package name. Internally, we use a synthetic package name to allow 10017 // multiple versions of the same shared library to be installed. So, 10018 // we need to generate the synthetic package name of the latest shared 10019 // library in order to compare signatures. 10020 PackageSetting signatureCheckPs = pkgSetting; 10021 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10022 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 10023 if (libraryEntry != null) { 10024 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 10025 } 10026 } 10027 10028 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10029 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 10030 if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 10031 // We just determined the app is signed correctly, so bring 10032 // over the latest parsed certs. 10033 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10034 } else { 10035 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10036 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10037 "Package " + pkg.packageName + " upgrade keys do not match the " 10038 + "previously installed version"); 10039 } else { 10040 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10041 String msg = "System package " + pkg.packageName 10042 + " signature changed; retaining data."; 10043 reportSettingsProblem(Log.WARN, msg); 10044 } 10045 } 10046 } else { 10047 try { 10048 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 10049 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 10050 final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting, 10051 pkg.mSigningDetails, compareCompat, compareRecover); 10052 // The new KeySets will be re-added later in the scanning process. 10053 if (compatMatch) { 10054 synchronized (mPackages) { 10055 ksms.removeAppKeySetDataLPw(pkg.packageName); 10056 } 10057 } 10058 // We just determined the app is signed correctly, so bring 10059 // over the latest parsed certs. 10060 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10061 } catch (PackageManagerException e) { 10062 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10063 throw e; 10064 } 10065 // The signature has changed, but this package is in the system 10066 // image... let's recover! 10067 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10068 // However... if this package is part of a shared user, but it 10069 // doesn't match the signature of the shared user, let's fail. 10070 // What this means is that you can't change the signatures 10071 // associated with an overall shared user, which doesn't seem all 10072 // that unreasonable. 10073 if (signatureCheckPs.sharedUser != null) { 10074 if (compareSignatures( 10075 signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures, 10076 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) { 10077 throw new PackageManagerException( 10078 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10079 "Signature mismatch for shared user: " 10080 + pkgSetting.sharedUser); 10081 } 10082 } 10083 // File a report about this. 10084 String msg = "System package " + pkg.packageName 10085 + " signature changed; retaining data."; 10086 reportSettingsProblem(Log.WARN, msg); 10087 } 10088 } 10089 10090 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 10091 // This package wants to adopt ownership of permissions from 10092 // another package. 10093 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 10094 final String origName = pkg.mAdoptPermissions.get(i); 10095 final PackageSetting orig = mSettings.getPackageLPr(origName); 10096 if (orig != null) { 10097 if (verifyPackageUpdateLPr(orig, pkg)) { 10098 Slog.i(TAG, "Adopting permissions from " + origName + " to " 10099 + pkg.packageName); 10100 mSettings.mPermissions.transferPermissions(origName, pkg.packageName); 10101 } 10102 } 10103 } 10104 } 10105 10106 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 10107 for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) { 10108 final String codePathString = changedAbiCodePath.get(i); 10109 try { 10110 mInstaller.rmdex(codePathString, 10111 getDexCodeInstructionSet(getPreferredInstructionSet())); 10112 } catch (InstallerException ignored) { 10113 } 10114 } 10115 } 10116 10117 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10118 if (oldPkgSetting != null) { 10119 synchronized (mPackages) { 10120 mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting); 10121 } 10122 } 10123 } else { 10124 final int userId = user == null ? 0 : user.getIdentifier(); 10125 // Modify state for the given package setting 10126 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 10127 (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 10128 if (pkgSetting.getInstantApp(userId)) { 10129 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 10130 } 10131 } 10132 } 10133 10134 /** 10135 * Returns the "real" name of the package. 10136 * <p>This may differ from the package's actual name if the application has already 10137 * been installed under one of this package's original names. 10138 */ 10139 private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg, 10140 @Nullable String renamedPkgName) { 10141 if (isPackageRenamed(pkg, renamedPkgName)) { 10142 return pkg.mRealPackage; 10143 } 10144 return null; 10145 } 10146 10147 /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */ 10148 private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg, 10149 @Nullable String renamedPkgName) { 10150 return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName); 10151 } 10152 10153 /** 10154 * Returns the original package setting. 10155 * <p>A package can migrate its name during an update. In this scenario, a package 10156 * designates a set of names that it considers as one of its original names. 10157 * <p>An original package must be signed identically and it must have the same 10158 * shared user [if any]. 10159 */ 10160 @GuardedBy("mPackages") 10161 private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg, 10162 @Nullable String renamedPkgName) { 10163 if (!isPackageRenamed(pkg, renamedPkgName)) { 10164 return null; 10165 } 10166 for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) { 10167 final PackageSetting originalPs = 10168 mSettings.getPackageLPr(pkg.mOriginalPackages.get(i)); 10169 if (originalPs != null) { 10170 // the package is already installed under its original name... 10171 // but, should we use it? 10172 if (!verifyPackageUpdateLPr(originalPs, pkg)) { 10173 // the new package is incompatible with the original 10174 continue; 10175 } else if (originalPs.sharedUser != null) { 10176 if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) { 10177 // the shared user id is incompatible with the original 10178 Slog.w(TAG, "Unable to migrate data from " + originalPs.name 10179 + " to " + pkg.packageName + ": old uid " 10180 + originalPs.sharedUser.name 10181 + " differs from " + pkg.mSharedUserId); 10182 continue; 10183 } 10184 // TODO: Add case when shared user id is added [b/28144775] 10185 } else { 10186 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 10187 + pkg.packageName + " to old name " + originalPs.name); 10188 } 10189 return originalPs; 10190 } 10191 } 10192 return null; 10193 } 10194 10195 /** 10196 * Renames the package if it was installed under a different name. 10197 * <p>When we've already installed the package under an original name, update 10198 * the new package so we can continue to have the old name. 10199 */ 10200 private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg, 10201 @NonNull String renamedPackageName) { 10202 if (pkg.mOriginalPackages == null 10203 || !pkg.mOriginalPackages.contains(renamedPackageName) 10204 || pkg.packageName.equals(renamedPackageName)) { 10205 return; 10206 } 10207 pkg.setPackageName(renamedPackageName); 10208 } 10209 10210 /** 10211 * Just scans the package without any side effects. 10212 * <p>Not entirely true at the moment. There is still one side effect -- this 10213 * method potentially modifies a live {@link PackageSetting} object representing 10214 * the package being scanned. This will be resolved in the future. 10215 * 10216 * @param request Information about the package to be scanned 10217 * @param isUnderFactoryTest Whether or not the device is under factory test 10218 * @param currentTime The current time, in millis 10219 * @return The results of the scan 10220 */ 10221 @GuardedBy("mInstallLock") 10222 private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request, 10223 boolean isUnderFactoryTest, long currentTime) 10224 throws PackageManagerException { 10225 final PackageParser.Package pkg = request.pkg; 10226 PackageSetting pkgSetting = request.pkgSetting; 10227 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10228 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10229 final @ParseFlags int parseFlags = request.parseFlags; 10230 final @ScanFlags int scanFlags = request.scanFlags; 10231 final String realPkgName = request.realPkgName; 10232 final SharedUserSetting sharedUserSetting = request.sharedUserSetting; 10233 final UserHandle user = request.user; 10234 final boolean isPlatformPackage = request.isPlatformPackage; 10235 10236 List<String> changedAbiCodePath = null; 10237 10238 if (DEBUG_PACKAGE_SCANNING) { 10239 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10240 Log.d(TAG, "Scanning package " + pkg.packageName); 10241 } 10242 10243 if (Build.IS_DEBUGGABLE && 10244 pkg.isPrivileged() && 10245 !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) { 10246 PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg); 10247 } 10248 10249 // Initialize package source and resource directories 10250 final File scanFile = new File(pkg.codePath); 10251 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 10252 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 10253 10254 // We keep references to the derived CPU Abis from settings in oder to reuse 10255 // them in the case where we're not upgrading or booting for the first time. 10256 String primaryCpuAbiFromSettings = null; 10257 String secondaryCpuAbiFromSettings = null; 10258 boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0; 10259 10260 if (!needToDeriveAbi) { 10261 if (pkgSetting != null) { 10262 primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString; 10263 secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString; 10264 } else { 10265 // Re-scanning a system package after uninstalling updates; need to derive ABI 10266 needToDeriveAbi = true; 10267 } 10268 } 10269 10270 if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) { 10271 PackageManagerService.reportSettingsProblem(Log.WARN, 10272 "Package " + pkg.packageName + " shared user changed from " 10273 + (pkgSetting.sharedUser != null 10274 ? pkgSetting.sharedUser.name : "<nothing>") 10275 + " to " 10276 + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>") 10277 + "; replacing with new"); 10278 pkgSetting = null; 10279 } 10280 10281 String[] usesStaticLibraries = null; 10282 if (pkg.usesStaticLibraries != null) { 10283 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 10284 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 10285 } 10286 final boolean createNewPackage = (pkgSetting == null); 10287 if (createNewPackage) { 10288 final String parentPackageName = (pkg.parentPackage != null) 10289 ? pkg.parentPackage.packageName : null; 10290 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10291 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0; 10292 // REMOVE SharedUserSetting from method; update in a separate call 10293 pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting, 10294 disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile, 10295 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 10296 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10297 pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10298 user, true /*allowInstall*/, instantApp, virtualPreload, 10299 parentPackageName, pkg.getChildPackageNames(), 10300 UserManagerService.getInstance(), usesStaticLibraries, 10301 pkg.usesStaticLibrariesVersions); 10302 } else { 10303 // REMOVE SharedUserSetting from method; update in a separate call. 10304 // 10305 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 10306 // secondaryCpuAbi are not known at this point so we always update them 10307 // to null here, only to reset them at a later point. 10308 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting, 10309 destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir, 10310 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10311 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10312 pkg.getChildPackageNames(), UserManagerService.getInstance(), 10313 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 10314 } 10315 if (createNewPackage && originalPkgSetting != null) { 10316 // This is the initial transition from the original package, so, 10317 // fix up the new package's name now. We must do this after looking 10318 // up the package under its new name, so getPackageLP takes care of 10319 // fiddling things correctly. 10320 pkg.setPackageName(originalPkgSetting.name); 10321 10322 // File a report about this. 10323 String msg = "New package " + pkgSetting.realName 10324 + " renamed to replace old package " + pkgSetting.name; 10325 reportSettingsProblem(Log.WARN, msg); 10326 } 10327 10328 if (disabledPkgSetting != null) { 10329 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10330 } 10331 10332 SELinuxMMAC.assignSeInfoValue(pkg); 10333 10334 pkg.mExtras = pkgSetting; 10335 pkg.applicationInfo.processName = fixProcessName( 10336 pkg.applicationInfo.packageName, 10337 pkg.applicationInfo.processName); 10338 10339 if (!isPlatformPackage) { 10340 // Get all of our default paths setup 10341 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 10342 } 10343 10344 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 10345 10346 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 10347 if (needToDeriveAbi) { 10348 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 10349 final boolean extractNativeLibs = !pkg.isLibrary(); 10350 derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs); 10351 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10352 10353 // Some system apps still use directory structure for native libraries 10354 // in which case we might end up not detecting abi solely based on apk 10355 // structure. Try to detect abi based on directory structure. 10356 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 10357 pkg.applicationInfo.primaryCpuAbi == null) { 10358 setBundledAppAbisAndRoots(pkg, pkgSetting); 10359 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10360 } 10361 } else { 10362 // This is not a first boot or an upgrade, don't bother deriving the 10363 // ABI during the scan. Instead, trust the value that was stored in the 10364 // package setting. 10365 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 10366 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 10367 10368 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10369 10370 if (DEBUG_ABI_SELECTION) { 10371 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 10372 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 10373 pkg.applicationInfo.secondaryCpuAbi); 10374 } 10375 } 10376 } else { 10377 if ((scanFlags & SCAN_MOVE) != 0) { 10378 // We haven't run dex-opt for this move (since we've moved the compiled output too) 10379 // but we already have this packages package info in the PackageSetting. We just 10380 // use that and derive the native library path based on the new codepath. 10381 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 10382 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 10383 } 10384 10385 // Set native library paths again. For moves, the path will be updated based on the 10386 // ABIs we've determined above. For non-moves, the path will be updated based on the 10387 // ABIs we determined during compilation, but the path will depend on the final 10388 // package path (after the rename away from the stage path). 10389 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10390 } 10391 10392 // This is a special case for the "system" package, where the ABI is 10393 // dictated by the zygote configuration (and init.rc). We should keep track 10394 // of this ABI so that we can deal with "normal" applications that run under 10395 // the same UID correctly. 10396 if (isPlatformPackage) { 10397 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 10398 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 10399 } 10400 10401 // If there's a mismatch between the abi-override in the package setting 10402 // and the abiOverride specified for the install. Warn about this because we 10403 // would've already compiled the app without taking the package setting into 10404 // account. 10405 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 10406 if (cpuAbiOverride == null && pkg.packageName != null) { 10407 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 10408 " for package " + pkg.packageName); 10409 } 10410 } 10411 10412 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10413 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10414 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 10415 10416 // Copy the derived override back to the parsed package, so that we can 10417 // update the package settings accordingly. 10418 pkg.cpuAbiOverride = cpuAbiOverride; 10419 10420 if (DEBUG_ABI_SELECTION) { 10421 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName 10422 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 10423 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 10424 } 10425 10426 // Push the derived path down into PackageSettings so we know what to 10427 // clean up at uninstall time. 10428 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 10429 10430 if (DEBUG_ABI_SELECTION) { 10431 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 10432 " primary=" + pkg.applicationInfo.primaryCpuAbi + 10433 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 10434 } 10435 10436 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 10437 // We don't do this here during boot because we can do it all 10438 // at once after scanning all existing packages. 10439 // 10440 // We also do this *before* we perform dexopt on this package, so that 10441 // we can avoid redundant dexopts, and also to make sure we've got the 10442 // code and package path correct. 10443 changedAbiCodePath = 10444 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 10445 } 10446 10447 if (isUnderFactoryTest && pkg.requestedPermissions.contains( 10448 android.Manifest.permission.FACTORY_TEST)) { 10449 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 10450 } 10451 10452 if (isSystemApp(pkg)) { 10453 pkgSetting.isOrphaned = true; 10454 } 10455 10456 // Take care of first install / last update times. 10457 final long scanFileTime = getLastModifiedTime(pkg); 10458 if (currentTime != 0) { 10459 if (pkgSetting.firstInstallTime == 0) { 10460 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 10461 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 10462 pkgSetting.lastUpdateTime = currentTime; 10463 } 10464 } else if (pkgSetting.firstInstallTime == 0) { 10465 // We need *something*. Take time time stamp of the file. 10466 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 10467 } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 10468 if (scanFileTime != pkgSetting.timeStamp) { 10469 // A package on the system image has changed; consider this 10470 // to be an update. 10471 pkgSetting.lastUpdateTime = scanFileTime; 10472 } 10473 } 10474 pkgSetting.setTimeStamp(scanFileTime); 10475 10476 pkgSetting.pkg = pkg; 10477 pkgSetting.pkgFlags = pkg.applicationInfo.flags; 10478 if (pkg.getLongVersionCode() != pkgSetting.versionCode) { 10479 pkgSetting.versionCode = pkg.getLongVersionCode(); 10480 } 10481 // Update volume if needed 10482 final String volumeUuid = pkg.applicationInfo.volumeUuid; 10483 if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) { 10484 Slog.i(PackageManagerService.TAG, 10485 "Update" + (pkgSetting.isSystem() ? " system" : "") 10486 + " package " + pkg.packageName 10487 + " volume from " + pkgSetting.volumeUuid 10488 + " to " + volumeUuid); 10489 pkgSetting.volumeUuid = volumeUuid; 10490 } 10491 10492 return new ScanResult(true, pkgSetting, changedAbiCodePath); 10493 } 10494 10495 /** 10496 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 10497 */ 10498 private static boolean apkHasCode(String fileName) { 10499 StrictJarFile jarFile = null; 10500 try { 10501 jarFile = new StrictJarFile(fileName, 10502 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 10503 return jarFile.findEntry("classes.dex") != null; 10504 } catch (IOException ignore) { 10505 } finally { 10506 try { 10507 if (jarFile != null) { 10508 jarFile.close(); 10509 } 10510 } catch (IOException ignore) {} 10511 } 10512 return false; 10513 } 10514 10515 /** 10516 * Enforces code policy for the package. This ensures that if an APK has 10517 * declared hasCode="true" in its manifest that the APK actually contains 10518 * code. 10519 * 10520 * @throws PackageManagerException If bytecode could not be found when it should exist 10521 */ 10522 private static void assertCodePolicy(PackageParser.Package pkg) 10523 throws PackageManagerException { 10524 final boolean shouldHaveCode = 10525 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 10526 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 10527 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10528 "Package " + pkg.baseCodePath + " code is missing"); 10529 } 10530 10531 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 10532 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 10533 final boolean splitShouldHaveCode = 10534 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 10535 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 10536 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10537 "Package " + pkg.splitCodePaths[i] + " code is missing"); 10538 } 10539 } 10540 } 10541 } 10542 10543 /** 10544 * Applies policy to the parsed package based upon the given policy flags. 10545 * Ensures the package is in a good state. 10546 * <p> 10547 * Implementation detail: This method must NOT have any side effect. It would 10548 * ideally be static, but, it requires locks to read system state. 10549 */ 10550 private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10551 final @ScanFlags int scanFlags) { 10552 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 10553 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 10554 if (pkg.applicationInfo.isDirectBootAware()) { 10555 // we're direct boot aware; set for all components 10556 for (PackageParser.Service s : pkg.services) { 10557 s.info.encryptionAware = s.info.directBootAware = true; 10558 } 10559 for (PackageParser.Provider p : pkg.providers) { 10560 p.info.encryptionAware = p.info.directBootAware = true; 10561 } 10562 for (PackageParser.Activity a : pkg.activities) { 10563 a.info.encryptionAware = a.info.directBootAware = true; 10564 } 10565 for (PackageParser.Activity r : pkg.receivers) { 10566 r.info.encryptionAware = r.info.directBootAware = true; 10567 } 10568 } 10569 if (compressedFileExists(pkg.codePath)) { 10570 pkg.isStub = true; 10571 } 10572 } else { 10573 // non system apps can't be flagged as core 10574 pkg.coreApp = false; 10575 // clear flags not applicable to regular apps 10576 pkg.applicationInfo.flags &= 10577 ~ApplicationInfo.FLAG_PERSISTENT; 10578 pkg.applicationInfo.privateFlags &= 10579 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10580 pkg.applicationInfo.privateFlags &= 10581 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10582 // clear protected broadcasts 10583 pkg.protectedBroadcasts = null; 10584 // cap permission priorities 10585 if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) { 10586 for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) { 10587 pkg.permissionGroups.get(i).info.priority = 0; 10588 } 10589 } 10590 } 10591 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10592 // ignore export request for single user receivers 10593 if (pkg.receivers != null) { 10594 for (int i = pkg.receivers.size() - 1; i >= 0; --i) { 10595 final PackageParser.Activity receiver = pkg.receivers.get(i); 10596 if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 10597 receiver.info.exported = false; 10598 } 10599 } 10600 } 10601 // ignore export request for single user services 10602 if (pkg.services != null) { 10603 for (int i = pkg.services.size() - 1; i >= 0; --i) { 10604 final PackageParser.Service service = pkg.services.get(i); 10605 if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 10606 service.info.exported = false; 10607 } 10608 } 10609 } 10610 // ignore export request for single user providers 10611 if (pkg.providers != null) { 10612 for (int i = pkg.providers.size() - 1; i >= 0; --i) { 10613 final PackageParser.Provider provider = pkg.providers.get(i); 10614 if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) { 10615 provider.info.exported = false; 10616 } 10617 } 10618 } 10619 } 10620 pkg.mTrustedOverlay = (scanFlags & SCAN_TRUSTED_OVERLAY) != 0; 10621 10622 if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) { 10623 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10624 } 10625 10626 if ((scanFlags & SCAN_AS_OEM) != 0) { 10627 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 10628 } 10629 10630 if ((scanFlags & SCAN_AS_VENDOR) != 0) { 10631 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR; 10632 } 10633 10634 if (!isSystemApp(pkg)) { 10635 // Only system apps can use these features. 10636 pkg.mOriginalPackages = null; 10637 pkg.mRealPackage = null; 10638 pkg.mAdoptPermissions = null; 10639 } 10640 } 10641 10642 /** 10643 * Asserts the parsed package is valid according to the given policy. If the 10644 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10645 * <p> 10646 * Implementation detail: This method must NOT have any side effects. It would 10647 * ideally be static, but, it requires locks to read system state. 10648 * 10649 * @throws PackageManagerException If the package fails any of the validation checks 10650 */ 10651 private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10652 final @ScanFlags int scanFlags) 10653 throws PackageManagerException { 10654 if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10655 assertCodePolicy(pkg); 10656 } 10657 10658 if (pkg.applicationInfo.getCodePath() == null || 10659 pkg.applicationInfo.getResourcePath() == null) { 10660 // Bail out. The resource and code paths haven't been set. 10661 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10662 "Code and resource paths haven't been set correctly"); 10663 } 10664 10665 // Make sure we're not adding any bogus keyset info 10666 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10667 ksms.assertScannedPackageValid(pkg); 10668 10669 synchronized (mPackages) { 10670 // The special "android" package can only be defined once 10671 if (pkg.packageName.equals("android")) { 10672 if (mAndroidApplication != null) { 10673 Slog.w(TAG, "*************************************************"); 10674 Slog.w(TAG, "Core android package being redefined. Skipping."); 10675 Slog.w(TAG, " codePath=" + pkg.codePath); 10676 Slog.w(TAG, "*************************************************"); 10677 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10678 "Core android package being redefined. Skipping."); 10679 } 10680 } 10681 10682 // A package name must be unique; don't allow duplicates 10683 if (mPackages.containsKey(pkg.packageName)) { 10684 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10685 "Application package " + pkg.packageName 10686 + " already installed. Skipping duplicate."); 10687 } 10688 10689 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10690 // Static libs have a synthetic package name containing the version 10691 // but we still want the base name to be unique. 10692 if (mPackages.containsKey(pkg.manifestPackageName)) { 10693 throw new PackageManagerException( 10694 "Duplicate static shared lib provider package"); 10695 } 10696 10697 // Static shared libraries should have at least O target SDK 10698 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10699 throw new PackageManagerException( 10700 "Packages declaring static-shared libs must target O SDK or higher"); 10701 } 10702 10703 // Package declaring static a shared lib cannot be instant apps 10704 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10705 throw new PackageManagerException( 10706 "Packages declaring static-shared libs cannot be instant apps"); 10707 } 10708 10709 // Package declaring static a shared lib cannot be renamed since the package 10710 // name is synthetic and apps can't code around package manager internals. 10711 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10712 throw new PackageManagerException( 10713 "Packages declaring static-shared libs cannot be renamed"); 10714 } 10715 10716 // Package declaring static a shared lib cannot declare child packages 10717 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10718 throw new PackageManagerException( 10719 "Packages declaring static-shared libs cannot have child packages"); 10720 } 10721 10722 // Package declaring static a shared lib cannot declare dynamic libs 10723 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10724 throw new PackageManagerException( 10725 "Packages declaring static-shared libs cannot declare dynamic libs"); 10726 } 10727 10728 // Package declaring static a shared lib cannot declare shared users 10729 if (pkg.mSharedUserId != null) { 10730 throw new PackageManagerException( 10731 "Packages declaring static-shared libs cannot declare shared users"); 10732 } 10733 10734 // Static shared libs cannot declare activities 10735 if (!pkg.activities.isEmpty()) { 10736 throw new PackageManagerException( 10737 "Static shared libs cannot declare activities"); 10738 } 10739 10740 // Static shared libs cannot declare services 10741 if (!pkg.services.isEmpty()) { 10742 throw new PackageManagerException( 10743 "Static shared libs cannot declare services"); 10744 } 10745 10746 // Static shared libs cannot declare providers 10747 if (!pkg.providers.isEmpty()) { 10748 throw new PackageManagerException( 10749 "Static shared libs cannot declare content providers"); 10750 } 10751 10752 // Static shared libs cannot declare receivers 10753 if (!pkg.receivers.isEmpty()) { 10754 throw new PackageManagerException( 10755 "Static shared libs cannot declare broadcast receivers"); 10756 } 10757 10758 // Static shared libs cannot declare permission groups 10759 if (!pkg.permissionGroups.isEmpty()) { 10760 throw new PackageManagerException( 10761 "Static shared libs cannot declare permission groups"); 10762 } 10763 10764 // Static shared libs cannot declare permissions 10765 if (!pkg.permissions.isEmpty()) { 10766 throw new PackageManagerException( 10767 "Static shared libs cannot declare permissions"); 10768 } 10769 10770 // Static shared libs cannot declare protected broadcasts 10771 if (pkg.protectedBroadcasts != null) { 10772 throw new PackageManagerException( 10773 "Static shared libs cannot declare protected broadcasts"); 10774 } 10775 10776 // Static shared libs cannot be overlay targets 10777 if (pkg.mOverlayTarget != null) { 10778 throw new PackageManagerException( 10779 "Static shared libs cannot be overlay targets"); 10780 } 10781 10782 // The version codes must be ordered as lib versions 10783 long minVersionCode = Long.MIN_VALUE; 10784 long maxVersionCode = Long.MAX_VALUE; 10785 10786 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10787 pkg.staticSharedLibName); 10788 if (versionedLib != null) { 10789 final int versionCount = versionedLib.size(); 10790 for (int i = 0; i < versionCount; i++) { 10791 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10792 final long libVersionCode = libInfo.getDeclaringPackage() 10793 .getLongVersionCode(); 10794 if (libInfo.getLongVersion() < pkg.staticSharedLibVersion) { 10795 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10796 } else if (libInfo.getLongVersion() > pkg.staticSharedLibVersion) { 10797 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10798 } else { 10799 minVersionCode = maxVersionCode = libVersionCode; 10800 break; 10801 } 10802 } 10803 } 10804 if (pkg.getLongVersionCode() < minVersionCode 10805 || pkg.getLongVersionCode() > maxVersionCode) { 10806 throw new PackageManagerException("Static shared" 10807 + " lib version codes must be ordered as lib versions"); 10808 } 10809 } 10810 10811 // Only privileged apps and updated privileged apps can add child packages. 10812 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10813 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10814 throw new PackageManagerException("Only privileged apps can add child " 10815 + "packages. Ignoring package " + pkg.packageName); 10816 } 10817 final int childCount = pkg.childPackages.size(); 10818 for (int i = 0; i < childCount; i++) { 10819 PackageParser.Package childPkg = pkg.childPackages.get(i); 10820 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10821 childPkg.packageName)) { 10822 throw new PackageManagerException("Can't override child of " 10823 + "another disabled app. Ignoring package " + pkg.packageName); 10824 } 10825 } 10826 } 10827 10828 // If we're only installing presumed-existing packages, require that the 10829 // scanned APK is both already known and at the path previously established 10830 // for it. Previously unknown packages we pick up normally, but if we have an 10831 // a priori expectation about this package's install presence, enforce it. 10832 // With a singular exception for new system packages. When an OTA contains 10833 // a new system package, we allow the codepath to change from a system location 10834 // to the user-installed location. If we don't allow this change, any newer, 10835 // user-installed version of the application will be ignored. 10836 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10837 if (mExpectingBetter.containsKey(pkg.packageName)) { 10838 logCriticalInfo(Log.WARN, 10839 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10840 } else { 10841 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10842 if (known != null) { 10843 if (DEBUG_PACKAGE_SCANNING) { 10844 Log.d(TAG, "Examining " + pkg.codePath 10845 + " and requiring known paths " + known.codePathString 10846 + " & " + known.resourcePathString); 10847 } 10848 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10849 || !pkg.applicationInfo.getResourcePath().equals( 10850 known.resourcePathString)) { 10851 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10852 "Application package " + pkg.packageName 10853 + " found at " + pkg.applicationInfo.getCodePath() 10854 + " but expected at " + known.codePathString 10855 + "; ignoring."); 10856 } 10857 } else { 10858 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10859 "Application package " + pkg.packageName 10860 + " not found; ignoring."); 10861 } 10862 } 10863 } 10864 10865 // Verify that this new package doesn't have any content providers 10866 // that conflict with existing packages. Only do this if the 10867 // package isn't already installed, since we don't want to break 10868 // things that are installed. 10869 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 10870 final int N = pkg.providers.size(); 10871 int i; 10872 for (i=0; i<N; i++) { 10873 PackageParser.Provider p = pkg.providers.get(i); 10874 if (p.info.authority != null) { 10875 String names[] = p.info.authority.split(";"); 10876 for (int j = 0; j < names.length; j++) { 10877 if (mProvidersByAuthority.containsKey(names[j])) { 10878 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10879 final String otherPackageName = 10880 ((other != null && other.getComponentName() != null) ? 10881 other.getComponentName().getPackageName() : "?"); 10882 throw new PackageManagerException( 10883 INSTALL_FAILED_CONFLICTING_PROVIDER, 10884 "Can't install because provider name " + names[j] 10885 + " (in package " + pkg.applicationInfo.packageName 10886 + ") is already used by " + otherPackageName); 10887 } 10888 } 10889 } 10890 } 10891 } 10892 10893 // Verify that packages sharing a user with a privileged app are marked as privileged. 10894 if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) { 10895 SharedUserSetting sharedUserSetting = null; 10896 try { 10897 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 10898 } catch (PackageManagerException ignore) {} 10899 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 10900 // Exempt SharedUsers signed with the platform key. 10901 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 10902 if ((platformPkgSetting.signatures.mSigningDetails 10903 != PackageParser.SigningDetails.UNKNOWN) 10904 && (compareSignatures( 10905 platformPkgSetting.signatures.mSigningDetails.signatures, 10906 pkg.mSigningDetails.signatures) 10907 != PackageManager.SIGNATURE_MATCH)) { 10908 throw new PackageManagerException("Apps that share a user with a " + 10909 "privileged app must themselves be marked as privileged. " + 10910 pkg.packageName + " shares privileged user " + 10911 pkg.mSharedUserId + "."); 10912 } 10913 } 10914 } 10915 } 10916 } 10917 10918 private boolean addSharedLibraryLPw(String path, String apk, String name, long version, 10919 int type, String declaringPackageName, long declaringVersionCode) { 10920 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10921 if (versionedLib == null) { 10922 versionedLib = new LongSparseArray<>(); 10923 mSharedLibraries.put(name, versionedLib); 10924 if (type == SharedLibraryInfo.TYPE_STATIC) { 10925 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 10926 } 10927 } else if (versionedLib.indexOfKey(version) >= 0) { 10928 return false; 10929 } 10930 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 10931 version, type, declaringPackageName, declaringVersionCode); 10932 versionedLib.put(version, libEntry); 10933 return true; 10934 } 10935 10936 private boolean removeSharedLibraryLPw(String name, long version) { 10937 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10938 if (versionedLib == null) { 10939 return false; 10940 } 10941 final int libIdx = versionedLib.indexOfKey(version); 10942 if (libIdx < 0) { 10943 return false; 10944 } 10945 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 10946 versionedLib.remove(version); 10947 if (versionedLib.size() <= 0) { 10948 mSharedLibraries.remove(name); 10949 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 10950 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 10951 .getPackageName()); 10952 } 10953 } 10954 return true; 10955 } 10956 10957 /** 10958 * Adds a scanned package to the system. When this method is finished, the package will 10959 * be available for query, resolution, etc... 10960 */ 10961 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 10962 UserHandle user, final @ScanFlags int scanFlags, boolean chatty) { 10963 final String pkgName = pkg.packageName; 10964 if (mCustomResolverComponentName != null && 10965 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 10966 setUpCustomResolverActivity(pkg); 10967 } 10968 10969 if (pkg.packageName.equals("android")) { 10970 synchronized (mPackages) { 10971 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10972 // Set up information for our fall-back user intent resolution activity. 10973 mPlatformPackage = pkg; 10974 pkg.mVersionCode = mSdkVersion; 10975 pkg.mVersionCodeMajor = 0; 10976 mAndroidApplication = pkg.applicationInfo; 10977 if (!mResolverReplaced) { 10978 mResolveActivity.applicationInfo = mAndroidApplication; 10979 mResolveActivity.name = ResolverActivity.class.getName(); 10980 mResolveActivity.packageName = mAndroidApplication.packageName; 10981 mResolveActivity.processName = "system:ui"; 10982 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10983 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 10984 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 10985 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 10986 mResolveActivity.exported = true; 10987 mResolveActivity.enabled = true; 10988 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 10989 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 10990 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 10991 | ActivityInfo.CONFIG_SCREEN_LAYOUT 10992 | ActivityInfo.CONFIG_ORIENTATION 10993 | ActivityInfo.CONFIG_KEYBOARD 10994 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 10995 mResolveInfo.activityInfo = mResolveActivity; 10996 mResolveInfo.priority = 0; 10997 mResolveInfo.preferredOrder = 0; 10998 mResolveInfo.match = 0; 10999 mResolveComponentName = new ComponentName( 11000 mAndroidApplication.packageName, mResolveActivity.name); 11001 } 11002 } 11003 } 11004 } 11005 11006 ArrayList<PackageParser.Package> clientLibPkgs = null; 11007 // writer 11008 synchronized (mPackages) { 11009 boolean hasStaticSharedLibs = false; 11010 11011 // Any app can add new static shared libraries 11012 if (pkg.staticSharedLibName != null) { 11013 // Static shared libs don't allow renaming as they have synthetic package 11014 // names to allow install of multiple versions, so use name from manifest. 11015 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 11016 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 11017 pkg.manifestPackageName, pkg.getLongVersionCode())) { 11018 hasStaticSharedLibs = true; 11019 } else { 11020 Slog.w(TAG, "Package " + pkg.packageName + " library " 11021 + pkg.staticSharedLibName + " already exists; skipping"); 11022 } 11023 // Static shared libs cannot be updated once installed since they 11024 // use synthetic package name which includes the version code, so 11025 // not need to update other packages's shared lib dependencies. 11026 } 11027 11028 if (!hasStaticSharedLibs 11029 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11030 // Only system apps can add new dynamic shared libraries. 11031 if (pkg.libraryNames != null) { 11032 for (int i = 0; i < pkg.libraryNames.size(); i++) { 11033 String name = pkg.libraryNames.get(i); 11034 boolean allowed = false; 11035 if (pkg.isUpdatedSystemApp()) { 11036 // New library entries can only be added through the 11037 // system image. This is important to get rid of a lot 11038 // of nasty edge cases: for example if we allowed a non- 11039 // system update of the app to add a library, then uninstalling 11040 // the update would make the library go away, and assumptions 11041 // we made such as through app install filtering would now 11042 // have allowed apps on the device which aren't compatible 11043 // with it. Better to just have the restriction here, be 11044 // conservative, and create many fewer cases that can negatively 11045 // impact the user experience. 11046 final PackageSetting sysPs = mSettings 11047 .getDisabledSystemPkgLPr(pkg.packageName); 11048 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 11049 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 11050 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 11051 allowed = true; 11052 break; 11053 } 11054 } 11055 } 11056 } else { 11057 allowed = true; 11058 } 11059 if (allowed) { 11060 if (!addSharedLibraryLPw(null, pkg.packageName, name, 11061 SharedLibraryInfo.VERSION_UNDEFINED, 11062 SharedLibraryInfo.TYPE_DYNAMIC, 11063 pkg.packageName, pkg.getLongVersionCode())) { 11064 Slog.w(TAG, "Package " + pkg.packageName + " library " 11065 + name + " already exists; skipping"); 11066 } 11067 } else { 11068 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 11069 + name + " that is not declared on system image; skipping"); 11070 } 11071 } 11072 11073 if ((scanFlags & SCAN_BOOTING) == 0) { 11074 // If we are not booting, we need to update any applications 11075 // that are clients of our shared library. If we are booting, 11076 // this will all be done once the scan is complete. 11077 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 11078 } 11079 } 11080 } 11081 } 11082 11083 if ((scanFlags & SCAN_BOOTING) != 0) { 11084 // No apps can run during boot scan, so they don't need to be frozen 11085 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 11086 // Caller asked to not kill app, so it's probably not frozen 11087 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 11088 // Caller asked us to ignore frozen check for some reason; they 11089 // probably didn't know the package name 11090 } else { 11091 // We're doing major surgery on this package, so it better be frozen 11092 // right now to keep it from launching 11093 checkPackageFrozen(pkgName); 11094 } 11095 11096 // Also need to kill any apps that are dependent on the library. 11097 if (clientLibPkgs != null) { 11098 for (int i=0; i<clientLibPkgs.size(); i++) { 11099 PackageParser.Package clientPkg = clientLibPkgs.get(i); 11100 killApplication(clientPkg.applicationInfo.packageName, 11101 clientPkg.applicationInfo.uid, "update lib"); 11102 } 11103 } 11104 11105 // writer 11106 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 11107 11108 synchronized (mPackages) { 11109 // We don't expect installation to fail beyond this point 11110 11111 // Add the new setting to mSettings 11112 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 11113 // Add the new setting to mPackages 11114 mPackages.put(pkg.applicationInfo.packageName, pkg); 11115 // Make sure we don't accidentally delete its data. 11116 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 11117 while (iter.hasNext()) { 11118 PackageCleanItem item = iter.next(); 11119 if (pkgName.equals(item.packageName)) { 11120 iter.remove(); 11121 } 11122 } 11123 11124 // Add the package's KeySets to the global KeySetManagerService 11125 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11126 ksms.addScannedPackageLPw(pkg); 11127 11128 int N = pkg.providers.size(); 11129 StringBuilder r = null; 11130 int i; 11131 for (i=0; i<N; i++) { 11132 PackageParser.Provider p = pkg.providers.get(i); 11133 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 11134 p.info.processName); 11135 mProviders.addProvider(p); 11136 p.syncable = p.info.isSyncable; 11137 if (p.info.authority != null) { 11138 String names[] = p.info.authority.split(";"); 11139 p.info.authority = null; 11140 for (int j = 0; j < names.length; j++) { 11141 if (j == 1 && p.syncable) { 11142 // We only want the first authority for a provider to possibly be 11143 // syncable, so if we already added this provider using a different 11144 // authority clear the syncable flag. We copy the provider before 11145 // changing it because the mProviders object contains a reference 11146 // to a provider that we don't want to change. 11147 // Only do this for the second authority since the resulting provider 11148 // object can be the same for all future authorities for this provider. 11149 p = new PackageParser.Provider(p); 11150 p.syncable = false; 11151 } 11152 if (!mProvidersByAuthority.containsKey(names[j])) { 11153 mProvidersByAuthority.put(names[j], p); 11154 if (p.info.authority == null) { 11155 p.info.authority = names[j]; 11156 } else { 11157 p.info.authority = p.info.authority + ";" + names[j]; 11158 } 11159 if (DEBUG_PACKAGE_SCANNING) { 11160 if (chatty) 11161 Log.d(TAG, "Registered content provider: " + names[j] 11162 + ", className = " + p.info.name + ", isSyncable = " 11163 + p.info.isSyncable); 11164 } 11165 } else { 11166 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11167 Slog.w(TAG, "Skipping provider name " + names[j] + 11168 " (in package " + pkg.applicationInfo.packageName + 11169 "): name already used by " 11170 + ((other != null && other.getComponentName() != null) 11171 ? other.getComponentName().getPackageName() : "?")); 11172 } 11173 } 11174 } 11175 if (chatty) { 11176 if (r == null) { 11177 r = new StringBuilder(256); 11178 } else { 11179 r.append(' '); 11180 } 11181 r.append(p.info.name); 11182 } 11183 } 11184 if (r != null) { 11185 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 11186 } 11187 11188 N = pkg.services.size(); 11189 r = null; 11190 for (i=0; i<N; i++) { 11191 PackageParser.Service s = pkg.services.get(i); 11192 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 11193 s.info.processName); 11194 mServices.addService(s); 11195 if (chatty) { 11196 if (r == null) { 11197 r = new StringBuilder(256); 11198 } else { 11199 r.append(' '); 11200 } 11201 r.append(s.info.name); 11202 } 11203 } 11204 if (r != null) { 11205 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 11206 } 11207 11208 N = pkg.receivers.size(); 11209 r = null; 11210 for (i=0; i<N; i++) { 11211 PackageParser.Activity a = pkg.receivers.get(i); 11212 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11213 a.info.processName); 11214 mReceivers.addActivity(a, "receiver"); 11215 if (chatty) { 11216 if (r == null) { 11217 r = new StringBuilder(256); 11218 } else { 11219 r.append(' '); 11220 } 11221 r.append(a.info.name); 11222 } 11223 } 11224 if (r != null) { 11225 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 11226 } 11227 11228 N = pkg.activities.size(); 11229 r = null; 11230 for (i=0; i<N; i++) { 11231 PackageParser.Activity a = pkg.activities.get(i); 11232 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11233 a.info.processName); 11234 mActivities.addActivity(a, "activity"); 11235 if (chatty) { 11236 if (r == null) { 11237 r = new StringBuilder(256); 11238 } else { 11239 r.append(' '); 11240 } 11241 r.append(a.info.name); 11242 } 11243 } 11244 if (r != null) { 11245 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11246 } 11247 11248 // Don't allow ephemeral applications to define new permissions groups. 11249 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11250 Slog.w(TAG, "Permission groups from package " + pkg.packageName 11251 + " ignored: instant apps cannot define new permission groups."); 11252 } else { 11253 mPermissionManager.addAllPermissionGroups(pkg, chatty); 11254 } 11255 11256 // Don't allow ephemeral applications to define new permissions. 11257 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11258 Slog.w(TAG, "Permissions from package " + pkg.packageName 11259 + " ignored: instant apps cannot define new permissions."); 11260 } else { 11261 mPermissionManager.addAllPermissions(pkg, chatty); 11262 } 11263 11264 N = pkg.instrumentation.size(); 11265 r = null; 11266 for (i=0; i<N; i++) { 11267 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11268 a.info.packageName = pkg.applicationInfo.packageName; 11269 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11270 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11271 a.info.splitNames = pkg.splitNames; 11272 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11273 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11274 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11275 a.info.dataDir = pkg.applicationInfo.dataDir; 11276 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11277 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11278 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11279 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11280 mInstrumentation.put(a.getComponentName(), a); 11281 if (chatty) { 11282 if (r == null) { 11283 r = new StringBuilder(256); 11284 } else { 11285 r.append(' '); 11286 } 11287 r.append(a.info.name); 11288 } 11289 } 11290 if (r != null) { 11291 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11292 } 11293 11294 if (pkg.protectedBroadcasts != null) { 11295 N = pkg.protectedBroadcasts.size(); 11296 synchronized (mProtectedBroadcasts) { 11297 for (i = 0; i < N; i++) { 11298 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 11299 } 11300 } 11301 } 11302 } 11303 11304 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11305 } 11306 11307 /** 11308 * Derive the ABI of a non-system package located at {@code scanFile}. This information 11309 * is derived purely on the basis of the contents of {@code scanFile} and 11310 * {@code cpuAbiOverride}. 11311 * 11312 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 11313 */ 11314 private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride, 11315 boolean extractLibs) 11316 throws PackageManagerException { 11317 // Give ourselves some initial paths; we'll come back for another 11318 // pass once we've determined ABI below. 11319 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11320 11321 // We would never need to extract libs for forward-locked and external packages, 11322 // since the container service will do it for us. We shouldn't attempt to 11323 // extract libs from system app when it was not updated. 11324 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 11325 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 11326 extractLibs = false; 11327 } 11328 11329 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 11330 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 11331 11332 NativeLibraryHelper.Handle handle = null; 11333 try { 11334 handle = NativeLibraryHelper.Handle.create(pkg); 11335 // TODO(multiArch): This can be null for apps that didn't go through the 11336 // usual installation process. We can calculate it again, like we 11337 // do during install time. 11338 // 11339 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 11340 // unnecessary. 11341 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 11342 11343 // Null out the abis so that they can be recalculated. 11344 pkg.applicationInfo.primaryCpuAbi = null; 11345 pkg.applicationInfo.secondaryCpuAbi = null; 11346 if (isMultiArch(pkg.applicationInfo)) { 11347 // Warn if we've set an abiOverride for multi-lib packages.. 11348 // By definition, we need to copy both 32 and 64 bit libraries for 11349 // such packages. 11350 if (pkg.cpuAbiOverride != null 11351 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 11352 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 11353 } 11354 11355 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 11356 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 11357 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 11358 if (extractLibs) { 11359 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11360 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11361 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 11362 useIsaSpecificSubdirs); 11363 } else { 11364 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11365 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 11366 } 11367 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11368 } 11369 11370 // Shared library native code should be in the APK zip aligned 11371 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 11372 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11373 "Shared library native lib extraction not supported"); 11374 } 11375 11376 maybeThrowExceptionForMultiArchCopy( 11377 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 11378 11379 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 11380 if (extractLibs) { 11381 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11382 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11383 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 11384 useIsaSpecificSubdirs); 11385 } else { 11386 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11387 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 11388 } 11389 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11390 } 11391 11392 maybeThrowExceptionForMultiArchCopy( 11393 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 11394 11395 if (abi64 >= 0) { 11396 // Shared library native libs should be in the APK zip aligned 11397 if (extractLibs && pkg.isLibrary()) { 11398 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11399 "Shared library native lib extraction not supported"); 11400 } 11401 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11402 } 11403 11404 if (abi32 >= 0) { 11405 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11406 if (abi64 >= 0) { 11407 if (pkg.use32bitAbi) { 11408 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11409 pkg.applicationInfo.primaryCpuAbi = abi; 11410 } else { 11411 pkg.applicationInfo.secondaryCpuAbi = abi; 11412 } 11413 } else { 11414 pkg.applicationInfo.primaryCpuAbi = abi; 11415 } 11416 } 11417 } else { 11418 String[] abiList = (cpuAbiOverride != null) ? 11419 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11420 11421 // Enable gross and lame hacks for apps that are built with old 11422 // SDK tools. We must scan their APKs for renderscript bitcode and 11423 // not launch them if it's present. Don't bother checking on devices 11424 // that don't have 64 bit support. 11425 boolean needsRenderScriptOverride = false; 11426 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11427 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11428 abiList = Build.SUPPORTED_32_BIT_ABIS; 11429 needsRenderScriptOverride = true; 11430 } 11431 11432 final int copyRet; 11433 if (extractLibs) { 11434 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11435 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11436 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11437 } else { 11438 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11439 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11440 } 11441 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11442 11443 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11444 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11445 "Error unpackaging native libs for app, errorCode=" + copyRet); 11446 } 11447 11448 if (copyRet >= 0) { 11449 // Shared libraries that have native libs must be multi-architecture 11450 if (pkg.isLibrary()) { 11451 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11452 "Shared library with native libs must be multiarch"); 11453 } 11454 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11455 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11456 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11457 } else if (needsRenderScriptOverride) { 11458 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11459 } 11460 } 11461 } catch (IOException ioe) { 11462 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11463 } finally { 11464 IoUtils.closeQuietly(handle); 11465 } 11466 11467 // Now that we've calculated the ABIs and determined if it's an internal app, 11468 // we will go ahead and populate the nativeLibraryPath. 11469 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11470 } 11471 11472 /** 11473 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11474 * i.e, so that all packages can be run inside a single process if required. 11475 * 11476 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11477 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11478 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11479 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11480 * updating a package that belongs to a shared user. 11481 * 11482 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11483 * adds unnecessary complexity. 11484 */ 11485 private static @Nullable List<String> adjustCpuAbisForSharedUserLPw( 11486 Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) { 11487 List<String> changedAbiCodePath = null; 11488 String requiredInstructionSet = null; 11489 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11490 requiredInstructionSet = VMRuntime.getInstructionSet( 11491 scannedPackage.applicationInfo.primaryCpuAbi); 11492 } 11493 11494 PackageSetting requirer = null; 11495 for (PackageSetting ps : packagesForUser) { 11496 // If packagesForUser contains scannedPackage, we skip it. This will happen 11497 // when scannedPackage is an update of an existing package. Without this check, 11498 // we will never be able to change the ABI of any package belonging to a shared 11499 // user, even if it's compatible with other packages. 11500 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11501 if (ps.primaryCpuAbiString == null) { 11502 continue; 11503 } 11504 11505 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11506 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11507 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11508 // this but there's not much we can do. 11509 String errorMessage = "Instruction set mismatch, " 11510 + ((requirer == null) ? "[caller]" : requirer) 11511 + " requires " + requiredInstructionSet + " whereas " + ps 11512 + " requires " + instructionSet; 11513 Slog.w(TAG, errorMessage); 11514 } 11515 11516 if (requiredInstructionSet == null) { 11517 requiredInstructionSet = instructionSet; 11518 requirer = ps; 11519 } 11520 } 11521 } 11522 11523 if (requiredInstructionSet != null) { 11524 String adjustedAbi; 11525 if (requirer != null) { 11526 // requirer != null implies that either scannedPackage was null or that scannedPackage 11527 // did not require an ABI, in which case we have to adjust scannedPackage to match 11528 // the ABI of the set (which is the same as requirer's ABI) 11529 adjustedAbi = requirer.primaryCpuAbiString; 11530 if (scannedPackage != null) { 11531 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11532 } 11533 } else { 11534 // requirer == null implies that we're updating all ABIs in the set to 11535 // match scannedPackage. 11536 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11537 } 11538 11539 for (PackageSetting ps : packagesForUser) { 11540 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11541 if (ps.primaryCpuAbiString != null) { 11542 continue; 11543 } 11544 11545 ps.primaryCpuAbiString = adjustedAbi; 11546 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11547 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11548 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11549 if (DEBUG_ABI_SELECTION) { 11550 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11551 + " (requirer=" 11552 + (requirer != null ? requirer.pkg : "null") 11553 + ", scannedPackage=" 11554 + (scannedPackage != null ? scannedPackage : "null") 11555 + ")"); 11556 } 11557 if (changedAbiCodePath == null) { 11558 changedAbiCodePath = new ArrayList<>(); 11559 } 11560 changedAbiCodePath.add(ps.codePathString); 11561 } 11562 } 11563 } 11564 } 11565 return changedAbiCodePath; 11566 } 11567 11568 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11569 synchronized (mPackages) { 11570 mResolverReplaced = true; 11571 // Set up information for custom user intent resolution activity. 11572 mResolveActivity.applicationInfo = pkg.applicationInfo; 11573 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11574 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11575 mResolveActivity.processName = pkg.applicationInfo.packageName; 11576 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11577 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11578 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11579 mResolveActivity.theme = 0; 11580 mResolveActivity.exported = true; 11581 mResolveActivity.enabled = true; 11582 mResolveInfo.activityInfo = mResolveActivity; 11583 mResolveInfo.priority = 0; 11584 mResolveInfo.preferredOrder = 0; 11585 mResolveInfo.match = 0; 11586 mResolveComponentName = mCustomResolverComponentName; 11587 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11588 mResolveComponentName); 11589 } 11590 } 11591 11592 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11593 if (installerActivity == null) { 11594 if (DEBUG_EPHEMERAL) { 11595 Slog.d(TAG, "Clear ephemeral installer activity"); 11596 } 11597 mInstantAppInstallerActivity = null; 11598 return; 11599 } 11600 11601 if (DEBUG_EPHEMERAL) { 11602 Slog.d(TAG, "Set ephemeral installer activity: " 11603 + installerActivity.getComponentName()); 11604 } 11605 // Set up information for ephemeral installer activity 11606 mInstantAppInstallerActivity = installerActivity; 11607 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11608 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11609 mInstantAppInstallerActivity.exported = true; 11610 mInstantAppInstallerActivity.enabled = true; 11611 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11612 mInstantAppInstallerInfo.priority = 0; 11613 mInstantAppInstallerInfo.preferredOrder = 1; 11614 mInstantAppInstallerInfo.isDefault = true; 11615 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11616 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11617 } 11618 11619 private static String calculateBundledApkRoot(final String codePathString) { 11620 final File codePath = new File(codePathString); 11621 final File codeRoot; 11622 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11623 codeRoot = Environment.getRootDirectory(); 11624 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11625 codeRoot = Environment.getOemDirectory(); 11626 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11627 codeRoot = Environment.getVendorDirectory(); 11628 } else { 11629 // Unrecognized code path; take its top real segment as the apk root: 11630 // e.g. /something/app/blah.apk => /something 11631 try { 11632 File f = codePath.getCanonicalFile(); 11633 File parent = f.getParentFile(); // non-null because codePath is a file 11634 File tmp; 11635 while ((tmp = parent.getParentFile()) != null) { 11636 f = parent; 11637 parent = tmp; 11638 } 11639 codeRoot = f; 11640 Slog.w(TAG, "Unrecognized code path " 11641 + codePath + " - using " + codeRoot); 11642 } catch (IOException e) { 11643 // Can't canonicalize the code path -- shenanigans? 11644 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11645 return Environment.getRootDirectory().getPath(); 11646 } 11647 } 11648 return codeRoot.getPath(); 11649 } 11650 11651 /** 11652 * Derive and set the location of native libraries for the given package, 11653 * which varies depending on where and how the package was installed. 11654 */ 11655 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11656 final ApplicationInfo info = pkg.applicationInfo; 11657 final String codePath = pkg.codePath; 11658 final File codeFile = new File(codePath); 11659 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11660 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11661 11662 info.nativeLibraryRootDir = null; 11663 info.nativeLibraryRootRequiresIsa = false; 11664 info.nativeLibraryDir = null; 11665 info.secondaryNativeLibraryDir = null; 11666 11667 if (isApkFile(codeFile)) { 11668 // Monolithic install 11669 if (bundledApp) { 11670 // If "/system/lib64/apkname" exists, assume that is the per-package 11671 // native library directory to use; otherwise use "/system/lib/apkname". 11672 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11673 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11674 getPrimaryInstructionSet(info)); 11675 11676 // This is a bundled system app so choose the path based on the ABI. 11677 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11678 // is just the default path. 11679 final String apkName = deriveCodePathName(codePath); 11680 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11681 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11682 apkName).getAbsolutePath(); 11683 11684 if (info.secondaryCpuAbi != null) { 11685 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11686 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11687 secondaryLibDir, apkName).getAbsolutePath(); 11688 } 11689 } else if (asecApp) { 11690 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11691 .getAbsolutePath(); 11692 } else { 11693 final String apkName = deriveCodePathName(codePath); 11694 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11695 .getAbsolutePath(); 11696 } 11697 11698 info.nativeLibraryRootRequiresIsa = false; 11699 info.nativeLibraryDir = info.nativeLibraryRootDir; 11700 } else { 11701 // Cluster install 11702 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11703 info.nativeLibraryRootRequiresIsa = true; 11704 11705 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11706 getPrimaryInstructionSet(info)).getAbsolutePath(); 11707 11708 if (info.secondaryCpuAbi != null) { 11709 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11710 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11711 } 11712 } 11713 } 11714 11715 /** 11716 * Calculate the abis and roots for a bundled app. These can uniquely 11717 * be determined from the contents of the system partition, i.e whether 11718 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11719 * of this information, and instead assume that the system was built 11720 * sensibly. 11721 */ 11722 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11723 PackageSetting pkgSetting) { 11724 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11725 11726 // If "/system/lib64/apkname" exists, assume that is the per-package 11727 // native library directory to use; otherwise use "/system/lib/apkname". 11728 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11729 setBundledAppAbi(pkg, apkRoot, apkName); 11730 // pkgSetting might be null during rescan following uninstall of updates 11731 // to a bundled app, so accommodate that possibility. The settings in 11732 // that case will be established later from the parsed package. 11733 // 11734 // If the settings aren't null, sync them up with what we've just derived. 11735 // note that apkRoot isn't stored in the package settings. 11736 if (pkgSetting != null) { 11737 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11738 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11739 } 11740 } 11741 11742 /** 11743 * Deduces the ABI of a bundled app and sets the relevant fields on the 11744 * parsed pkg object. 11745 * 11746 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11747 * under which system libraries are installed. 11748 * @param apkName the name of the installed package. 11749 */ 11750 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11751 final File codeFile = new File(pkg.codePath); 11752 11753 final boolean has64BitLibs; 11754 final boolean has32BitLibs; 11755 if (isApkFile(codeFile)) { 11756 // Monolithic install 11757 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11758 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11759 } else { 11760 // Cluster install 11761 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11762 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11763 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11764 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11765 has64BitLibs = (new File(rootDir, isa)).exists(); 11766 } else { 11767 has64BitLibs = false; 11768 } 11769 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11770 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11771 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11772 has32BitLibs = (new File(rootDir, isa)).exists(); 11773 } else { 11774 has32BitLibs = false; 11775 } 11776 } 11777 11778 if (has64BitLibs && !has32BitLibs) { 11779 // The package has 64 bit libs, but not 32 bit libs. Its primary 11780 // ABI should be 64 bit. We can safely assume here that the bundled 11781 // native libraries correspond to the most preferred ABI in the list. 11782 11783 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11784 pkg.applicationInfo.secondaryCpuAbi = null; 11785 } else if (has32BitLibs && !has64BitLibs) { 11786 // The package has 32 bit libs but not 64 bit libs. Its primary 11787 // ABI should be 32 bit. 11788 11789 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11790 pkg.applicationInfo.secondaryCpuAbi = null; 11791 } else if (has32BitLibs && has64BitLibs) { 11792 // The application has both 64 and 32 bit bundled libraries. We check 11793 // here that the app declares multiArch support, and warn if it doesn't. 11794 // 11795 // We will be lenient here and record both ABIs. The primary will be the 11796 // ABI that's higher on the list, i.e, a device that's configured to prefer 11797 // 64 bit apps will see a 64 bit primary ABI, 11798 11799 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11800 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11801 } 11802 11803 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11804 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11805 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11806 } else { 11807 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11808 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11809 } 11810 } else { 11811 pkg.applicationInfo.primaryCpuAbi = null; 11812 pkg.applicationInfo.secondaryCpuAbi = null; 11813 } 11814 } 11815 11816 private void killApplication(String pkgName, int appId, String reason) { 11817 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11818 } 11819 11820 private void killApplication(String pkgName, int appId, int userId, String reason) { 11821 // Request the ActivityManager to kill the process(only for existing packages) 11822 // so that we do not end up in a confused state while the user is still using the older 11823 // version of the application while the new one gets installed. 11824 final long token = Binder.clearCallingIdentity(); 11825 try { 11826 IActivityManager am = ActivityManager.getService(); 11827 if (am != null) { 11828 try { 11829 am.killApplication(pkgName, appId, userId, reason); 11830 } catch (RemoteException e) { 11831 } 11832 } 11833 } finally { 11834 Binder.restoreCallingIdentity(token); 11835 } 11836 } 11837 11838 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 11839 // Remove the parent package setting 11840 PackageSetting ps = (PackageSetting) pkg.mExtras; 11841 if (ps != null) { 11842 removePackageLI(ps, chatty); 11843 } 11844 // Remove the child package setting 11845 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11846 for (int i = 0; i < childCount; i++) { 11847 PackageParser.Package childPkg = pkg.childPackages.get(i); 11848 ps = (PackageSetting) childPkg.mExtras; 11849 if (ps != null) { 11850 removePackageLI(ps, chatty); 11851 } 11852 } 11853 } 11854 11855 void removePackageLI(PackageSetting ps, boolean chatty) { 11856 if (DEBUG_INSTALL) { 11857 if (chatty) 11858 Log.d(TAG, "Removing package " + ps.name); 11859 } 11860 11861 // writer 11862 synchronized (mPackages) { 11863 mPackages.remove(ps.name); 11864 final PackageParser.Package pkg = ps.pkg; 11865 if (pkg != null) { 11866 cleanPackageDataStructuresLILPw(pkg, chatty); 11867 } 11868 } 11869 } 11870 11871 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11872 if (DEBUG_INSTALL) { 11873 if (chatty) 11874 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11875 } 11876 11877 // writer 11878 synchronized (mPackages) { 11879 // Remove the parent package 11880 mPackages.remove(pkg.applicationInfo.packageName); 11881 cleanPackageDataStructuresLILPw(pkg, chatty); 11882 11883 // Remove the child packages 11884 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11885 for (int i = 0; i < childCount; i++) { 11886 PackageParser.Package childPkg = pkg.childPackages.get(i); 11887 mPackages.remove(childPkg.applicationInfo.packageName); 11888 cleanPackageDataStructuresLILPw(childPkg, chatty); 11889 } 11890 } 11891 } 11892 11893 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11894 int N = pkg.providers.size(); 11895 StringBuilder r = null; 11896 int i; 11897 for (i=0; i<N; i++) { 11898 PackageParser.Provider p = pkg.providers.get(i); 11899 mProviders.removeProvider(p); 11900 if (p.info.authority == null) { 11901 11902 /* There was another ContentProvider with this authority when 11903 * this app was installed so this authority is null, 11904 * Ignore it as we don't have to unregister the provider. 11905 */ 11906 continue; 11907 } 11908 String names[] = p.info.authority.split(";"); 11909 for (int j = 0; j < names.length; j++) { 11910 if (mProvidersByAuthority.get(names[j]) == p) { 11911 mProvidersByAuthority.remove(names[j]); 11912 if (DEBUG_REMOVE) { 11913 if (chatty) 11914 Log.d(TAG, "Unregistered content provider: " + names[j] 11915 + ", className = " + p.info.name + ", isSyncable = " 11916 + p.info.isSyncable); 11917 } 11918 } 11919 } 11920 if (DEBUG_REMOVE && chatty) { 11921 if (r == null) { 11922 r = new StringBuilder(256); 11923 } else { 11924 r.append(' '); 11925 } 11926 r.append(p.info.name); 11927 } 11928 } 11929 if (r != null) { 11930 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11931 } 11932 11933 N = pkg.services.size(); 11934 r = null; 11935 for (i=0; i<N; i++) { 11936 PackageParser.Service s = pkg.services.get(i); 11937 mServices.removeService(s); 11938 if (chatty) { 11939 if (r == null) { 11940 r = new StringBuilder(256); 11941 } else { 11942 r.append(' '); 11943 } 11944 r.append(s.info.name); 11945 } 11946 } 11947 if (r != null) { 11948 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11949 } 11950 11951 N = pkg.receivers.size(); 11952 r = null; 11953 for (i=0; i<N; i++) { 11954 PackageParser.Activity a = pkg.receivers.get(i); 11955 mReceivers.removeActivity(a, "receiver"); 11956 if (DEBUG_REMOVE && chatty) { 11957 if (r == null) { 11958 r = new StringBuilder(256); 11959 } else { 11960 r.append(' '); 11961 } 11962 r.append(a.info.name); 11963 } 11964 } 11965 if (r != null) { 11966 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11967 } 11968 11969 N = pkg.activities.size(); 11970 r = null; 11971 for (i=0; i<N; i++) { 11972 PackageParser.Activity a = pkg.activities.get(i); 11973 mActivities.removeActivity(a, "activity"); 11974 if (DEBUG_REMOVE && chatty) { 11975 if (r == null) { 11976 r = new StringBuilder(256); 11977 } else { 11978 r.append(' '); 11979 } 11980 r.append(a.info.name); 11981 } 11982 } 11983 if (r != null) { 11984 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11985 } 11986 11987 mPermissionManager.removeAllPermissions(pkg, chatty); 11988 11989 N = pkg.instrumentation.size(); 11990 r = null; 11991 for (i=0; i<N; i++) { 11992 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11993 mInstrumentation.remove(a.getComponentName()); 11994 if (DEBUG_REMOVE && chatty) { 11995 if (r == null) { 11996 r = new StringBuilder(256); 11997 } else { 11998 r.append(' '); 11999 } 12000 r.append(a.info.name); 12001 } 12002 } 12003 if (r != null) { 12004 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 12005 } 12006 12007 r = null; 12008 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 12009 // Only system apps can hold shared libraries. 12010 if (pkg.libraryNames != null) { 12011 for (i = 0; i < pkg.libraryNames.size(); i++) { 12012 String name = pkg.libraryNames.get(i); 12013 if (removeSharedLibraryLPw(name, 0)) { 12014 if (DEBUG_REMOVE && chatty) { 12015 if (r == null) { 12016 r = new StringBuilder(256); 12017 } else { 12018 r.append(' '); 12019 } 12020 r.append(name); 12021 } 12022 } 12023 } 12024 } 12025 } 12026 12027 r = null; 12028 12029 // Any package can hold static shared libraries. 12030 if (pkg.staticSharedLibName != null) { 12031 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 12032 if (DEBUG_REMOVE && chatty) { 12033 if (r == null) { 12034 r = new StringBuilder(256); 12035 } else { 12036 r.append(' '); 12037 } 12038 r.append(pkg.staticSharedLibName); 12039 } 12040 } 12041 } 12042 12043 if (r != null) { 12044 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 12045 } 12046 } 12047 12048 12049 final class ActivityIntentResolver 12050 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 12051 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12052 boolean defaultOnly, int userId) { 12053 if (!sUserManager.exists(userId)) return null; 12054 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 12055 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12056 } 12057 12058 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12059 int userId) { 12060 if (!sUserManager.exists(userId)) return null; 12061 mFlags = flags; 12062 return super.queryIntent(intent, resolvedType, 12063 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12064 userId); 12065 } 12066 12067 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12068 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 12069 if (!sUserManager.exists(userId)) return null; 12070 if (packageActivities == null) { 12071 return null; 12072 } 12073 mFlags = flags; 12074 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12075 final int N = packageActivities.size(); 12076 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 12077 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 12078 12079 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 12080 for (int i = 0; i < N; ++i) { 12081 intentFilters = packageActivities.get(i).intents; 12082 if (intentFilters != null && intentFilters.size() > 0) { 12083 PackageParser.ActivityIntentInfo[] array = 12084 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 12085 intentFilters.toArray(array); 12086 listCut.add(array); 12087 } 12088 } 12089 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12090 } 12091 12092 /** 12093 * Finds a privileged activity that matches the specified activity names. 12094 */ 12095 private PackageParser.Activity findMatchingActivity( 12096 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 12097 for (PackageParser.Activity sysActivity : activityList) { 12098 if (sysActivity.info.name.equals(activityInfo.name)) { 12099 return sysActivity; 12100 } 12101 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 12102 return sysActivity; 12103 } 12104 if (sysActivity.info.targetActivity != null) { 12105 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 12106 return sysActivity; 12107 } 12108 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 12109 return sysActivity; 12110 } 12111 } 12112 } 12113 return null; 12114 } 12115 12116 public class IterGenerator<E> { 12117 public Iterator<E> generate(ActivityIntentInfo info) { 12118 return null; 12119 } 12120 } 12121 12122 public class ActionIterGenerator extends IterGenerator<String> { 12123 @Override 12124 public Iterator<String> generate(ActivityIntentInfo info) { 12125 return info.actionsIterator(); 12126 } 12127 } 12128 12129 public class CategoriesIterGenerator extends IterGenerator<String> { 12130 @Override 12131 public Iterator<String> generate(ActivityIntentInfo info) { 12132 return info.categoriesIterator(); 12133 } 12134 } 12135 12136 public class SchemesIterGenerator extends IterGenerator<String> { 12137 @Override 12138 public Iterator<String> generate(ActivityIntentInfo info) { 12139 return info.schemesIterator(); 12140 } 12141 } 12142 12143 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 12144 @Override 12145 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 12146 return info.authoritiesIterator(); 12147 } 12148 } 12149 12150 /** 12151 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12152 * MODIFIED. Do not pass in a list that should not be changed. 12153 */ 12154 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12155 IterGenerator<T> generator, Iterator<T> searchIterator) { 12156 // loop through the set of actions; every one must be found in the intent filter 12157 while (searchIterator.hasNext()) { 12158 // we must have at least one filter in the list to consider a match 12159 if (intentList.size() == 0) { 12160 break; 12161 } 12162 12163 final T searchAction = searchIterator.next(); 12164 12165 // loop through the set of intent filters 12166 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12167 while (intentIter.hasNext()) { 12168 final ActivityIntentInfo intentInfo = intentIter.next(); 12169 boolean selectionFound = false; 12170 12171 // loop through the intent filter's selection criteria; at least one 12172 // of them must match the searched criteria 12173 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12174 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12175 final T intentSelection = intentSelectionIter.next(); 12176 if (intentSelection != null && intentSelection.equals(searchAction)) { 12177 selectionFound = true; 12178 break; 12179 } 12180 } 12181 12182 // the selection criteria wasn't found in this filter's set; this filter 12183 // is not a potential match 12184 if (!selectionFound) { 12185 intentIter.remove(); 12186 } 12187 } 12188 } 12189 } 12190 12191 private boolean isProtectedAction(ActivityIntentInfo filter) { 12192 final Iterator<String> actionsIter = filter.actionsIterator(); 12193 while (actionsIter != null && actionsIter.hasNext()) { 12194 final String filterAction = actionsIter.next(); 12195 if (PROTECTED_ACTIONS.contains(filterAction)) { 12196 return true; 12197 } 12198 } 12199 return false; 12200 } 12201 12202 /** 12203 * Adjusts the priority of the given intent filter according to policy. 12204 * <p> 12205 * <ul> 12206 * <li>The priority for non privileged applications is capped to '0'</li> 12207 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12208 * <li>The priority for unbundled updates to privileged applications is capped to the 12209 * priority defined on the system partition</li> 12210 * </ul> 12211 * <p> 12212 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12213 * allowed to obtain any priority on any action. 12214 */ 12215 private void adjustPriority( 12216 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12217 // nothing to do; priority is fine as-is 12218 if (intent.getPriority() <= 0) { 12219 return; 12220 } 12221 12222 final ActivityInfo activityInfo = intent.activity.info; 12223 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12224 12225 final boolean privilegedApp = 12226 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12227 if (!privilegedApp) { 12228 // non-privileged applications can never define a priority >0 12229 if (DEBUG_FILTERS) { 12230 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 12231 + " package: " + applicationInfo.packageName 12232 + " activity: " + intent.activity.className 12233 + " origPrio: " + intent.getPriority()); 12234 } 12235 intent.setPriority(0); 12236 return; 12237 } 12238 12239 if (systemActivities == null) { 12240 // the system package is not disabled; we're parsing the system partition 12241 if (isProtectedAction(intent)) { 12242 if (mDeferProtectedFilters) { 12243 // We can't deal with these just yet. No component should ever obtain a 12244 // >0 priority for a protected actions, with ONE exception -- the setup 12245 // wizard. The setup wizard, however, cannot be known until we're able to 12246 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12247 // until all intent filters have been processed. Chicken, meet egg. 12248 // Let the filter temporarily have a high priority and rectify the 12249 // priorities after all system packages have been scanned. 12250 mProtectedFilters.add(intent); 12251 if (DEBUG_FILTERS) { 12252 Slog.i(TAG, "Protected action; save for later;" 12253 + " package: " + applicationInfo.packageName 12254 + " activity: " + intent.activity.className 12255 + " origPrio: " + intent.getPriority()); 12256 } 12257 return; 12258 } else { 12259 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12260 Slog.i(TAG, "No setup wizard;" 12261 + " All protected intents capped to priority 0"); 12262 } 12263 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12264 if (DEBUG_FILTERS) { 12265 Slog.i(TAG, "Found setup wizard;" 12266 + " allow priority " + intent.getPriority() + ";" 12267 + " package: " + intent.activity.info.packageName 12268 + " activity: " + intent.activity.className 12269 + " priority: " + intent.getPriority()); 12270 } 12271 // setup wizard gets whatever it wants 12272 return; 12273 } 12274 if (DEBUG_FILTERS) { 12275 Slog.i(TAG, "Protected action; cap priority to 0;" 12276 + " package: " + intent.activity.info.packageName 12277 + " activity: " + intent.activity.className 12278 + " origPrio: " + intent.getPriority()); 12279 } 12280 intent.setPriority(0); 12281 return; 12282 } 12283 } 12284 // privileged apps on the system image get whatever priority they request 12285 return; 12286 } 12287 12288 // privileged app unbundled update ... try to find the same activity 12289 final PackageParser.Activity foundActivity = 12290 findMatchingActivity(systemActivities, activityInfo); 12291 if (foundActivity == null) { 12292 // this is a new activity; it cannot obtain >0 priority 12293 if (DEBUG_FILTERS) { 12294 Slog.i(TAG, "New activity; cap priority to 0;" 12295 + " package: " + applicationInfo.packageName 12296 + " activity: " + intent.activity.className 12297 + " origPrio: " + intent.getPriority()); 12298 } 12299 intent.setPriority(0); 12300 return; 12301 } 12302 12303 // found activity, now check for filter equivalence 12304 12305 // a shallow copy is enough; we modify the list, not its contents 12306 final List<ActivityIntentInfo> intentListCopy = 12307 new ArrayList<>(foundActivity.intents); 12308 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12309 12310 // find matching action subsets 12311 final Iterator<String> actionsIterator = intent.actionsIterator(); 12312 if (actionsIterator != null) { 12313 getIntentListSubset( 12314 intentListCopy, new ActionIterGenerator(), actionsIterator); 12315 if (intentListCopy.size() == 0) { 12316 // no more intents to match; we're not equivalent 12317 if (DEBUG_FILTERS) { 12318 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12319 + " package: " + applicationInfo.packageName 12320 + " activity: " + intent.activity.className 12321 + " origPrio: " + intent.getPriority()); 12322 } 12323 intent.setPriority(0); 12324 return; 12325 } 12326 } 12327 12328 // find matching category subsets 12329 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12330 if (categoriesIterator != null) { 12331 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12332 categoriesIterator); 12333 if (intentListCopy.size() == 0) { 12334 // no more intents to match; we're not equivalent 12335 if (DEBUG_FILTERS) { 12336 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12337 + " package: " + applicationInfo.packageName 12338 + " activity: " + intent.activity.className 12339 + " origPrio: " + intent.getPriority()); 12340 } 12341 intent.setPriority(0); 12342 return; 12343 } 12344 } 12345 12346 // find matching schemes subsets 12347 final Iterator<String> schemesIterator = intent.schemesIterator(); 12348 if (schemesIterator != null) { 12349 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12350 schemesIterator); 12351 if (intentListCopy.size() == 0) { 12352 // no more intents to match; we're not equivalent 12353 if (DEBUG_FILTERS) { 12354 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12355 + " package: " + applicationInfo.packageName 12356 + " activity: " + intent.activity.className 12357 + " origPrio: " + intent.getPriority()); 12358 } 12359 intent.setPriority(0); 12360 return; 12361 } 12362 } 12363 12364 // find matching authorities subsets 12365 final Iterator<IntentFilter.AuthorityEntry> 12366 authoritiesIterator = intent.authoritiesIterator(); 12367 if (authoritiesIterator != null) { 12368 getIntentListSubset(intentListCopy, 12369 new AuthoritiesIterGenerator(), 12370 authoritiesIterator); 12371 if (intentListCopy.size() == 0) { 12372 // no more intents to match; we're not equivalent 12373 if (DEBUG_FILTERS) { 12374 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12375 + " package: " + applicationInfo.packageName 12376 + " activity: " + intent.activity.className 12377 + " origPrio: " + intent.getPriority()); 12378 } 12379 intent.setPriority(0); 12380 return; 12381 } 12382 } 12383 12384 // we found matching filter(s); app gets the max priority of all intents 12385 int cappedPriority = 0; 12386 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12387 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12388 } 12389 if (intent.getPriority() > cappedPriority) { 12390 if (DEBUG_FILTERS) { 12391 Slog.i(TAG, "Found matching filter(s);" 12392 + " cap priority to " + cappedPriority + ";" 12393 + " package: " + applicationInfo.packageName 12394 + " activity: " + intent.activity.className 12395 + " origPrio: " + intent.getPriority()); 12396 } 12397 intent.setPriority(cappedPriority); 12398 return; 12399 } 12400 // all this for nothing; the requested priority was <= what was on the system 12401 } 12402 12403 public final void addActivity(PackageParser.Activity a, String type) { 12404 mActivities.put(a.getComponentName(), a); 12405 if (DEBUG_SHOW_INFO) 12406 Log.v( 12407 TAG, " " + type + " " + 12408 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12409 if (DEBUG_SHOW_INFO) 12410 Log.v(TAG, " Class=" + a.info.name); 12411 final int NI = a.intents.size(); 12412 for (int j=0; j<NI; j++) { 12413 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12414 if ("activity".equals(type)) { 12415 final PackageSetting ps = 12416 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12417 final List<PackageParser.Activity> systemActivities = 12418 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12419 adjustPriority(systemActivities, intent); 12420 } 12421 if (DEBUG_SHOW_INFO) { 12422 Log.v(TAG, " IntentFilter:"); 12423 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12424 } 12425 if (!intent.debugCheck()) { 12426 Log.w(TAG, "==> For Activity " + a.info.name); 12427 } 12428 addFilter(intent); 12429 } 12430 } 12431 12432 public final void removeActivity(PackageParser.Activity a, String type) { 12433 mActivities.remove(a.getComponentName()); 12434 if (DEBUG_SHOW_INFO) { 12435 Log.v(TAG, " " + type + " " 12436 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12437 : a.info.name) + ":"); 12438 Log.v(TAG, " Class=" + a.info.name); 12439 } 12440 final int NI = a.intents.size(); 12441 for (int j=0; j<NI; j++) { 12442 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12443 if (DEBUG_SHOW_INFO) { 12444 Log.v(TAG, " IntentFilter:"); 12445 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12446 } 12447 removeFilter(intent); 12448 } 12449 } 12450 12451 @Override 12452 protected boolean allowFilterResult( 12453 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12454 ActivityInfo filterAi = filter.activity.info; 12455 for (int i=dest.size()-1; i>=0; i--) { 12456 ActivityInfo destAi = dest.get(i).activityInfo; 12457 if (destAi.name == filterAi.name 12458 && destAi.packageName == filterAi.packageName) { 12459 return false; 12460 } 12461 } 12462 return true; 12463 } 12464 12465 @Override 12466 protected ActivityIntentInfo[] newArray(int size) { 12467 return new ActivityIntentInfo[size]; 12468 } 12469 12470 @Override 12471 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12472 if (!sUserManager.exists(userId)) return true; 12473 PackageParser.Package p = filter.activity.owner; 12474 if (p != null) { 12475 PackageSetting ps = (PackageSetting)p.mExtras; 12476 if (ps != null) { 12477 // System apps are never considered stopped for purposes of 12478 // filtering, because there may be no way for the user to 12479 // actually re-launch them. 12480 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12481 && ps.getStopped(userId); 12482 } 12483 } 12484 return false; 12485 } 12486 12487 @Override 12488 protected boolean isPackageForFilter(String packageName, 12489 PackageParser.ActivityIntentInfo info) { 12490 return packageName.equals(info.activity.owner.packageName); 12491 } 12492 12493 @Override 12494 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12495 int match, int userId) { 12496 if (!sUserManager.exists(userId)) return null; 12497 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12498 return null; 12499 } 12500 final PackageParser.Activity activity = info.activity; 12501 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12502 if (ps == null) { 12503 return null; 12504 } 12505 final PackageUserState userState = ps.readUserState(userId); 12506 ActivityInfo ai = 12507 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 12508 if (ai == null) { 12509 return null; 12510 } 12511 final boolean matchExplicitlyVisibleOnly = 12512 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12513 final boolean matchVisibleToInstantApp = 12514 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12515 final boolean componentVisible = 12516 matchVisibleToInstantApp 12517 && info.isVisibleToInstantApp() 12518 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12519 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12520 // throw out filters that aren't visible to ephemeral apps 12521 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12522 return null; 12523 } 12524 // throw out instant app filters if we're not explicitly requesting them 12525 if (!matchInstantApp && userState.instantApp) { 12526 return null; 12527 } 12528 // throw out instant app filters if updates are available; will trigger 12529 // instant app resolution 12530 if (userState.instantApp && ps.isUpdateAvailable()) { 12531 return null; 12532 } 12533 final ResolveInfo res = new ResolveInfo(); 12534 res.activityInfo = ai; 12535 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12536 res.filter = info; 12537 } 12538 if (info != null) { 12539 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12540 } 12541 res.priority = info.getPriority(); 12542 res.preferredOrder = activity.owner.mPreferredOrder; 12543 //System.out.println("Result: " + res.activityInfo.className + 12544 // " = " + res.priority); 12545 res.match = match; 12546 res.isDefault = info.hasDefault; 12547 res.labelRes = info.labelRes; 12548 res.nonLocalizedLabel = info.nonLocalizedLabel; 12549 if (userNeedsBadging(userId)) { 12550 res.noResourceId = true; 12551 } else { 12552 res.icon = info.icon; 12553 } 12554 res.iconResourceId = info.icon; 12555 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12556 res.isInstantAppAvailable = userState.instantApp; 12557 return res; 12558 } 12559 12560 @Override 12561 protected void sortResults(List<ResolveInfo> results) { 12562 Collections.sort(results, mResolvePrioritySorter); 12563 } 12564 12565 @Override 12566 protected void dumpFilter(PrintWriter out, String prefix, 12567 PackageParser.ActivityIntentInfo filter) { 12568 out.print(prefix); out.print( 12569 Integer.toHexString(System.identityHashCode(filter.activity))); 12570 out.print(' '); 12571 filter.activity.printComponentShortName(out); 12572 out.print(" filter "); 12573 out.println(Integer.toHexString(System.identityHashCode(filter))); 12574 } 12575 12576 @Override 12577 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12578 return filter.activity; 12579 } 12580 12581 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12582 PackageParser.Activity activity = (PackageParser.Activity)label; 12583 out.print(prefix); out.print( 12584 Integer.toHexString(System.identityHashCode(activity))); 12585 out.print(' '); 12586 activity.printComponentShortName(out); 12587 if (count > 1) { 12588 out.print(" ("); out.print(count); out.print(" filters)"); 12589 } 12590 out.println(); 12591 } 12592 12593 // Keys are String (activity class name), values are Activity. 12594 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12595 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12596 private int mFlags; 12597 } 12598 12599 private final class ServiceIntentResolver 12600 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12601 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12602 boolean defaultOnly, int userId) { 12603 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12604 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12605 } 12606 12607 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12608 int userId) { 12609 if (!sUserManager.exists(userId)) return null; 12610 mFlags = flags; 12611 return super.queryIntent(intent, resolvedType, 12612 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12613 userId); 12614 } 12615 12616 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12617 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12618 if (!sUserManager.exists(userId)) return null; 12619 if (packageServices == null) { 12620 return null; 12621 } 12622 mFlags = flags; 12623 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12624 final int N = packageServices.size(); 12625 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12626 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12627 12628 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12629 for (int i = 0; i < N; ++i) { 12630 intentFilters = packageServices.get(i).intents; 12631 if (intentFilters != null && intentFilters.size() > 0) { 12632 PackageParser.ServiceIntentInfo[] array = 12633 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12634 intentFilters.toArray(array); 12635 listCut.add(array); 12636 } 12637 } 12638 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12639 } 12640 12641 public final void addService(PackageParser.Service s) { 12642 mServices.put(s.getComponentName(), s); 12643 if (DEBUG_SHOW_INFO) { 12644 Log.v(TAG, " " 12645 + (s.info.nonLocalizedLabel != null 12646 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12647 Log.v(TAG, " Class=" + s.info.name); 12648 } 12649 final int NI = s.intents.size(); 12650 int j; 12651 for (j=0; j<NI; j++) { 12652 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12653 if (DEBUG_SHOW_INFO) { 12654 Log.v(TAG, " IntentFilter:"); 12655 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12656 } 12657 if (!intent.debugCheck()) { 12658 Log.w(TAG, "==> For Service " + s.info.name); 12659 } 12660 addFilter(intent); 12661 } 12662 } 12663 12664 public final void removeService(PackageParser.Service s) { 12665 mServices.remove(s.getComponentName()); 12666 if (DEBUG_SHOW_INFO) { 12667 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12668 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12669 Log.v(TAG, " Class=" + s.info.name); 12670 } 12671 final int NI = s.intents.size(); 12672 int j; 12673 for (j=0; j<NI; j++) { 12674 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12675 if (DEBUG_SHOW_INFO) { 12676 Log.v(TAG, " IntentFilter:"); 12677 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12678 } 12679 removeFilter(intent); 12680 } 12681 } 12682 12683 @Override 12684 protected boolean allowFilterResult( 12685 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12686 ServiceInfo filterSi = filter.service.info; 12687 for (int i=dest.size()-1; i>=0; i--) { 12688 ServiceInfo destAi = dest.get(i).serviceInfo; 12689 if (destAi.name == filterSi.name 12690 && destAi.packageName == filterSi.packageName) { 12691 return false; 12692 } 12693 } 12694 return true; 12695 } 12696 12697 @Override 12698 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12699 return new PackageParser.ServiceIntentInfo[size]; 12700 } 12701 12702 @Override 12703 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12704 if (!sUserManager.exists(userId)) return true; 12705 PackageParser.Package p = filter.service.owner; 12706 if (p != null) { 12707 PackageSetting ps = (PackageSetting)p.mExtras; 12708 if (ps != null) { 12709 // System apps are never considered stopped for purposes of 12710 // filtering, because there may be no way for the user to 12711 // actually re-launch them. 12712 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12713 && ps.getStopped(userId); 12714 } 12715 } 12716 return false; 12717 } 12718 12719 @Override 12720 protected boolean isPackageForFilter(String packageName, 12721 PackageParser.ServiceIntentInfo info) { 12722 return packageName.equals(info.service.owner.packageName); 12723 } 12724 12725 @Override 12726 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12727 int match, int userId) { 12728 if (!sUserManager.exists(userId)) return null; 12729 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12730 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12731 return null; 12732 } 12733 final PackageParser.Service service = info.service; 12734 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12735 if (ps == null) { 12736 return null; 12737 } 12738 final PackageUserState userState = ps.readUserState(userId); 12739 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12740 userState, userId); 12741 if (si == null) { 12742 return null; 12743 } 12744 final boolean matchVisibleToInstantApp = 12745 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12746 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12747 // throw out filters that aren't visible to ephemeral apps 12748 if (matchVisibleToInstantApp 12749 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12750 return null; 12751 } 12752 // throw out ephemeral filters if we're not explicitly requesting them 12753 if (!isInstantApp && userState.instantApp) { 12754 return null; 12755 } 12756 // throw out instant app filters if updates are available; will trigger 12757 // instant app resolution 12758 if (userState.instantApp && ps.isUpdateAvailable()) { 12759 return null; 12760 } 12761 final ResolveInfo res = new ResolveInfo(); 12762 res.serviceInfo = si; 12763 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12764 res.filter = filter; 12765 } 12766 res.priority = info.getPriority(); 12767 res.preferredOrder = service.owner.mPreferredOrder; 12768 res.match = match; 12769 res.isDefault = info.hasDefault; 12770 res.labelRes = info.labelRes; 12771 res.nonLocalizedLabel = info.nonLocalizedLabel; 12772 res.icon = info.icon; 12773 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12774 return res; 12775 } 12776 12777 @Override 12778 protected void sortResults(List<ResolveInfo> results) { 12779 Collections.sort(results, mResolvePrioritySorter); 12780 } 12781 12782 @Override 12783 protected void dumpFilter(PrintWriter out, String prefix, 12784 PackageParser.ServiceIntentInfo filter) { 12785 out.print(prefix); out.print( 12786 Integer.toHexString(System.identityHashCode(filter.service))); 12787 out.print(' '); 12788 filter.service.printComponentShortName(out); 12789 out.print(" filter "); 12790 out.print(Integer.toHexString(System.identityHashCode(filter))); 12791 if (filter.service.info.permission != null) { 12792 out.print(" permission "); out.println(filter.service.info.permission); 12793 } else { 12794 out.println(); 12795 } 12796 } 12797 12798 @Override 12799 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12800 return filter.service; 12801 } 12802 12803 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12804 PackageParser.Service service = (PackageParser.Service)label; 12805 out.print(prefix); out.print( 12806 Integer.toHexString(System.identityHashCode(service))); 12807 out.print(' '); 12808 service.printComponentShortName(out); 12809 if (count > 1) { 12810 out.print(" ("); out.print(count); out.print(" filters)"); 12811 } 12812 out.println(); 12813 } 12814 12815// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12816// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12817// final List<ResolveInfo> retList = Lists.newArrayList(); 12818// while (i.hasNext()) { 12819// final ResolveInfo resolveInfo = (ResolveInfo) i; 12820// if (isEnabledLP(resolveInfo.serviceInfo)) { 12821// retList.add(resolveInfo); 12822// } 12823// } 12824// return retList; 12825// } 12826 12827 // Keys are String (activity class name), values are Activity. 12828 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12829 = new ArrayMap<ComponentName, PackageParser.Service>(); 12830 private int mFlags; 12831 } 12832 12833 private final class ProviderIntentResolver 12834 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12835 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12836 boolean defaultOnly, int userId) { 12837 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12838 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12839 } 12840 12841 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12842 int userId) { 12843 if (!sUserManager.exists(userId)) 12844 return null; 12845 mFlags = flags; 12846 return super.queryIntent(intent, resolvedType, 12847 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12848 userId); 12849 } 12850 12851 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12852 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12853 if (!sUserManager.exists(userId)) 12854 return null; 12855 if (packageProviders == null) { 12856 return null; 12857 } 12858 mFlags = flags; 12859 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12860 final int N = packageProviders.size(); 12861 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12862 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12863 12864 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12865 for (int i = 0; i < N; ++i) { 12866 intentFilters = packageProviders.get(i).intents; 12867 if (intentFilters != null && intentFilters.size() > 0) { 12868 PackageParser.ProviderIntentInfo[] array = 12869 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12870 intentFilters.toArray(array); 12871 listCut.add(array); 12872 } 12873 } 12874 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12875 } 12876 12877 public final void addProvider(PackageParser.Provider p) { 12878 if (mProviders.containsKey(p.getComponentName())) { 12879 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12880 return; 12881 } 12882 12883 mProviders.put(p.getComponentName(), p); 12884 if (DEBUG_SHOW_INFO) { 12885 Log.v(TAG, " " 12886 + (p.info.nonLocalizedLabel != null 12887 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12888 Log.v(TAG, " Class=" + p.info.name); 12889 } 12890 final int NI = p.intents.size(); 12891 int j; 12892 for (j = 0; j < NI; j++) { 12893 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12894 if (DEBUG_SHOW_INFO) { 12895 Log.v(TAG, " IntentFilter:"); 12896 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12897 } 12898 if (!intent.debugCheck()) { 12899 Log.w(TAG, "==> For Provider " + p.info.name); 12900 } 12901 addFilter(intent); 12902 } 12903 } 12904 12905 public final void removeProvider(PackageParser.Provider p) { 12906 mProviders.remove(p.getComponentName()); 12907 if (DEBUG_SHOW_INFO) { 12908 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12909 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12910 Log.v(TAG, " Class=" + p.info.name); 12911 } 12912 final int NI = p.intents.size(); 12913 int j; 12914 for (j = 0; j < NI; j++) { 12915 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12916 if (DEBUG_SHOW_INFO) { 12917 Log.v(TAG, " IntentFilter:"); 12918 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12919 } 12920 removeFilter(intent); 12921 } 12922 } 12923 12924 @Override 12925 protected boolean allowFilterResult( 12926 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12927 ProviderInfo filterPi = filter.provider.info; 12928 for (int i = dest.size() - 1; i >= 0; i--) { 12929 ProviderInfo destPi = dest.get(i).providerInfo; 12930 if (destPi.name == filterPi.name 12931 && destPi.packageName == filterPi.packageName) { 12932 return false; 12933 } 12934 } 12935 return true; 12936 } 12937 12938 @Override 12939 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12940 return new PackageParser.ProviderIntentInfo[size]; 12941 } 12942 12943 @Override 12944 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12945 if (!sUserManager.exists(userId)) 12946 return true; 12947 PackageParser.Package p = filter.provider.owner; 12948 if (p != null) { 12949 PackageSetting ps = (PackageSetting) p.mExtras; 12950 if (ps != null) { 12951 // System apps are never considered stopped for purposes of 12952 // filtering, because there may be no way for the user to 12953 // actually re-launch them. 12954 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12955 && ps.getStopped(userId); 12956 } 12957 } 12958 return false; 12959 } 12960 12961 @Override 12962 protected boolean isPackageForFilter(String packageName, 12963 PackageParser.ProviderIntentInfo info) { 12964 return packageName.equals(info.provider.owner.packageName); 12965 } 12966 12967 @Override 12968 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12969 int match, int userId) { 12970 if (!sUserManager.exists(userId)) 12971 return null; 12972 final PackageParser.ProviderIntentInfo info = filter; 12973 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12974 return null; 12975 } 12976 final PackageParser.Provider provider = info.provider; 12977 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12978 if (ps == null) { 12979 return null; 12980 } 12981 final PackageUserState userState = ps.readUserState(userId); 12982 final boolean matchVisibleToInstantApp = 12983 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12984 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12985 // throw out filters that aren't visible to instant applications 12986 if (matchVisibleToInstantApp 12987 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12988 return null; 12989 } 12990 // throw out instant application filters if we're not explicitly requesting them 12991 if (!isInstantApp && userState.instantApp) { 12992 return null; 12993 } 12994 // throw out instant application filters if updates are available; will trigger 12995 // instant application resolution 12996 if (userState.instantApp && ps.isUpdateAvailable()) { 12997 return null; 12998 } 12999 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 13000 userState, userId); 13001 if (pi == null) { 13002 return null; 13003 } 13004 final ResolveInfo res = new ResolveInfo(); 13005 res.providerInfo = pi; 13006 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 13007 res.filter = filter; 13008 } 13009 res.priority = info.getPriority(); 13010 res.preferredOrder = provider.owner.mPreferredOrder; 13011 res.match = match; 13012 res.isDefault = info.hasDefault; 13013 res.labelRes = info.labelRes; 13014 res.nonLocalizedLabel = info.nonLocalizedLabel; 13015 res.icon = info.icon; 13016 res.system = res.providerInfo.applicationInfo.isSystemApp(); 13017 return res; 13018 } 13019 13020 @Override 13021 protected void sortResults(List<ResolveInfo> results) { 13022 Collections.sort(results, mResolvePrioritySorter); 13023 } 13024 13025 @Override 13026 protected void dumpFilter(PrintWriter out, String prefix, 13027 PackageParser.ProviderIntentInfo filter) { 13028 out.print(prefix); 13029 out.print( 13030 Integer.toHexString(System.identityHashCode(filter.provider))); 13031 out.print(' '); 13032 filter.provider.printComponentShortName(out); 13033 out.print(" filter "); 13034 out.println(Integer.toHexString(System.identityHashCode(filter))); 13035 } 13036 13037 @Override 13038 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 13039 return filter.provider; 13040 } 13041 13042 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13043 PackageParser.Provider provider = (PackageParser.Provider)label; 13044 out.print(prefix); out.print( 13045 Integer.toHexString(System.identityHashCode(provider))); 13046 out.print(' '); 13047 provider.printComponentShortName(out); 13048 if (count > 1) { 13049 out.print(" ("); out.print(count); out.print(" filters)"); 13050 } 13051 out.println(); 13052 } 13053 13054 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 13055 = new ArrayMap<ComponentName, PackageParser.Provider>(); 13056 private int mFlags; 13057 } 13058 13059 static final class EphemeralIntentResolver 13060 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 13061 /** 13062 * The result that has the highest defined order. Ordering applies on a 13063 * per-package basis. Mapping is from package name to Pair of order and 13064 * EphemeralResolveInfo. 13065 * <p> 13066 * NOTE: This is implemented as a field variable for convenience and efficiency. 13067 * By having a field variable, we're able to track filter ordering as soon as 13068 * a non-zero order is defined. Otherwise, multiple loops across the result set 13069 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 13070 * this needs to be contained entirely within {@link #filterResults}. 13071 */ 13072 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 13073 13074 @Override 13075 protected AuxiliaryResolveInfo[] newArray(int size) { 13076 return new AuxiliaryResolveInfo[size]; 13077 } 13078 13079 @Override 13080 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 13081 return true; 13082 } 13083 13084 @Override 13085 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 13086 int userId) { 13087 if (!sUserManager.exists(userId)) { 13088 return null; 13089 } 13090 final String packageName = responseObj.resolveInfo.getPackageName(); 13091 final Integer order = responseObj.getOrder(); 13092 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 13093 mOrderResult.get(packageName); 13094 // ordering is enabled and this item's order isn't high enough 13095 if (lastOrderResult != null && lastOrderResult.first >= order) { 13096 return null; 13097 } 13098 final InstantAppResolveInfo res = responseObj.resolveInfo; 13099 if (order > 0) { 13100 // non-zero order, enable ordering 13101 mOrderResult.put(packageName, new Pair<>(order, res)); 13102 } 13103 return responseObj; 13104 } 13105 13106 @Override 13107 protected void filterResults(List<AuxiliaryResolveInfo> results) { 13108 // only do work if ordering is enabled [most of the time it won't be] 13109 if (mOrderResult.size() == 0) { 13110 return; 13111 } 13112 int resultSize = results.size(); 13113 for (int i = 0; i < resultSize; i++) { 13114 final InstantAppResolveInfo info = results.get(i).resolveInfo; 13115 final String packageName = info.getPackageName(); 13116 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 13117 if (savedInfo == null) { 13118 // package doesn't having ordering 13119 continue; 13120 } 13121 if (savedInfo.second == info) { 13122 // circled back to the highest ordered item; remove from order list 13123 mOrderResult.remove(packageName); 13124 if (mOrderResult.size() == 0) { 13125 // no more ordered items 13126 break; 13127 } 13128 continue; 13129 } 13130 // item has a worse order, remove it from the result list 13131 results.remove(i); 13132 resultSize--; 13133 i--; 13134 } 13135 } 13136 } 13137 13138 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 13139 new Comparator<ResolveInfo>() { 13140 public int compare(ResolveInfo r1, ResolveInfo r2) { 13141 int v1 = r1.priority; 13142 int v2 = r2.priority; 13143 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 13144 if (v1 != v2) { 13145 return (v1 > v2) ? -1 : 1; 13146 } 13147 v1 = r1.preferredOrder; 13148 v2 = r2.preferredOrder; 13149 if (v1 != v2) { 13150 return (v1 > v2) ? -1 : 1; 13151 } 13152 if (r1.isDefault != r2.isDefault) { 13153 return r1.isDefault ? -1 : 1; 13154 } 13155 v1 = r1.match; 13156 v2 = r2.match; 13157 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13158 if (v1 != v2) { 13159 return (v1 > v2) ? -1 : 1; 13160 } 13161 if (r1.system != r2.system) { 13162 return r1.system ? -1 : 1; 13163 } 13164 if (r1.activityInfo != null) { 13165 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13166 } 13167 if (r1.serviceInfo != null) { 13168 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13169 } 13170 if (r1.providerInfo != null) { 13171 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13172 } 13173 return 0; 13174 } 13175 }; 13176 13177 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13178 new Comparator<ProviderInfo>() { 13179 public int compare(ProviderInfo p1, ProviderInfo p2) { 13180 final int v1 = p1.initOrder; 13181 final int v2 = p2.initOrder; 13182 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13183 } 13184 }; 13185 13186 @Override 13187 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13188 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13189 final int[] userIds, int[] instantUserIds) { 13190 mHandler.post(new Runnable() { 13191 @Override 13192 public void run() { 13193 try { 13194 final IActivityManager am = ActivityManager.getService(); 13195 if (am == null) return; 13196 final int[] resolvedUserIds; 13197 if (userIds == null) { 13198 resolvedUserIds = am.getRunningUserIds(); 13199 } else { 13200 resolvedUserIds = userIds; 13201 } 13202 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13203 resolvedUserIds, false); 13204 if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) { 13205 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13206 instantUserIds, true); 13207 } 13208 } catch (RemoteException ex) { 13209 } 13210 } 13211 }); 13212 } 13213 13214 @Override 13215 public void notifyPackageAdded(String packageName) { 13216 final PackageListObserver[] observers; 13217 synchronized (mPackages) { 13218 if (mPackageListObservers.size() == 0) { 13219 return; 13220 } 13221 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13222 } 13223 for (int i = observers.length - 1; i >= 0; --i) { 13224 observers[i].onPackageAdded(packageName); 13225 } 13226 } 13227 13228 @Override 13229 public void notifyPackageRemoved(String packageName) { 13230 final PackageListObserver[] observers; 13231 synchronized (mPackages) { 13232 if (mPackageListObservers.size() == 0) { 13233 return; 13234 } 13235 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13236 } 13237 for (int i = observers.length - 1; i >= 0; --i) { 13238 observers[i].onPackageRemoved(packageName); 13239 } 13240 } 13241 13242 /** 13243 * Sends a broadcast for the given action. 13244 * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with 13245 * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows 13246 * the system and applications allowed to see instant applications to receive package 13247 * lifecycle events for instant applications. 13248 */ 13249 private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras, 13250 int flags, String targetPkg, IIntentReceiver finishedReceiver, 13251 int[] userIds, boolean isInstantApp) 13252 throws RemoteException { 13253 for (int id : userIds) { 13254 final Intent intent = new Intent(action, 13255 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13256 final String[] requiredPermissions = 13257 isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null; 13258 if (extras != null) { 13259 intent.putExtras(extras); 13260 } 13261 if (targetPkg != null) { 13262 intent.setPackage(targetPkg); 13263 } 13264 // Modify the UID when posting to other users 13265 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13266 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13267 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13268 intent.putExtra(Intent.EXTRA_UID, uid); 13269 } 13270 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13271 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13272 if (DEBUG_BROADCASTS) { 13273 RuntimeException here = new RuntimeException("here"); 13274 here.fillInStackTrace(); 13275 Slog.d(TAG, "Sending to user " + id + ": " 13276 + intent.toShortString(false, true, false, false) 13277 + " " + intent.getExtras(), here); 13278 } 13279 am.broadcastIntent(null, intent, null, finishedReceiver, 13280 0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE, 13281 null, finishedReceiver != null, false, id); 13282 } 13283 } 13284 13285 /** 13286 * Check if the external storage media is available. This is true if there 13287 * is a mounted external storage medium or if the external storage is 13288 * emulated. 13289 */ 13290 private boolean isExternalMediaAvailable() { 13291 return mMediaMounted || Environment.isExternalStorageEmulated(); 13292 } 13293 13294 @Override 13295 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13296 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 13297 return null; 13298 } 13299 if (!isExternalMediaAvailable()) { 13300 // If the external storage is no longer mounted at this point, 13301 // the caller may not have been able to delete all of this 13302 // packages files and can not delete any more. Bail. 13303 return null; 13304 } 13305 synchronized (mPackages) { 13306 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13307 if (lastPackage != null) { 13308 pkgs.remove(lastPackage); 13309 } 13310 if (pkgs.size() > 0) { 13311 return pkgs.get(0); 13312 } 13313 } 13314 return null; 13315 } 13316 13317 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13318 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13319 userId, andCode ? 1 : 0, packageName); 13320 if (mSystemReady) { 13321 msg.sendToTarget(); 13322 } else { 13323 if (mPostSystemReadyMessages == null) { 13324 mPostSystemReadyMessages = new ArrayList<>(); 13325 } 13326 mPostSystemReadyMessages.add(msg); 13327 } 13328 } 13329 13330 void startCleaningPackages() { 13331 // reader 13332 if (!isExternalMediaAvailable()) { 13333 return; 13334 } 13335 synchronized (mPackages) { 13336 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13337 return; 13338 } 13339 } 13340 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13341 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13342 IActivityManager am = ActivityManager.getService(); 13343 if (am != null) { 13344 int dcsUid = -1; 13345 synchronized (mPackages) { 13346 if (!mDefaultContainerWhitelisted) { 13347 mDefaultContainerWhitelisted = true; 13348 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13349 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13350 } 13351 } 13352 try { 13353 if (dcsUid > 0) { 13354 am.backgroundWhitelistUid(dcsUid); 13355 } 13356 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13357 UserHandle.USER_SYSTEM); 13358 } catch (RemoteException e) { 13359 } 13360 } 13361 } 13362 13363 /** 13364 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13365 * it is acting on behalf on an enterprise or the user). 13366 * 13367 * Note that the ordering of the conditionals in this method is important. The checks we perform 13368 * are as follows, in this order: 13369 * 13370 * 1) If the install is being performed by a system app, we can trust the app to have set the 13371 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13372 * what it is. 13373 * 2) If the install is being performed by a device or profile owner app, the install reason 13374 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13375 * set the install reason correctly. If the app targets an older SDK version where install 13376 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13377 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13378 * 3) In all other cases, the install is being performed by a regular app that is neither part 13379 * of the system nor a device or profile owner. We have no reason to believe that this app is 13380 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13381 * set to enterprise policy and if so, change it to unknown instead. 13382 */ 13383 private int fixUpInstallReason(String installerPackageName, int installerUid, 13384 int installReason) { 13385 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13386 == PERMISSION_GRANTED) { 13387 // If the install is being performed by a system app, we trust that app to have set the 13388 // install reason correctly. 13389 return installReason; 13390 } 13391 13392 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13393 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13394 if (dpm != null) { 13395 ComponentName owner = null; 13396 try { 13397 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13398 if (owner == null) { 13399 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13400 } 13401 } catch (RemoteException e) { 13402 } 13403 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13404 // If the install is being performed by a device or profile owner, the install 13405 // reason should be enterprise policy. 13406 return PackageManager.INSTALL_REASON_POLICY; 13407 } 13408 } 13409 13410 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13411 // If the install is being performed by a regular app (i.e. neither system app nor 13412 // device or profile owner), we have no reason to believe that the app is acting on 13413 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13414 // change it to unknown instead. 13415 return PackageManager.INSTALL_REASON_UNKNOWN; 13416 } 13417 13418 // If the install is being performed by a regular app and the install reason was set to any 13419 // value but enterprise policy, leave the install reason unchanged. 13420 return installReason; 13421 } 13422 13423 void installStage(String packageName, File stagedDir, 13424 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13425 String installerPackageName, int installerUid, UserHandle user, 13426 PackageParser.SigningDetails signingDetails) { 13427 if (DEBUG_EPHEMERAL) { 13428 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13429 Slog.d(TAG, "Ephemeral install of " + packageName); 13430 } 13431 } 13432 final VerificationInfo verificationInfo = new VerificationInfo( 13433 sessionParams.originatingUri, sessionParams.referrerUri, 13434 sessionParams.originatingUid, installerUid); 13435 13436 final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir); 13437 13438 final Message msg = mHandler.obtainMessage(INIT_COPY); 13439 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13440 sessionParams.installReason); 13441 final InstallParams params = new InstallParams(origin, null, observer, 13442 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13443 verificationInfo, user, sessionParams.abiOverride, 13444 sessionParams.grantedRuntimePermissions, signingDetails, installReason); 13445 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13446 msg.obj = params; 13447 13448 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13449 System.identityHashCode(msg.obj)); 13450 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13451 System.identityHashCode(msg.obj)); 13452 13453 mHandler.sendMessage(msg); 13454 } 13455 13456 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13457 int userId) { 13458 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13459 final boolean isInstantApp = pkgSetting.getInstantApp(userId); 13460 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 13461 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 13462 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 13463 false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds); 13464 13465 // Send a session commit broadcast 13466 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 13467 info.installReason = pkgSetting.getInstallReason(userId); 13468 info.appPackageName = packageName; 13469 sendSessionCommitBroadcast(info, userId); 13470 } 13471 13472 @Override 13473 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 13474 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) { 13475 if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) { 13476 return; 13477 } 13478 Bundle extras = new Bundle(1); 13479 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13480 final int uid = UserHandle.getUid( 13481 (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId); 13482 extras.putInt(Intent.EXTRA_UID, uid); 13483 13484 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13485 packageName, extras, 0, null, null, userIds, instantUserIds); 13486 if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) { 13487 mHandler.post(() -> { 13488 for (int userId : userIds) { 13489 sendBootCompletedBroadcastToSystemApp( 13490 packageName, includeStopped, userId); 13491 } 13492 } 13493 ); 13494 } 13495 } 13496 13497 /** 13498 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13499 * automatically without needing an explicit launch. 13500 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13501 */ 13502 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 13503 int userId) { 13504 // If user is not running, the app didn't miss any broadcast 13505 if (!mUserManagerInternal.isUserRunning(userId)) { 13506 return; 13507 } 13508 final IActivityManager am = ActivityManager.getService(); 13509 try { 13510 // Deliver LOCKED_BOOT_COMPLETED first 13511 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13512 .setPackage(packageName); 13513 if (includeStopped) { 13514 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13515 } 13516 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13517 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13518 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13519 13520 // Deliver BOOT_COMPLETED only if user is unlocked 13521 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13522 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13523 if (includeStopped) { 13524 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13525 } 13526 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13527 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13528 } 13529 } catch (RemoteException e) { 13530 throw e.rethrowFromSystemServer(); 13531 } 13532 } 13533 13534 @Override 13535 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13536 int userId) { 13537 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13538 PackageSetting pkgSetting; 13539 final int callingUid = Binder.getCallingUid(); 13540 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13541 true /* requireFullPermission */, true /* checkShell */, 13542 "setApplicationHiddenSetting for user " + userId); 13543 13544 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13545 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13546 return false; 13547 } 13548 13549 long callingId = Binder.clearCallingIdentity(); 13550 try { 13551 boolean sendAdded = false; 13552 boolean sendRemoved = false; 13553 // writer 13554 synchronized (mPackages) { 13555 pkgSetting = mSettings.mPackages.get(packageName); 13556 if (pkgSetting == null) { 13557 return false; 13558 } 13559 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13560 return false; 13561 } 13562 // Do not allow "android" is being disabled 13563 if ("android".equals(packageName)) { 13564 Slog.w(TAG, "Cannot hide package: android"); 13565 return false; 13566 } 13567 // Cannot hide static shared libs as they are considered 13568 // a part of the using app (emulating static linking). Also 13569 // static libs are installed always on internal storage. 13570 PackageParser.Package pkg = mPackages.get(packageName); 13571 if (pkg != null && pkg.staticSharedLibName != null) { 13572 Slog.w(TAG, "Cannot hide package: " + packageName 13573 + " providing static shared library: " 13574 + pkg.staticSharedLibName); 13575 return false; 13576 } 13577 // Only allow protected packages to hide themselves. 13578 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 13579 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13580 Slog.w(TAG, "Not hiding protected package: " + packageName); 13581 return false; 13582 } 13583 13584 if (pkgSetting.getHidden(userId) != hidden) { 13585 pkgSetting.setHidden(hidden, userId); 13586 mSettings.writePackageRestrictionsLPr(userId); 13587 if (hidden) { 13588 sendRemoved = true; 13589 } else { 13590 sendAdded = true; 13591 } 13592 } 13593 } 13594 if (sendAdded) { 13595 sendPackageAddedForUser(packageName, pkgSetting, userId); 13596 return true; 13597 } 13598 if (sendRemoved) { 13599 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13600 "hiding pkg"); 13601 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13602 return true; 13603 } 13604 } finally { 13605 Binder.restoreCallingIdentity(callingId); 13606 } 13607 return false; 13608 } 13609 13610 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13611 int userId) { 13612 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13613 info.removedPackage = packageName; 13614 info.installerPackageName = pkgSetting.installerPackageName; 13615 info.removedUsers = new int[] {userId}; 13616 info.broadcastUsers = new int[] {userId}; 13617 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13618 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13619 } 13620 13621 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13622 if (pkgList.length > 0) { 13623 Bundle extras = new Bundle(1); 13624 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13625 13626 sendPackageBroadcast( 13627 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13628 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13629 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13630 new int[] {userId}, null); 13631 } 13632 } 13633 13634 /** 13635 * Returns true if application is not found or there was an error. Otherwise it returns 13636 * the hidden state of the package for the given user. 13637 */ 13638 @Override 13639 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13640 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13641 final int callingUid = Binder.getCallingUid(); 13642 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13643 true /* requireFullPermission */, false /* checkShell */, 13644 "getApplicationHidden for user " + userId); 13645 PackageSetting ps; 13646 long callingId = Binder.clearCallingIdentity(); 13647 try { 13648 // writer 13649 synchronized (mPackages) { 13650 ps = mSettings.mPackages.get(packageName); 13651 if (ps == null) { 13652 return true; 13653 } 13654 if (filterAppAccessLPr(ps, callingUid, userId)) { 13655 return true; 13656 } 13657 return ps.getHidden(userId); 13658 } 13659 } finally { 13660 Binder.restoreCallingIdentity(callingId); 13661 } 13662 } 13663 13664 /** 13665 * @hide 13666 */ 13667 @Override 13668 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13669 int installReason) { 13670 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13671 null); 13672 PackageSetting pkgSetting; 13673 final int callingUid = Binder.getCallingUid(); 13674 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13675 true /* requireFullPermission */, true /* checkShell */, 13676 "installExistingPackage for user " + userId); 13677 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13678 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13679 } 13680 13681 long callingId = Binder.clearCallingIdentity(); 13682 try { 13683 boolean installed = false; 13684 final boolean instantApp = 13685 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13686 final boolean fullApp = 13687 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13688 13689 // writer 13690 synchronized (mPackages) { 13691 pkgSetting = mSettings.mPackages.get(packageName); 13692 if (pkgSetting == null) { 13693 return PackageManager.INSTALL_FAILED_INVALID_URI; 13694 } 13695 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 13696 // only allow the existing package to be used if it's installed as a full 13697 // application for at least one user 13698 boolean installAllowed = false; 13699 for (int checkUserId : sUserManager.getUserIds()) { 13700 installAllowed = !pkgSetting.getInstantApp(checkUserId); 13701 if (installAllowed) { 13702 break; 13703 } 13704 } 13705 if (!installAllowed) { 13706 return PackageManager.INSTALL_FAILED_INVALID_URI; 13707 } 13708 } 13709 if (!pkgSetting.getInstalled(userId)) { 13710 pkgSetting.setInstalled(true, userId); 13711 pkgSetting.setHidden(false, userId); 13712 pkgSetting.setInstallReason(installReason, userId); 13713 mSettings.writePackageRestrictionsLPr(userId); 13714 mSettings.writeKernelMappingLPr(pkgSetting); 13715 installed = true; 13716 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13717 // upgrade app from instant to full; we don't allow app downgrade 13718 installed = true; 13719 } 13720 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13721 } 13722 13723 if (installed) { 13724 if (pkgSetting.pkg != null) { 13725 synchronized (mInstallLock) { 13726 // We don't need to freeze for a brand new install 13727 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13728 } 13729 } 13730 sendPackageAddedForUser(packageName, pkgSetting, userId); 13731 synchronized (mPackages) { 13732 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 13733 } 13734 } 13735 } finally { 13736 Binder.restoreCallingIdentity(callingId); 13737 } 13738 13739 return PackageManager.INSTALL_SUCCEEDED; 13740 } 13741 13742 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13743 boolean instantApp, boolean fullApp) { 13744 // no state specified; do nothing 13745 if (!instantApp && !fullApp) { 13746 return; 13747 } 13748 if (userId != UserHandle.USER_ALL) { 13749 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13750 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13751 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13752 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13753 } 13754 } else { 13755 for (int currentUserId : sUserManager.getUserIds()) { 13756 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13757 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13758 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13759 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13760 } 13761 } 13762 } 13763 } 13764 13765 boolean isUserRestricted(int userId, String restrictionKey) { 13766 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13767 if (restrictions.getBoolean(restrictionKey, false)) { 13768 Log.w(TAG, "User is restricted: " + restrictionKey); 13769 return true; 13770 } 13771 return false; 13772 } 13773 13774 @Override 13775 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13776 int userId) { 13777 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13778 final int callingUid = Binder.getCallingUid(); 13779 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13780 true /* requireFullPermission */, true /* checkShell */, 13781 "setPackagesSuspended for user " + userId); 13782 13783 if (ArrayUtils.isEmpty(packageNames)) { 13784 return packageNames; 13785 } 13786 13787 // List of package names for whom the suspended state has changed. 13788 List<String> changedPackages = new ArrayList<>(packageNames.length); 13789 // List of package names for whom the suspended state is not set as requested in this 13790 // method. 13791 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13792 long callingId = Binder.clearCallingIdentity(); 13793 try { 13794 for (int i = 0; i < packageNames.length; i++) { 13795 String packageName = packageNames[i]; 13796 boolean changed = false; 13797 final int appId; 13798 synchronized (mPackages) { 13799 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13800 if (pkgSetting == null 13801 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13802 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13803 + "\". Skipping suspending/un-suspending."); 13804 unactionedPackages.add(packageName); 13805 continue; 13806 } 13807 appId = pkgSetting.appId; 13808 if (pkgSetting.getSuspended(userId) != suspended) { 13809 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13810 unactionedPackages.add(packageName); 13811 continue; 13812 } 13813 pkgSetting.setSuspended(suspended, userId); 13814 mSettings.writePackageRestrictionsLPr(userId); 13815 changed = true; 13816 changedPackages.add(packageName); 13817 } 13818 } 13819 13820 if (changed && suspended) { 13821 killApplication(packageName, UserHandle.getUid(userId, appId), 13822 "suspending package"); 13823 } 13824 } 13825 } finally { 13826 Binder.restoreCallingIdentity(callingId); 13827 } 13828 13829 if (!changedPackages.isEmpty()) { 13830 sendPackagesSuspendedForUser(changedPackages.toArray( 13831 new String[changedPackages.size()]), userId, suspended); 13832 } 13833 13834 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13835 } 13836 13837 @Override 13838 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13839 final int callingUid = Binder.getCallingUid(); 13840 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13841 true /* requireFullPermission */, false /* checkShell */, 13842 "isPackageSuspendedForUser for user " + userId); 13843 synchronized (mPackages) { 13844 final PackageSetting ps = mSettings.mPackages.get(packageName); 13845 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 13846 throw new IllegalArgumentException("Unknown target package: " + packageName); 13847 } 13848 return ps.getSuspended(userId); 13849 } 13850 } 13851 13852 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13853 if (isPackageDeviceAdmin(packageName, userId)) { 13854 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13855 + "\": has an active device admin"); 13856 return false; 13857 } 13858 13859 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13860 if (packageName.equals(activeLauncherPackageName)) { 13861 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13862 + "\": contains the active launcher"); 13863 return false; 13864 } 13865 13866 if (packageName.equals(mRequiredInstallerPackage)) { 13867 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13868 + "\": required for package installation"); 13869 return false; 13870 } 13871 13872 if (packageName.equals(mRequiredUninstallerPackage)) { 13873 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13874 + "\": required for package uninstallation"); 13875 return false; 13876 } 13877 13878 if (packageName.equals(mRequiredVerifierPackage)) { 13879 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13880 + "\": required for package verification"); 13881 return false; 13882 } 13883 13884 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13885 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13886 + "\": is the default dialer"); 13887 return false; 13888 } 13889 13890 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13891 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13892 + "\": protected package"); 13893 return false; 13894 } 13895 13896 // Cannot suspend static shared libs as they are considered 13897 // a part of the using app (emulating static linking). Also 13898 // static libs are installed always on internal storage. 13899 PackageParser.Package pkg = mPackages.get(packageName); 13900 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13901 Slog.w(TAG, "Cannot suspend package: " + packageName 13902 + " providing static shared library: " 13903 + pkg.staticSharedLibName); 13904 return false; 13905 } 13906 13907 return true; 13908 } 13909 13910 private String getActiveLauncherPackageName(int userId) { 13911 Intent intent = new Intent(Intent.ACTION_MAIN); 13912 intent.addCategory(Intent.CATEGORY_HOME); 13913 ResolveInfo resolveInfo = resolveIntent( 13914 intent, 13915 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13916 PackageManager.MATCH_DEFAULT_ONLY, 13917 userId); 13918 13919 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13920 } 13921 13922 private String getDefaultDialerPackageName(int userId) { 13923 synchronized (mPackages) { 13924 return mSettings.getDefaultDialerPackageNameLPw(userId); 13925 } 13926 } 13927 13928 @Override 13929 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13930 mContext.enforceCallingOrSelfPermission( 13931 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13932 "Only package verification agents can verify applications"); 13933 13934 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13935 final PackageVerificationResponse response = new PackageVerificationResponse( 13936 verificationCode, Binder.getCallingUid()); 13937 msg.arg1 = id; 13938 msg.obj = response; 13939 mHandler.sendMessage(msg); 13940 } 13941 13942 @Override 13943 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13944 long millisecondsToDelay) { 13945 mContext.enforceCallingOrSelfPermission( 13946 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13947 "Only package verification agents can extend verification timeouts"); 13948 13949 final PackageVerificationState state = mPendingVerification.get(id); 13950 final PackageVerificationResponse response = new PackageVerificationResponse( 13951 verificationCodeAtTimeout, Binder.getCallingUid()); 13952 13953 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13954 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13955 } 13956 if (millisecondsToDelay < 0) { 13957 millisecondsToDelay = 0; 13958 } 13959 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13960 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13961 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13962 } 13963 13964 if ((state != null) && !state.timeoutExtended()) { 13965 state.extendTimeout(); 13966 13967 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13968 msg.arg1 = id; 13969 msg.obj = response; 13970 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13971 } 13972 } 13973 13974 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13975 int verificationCode, UserHandle user) { 13976 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13977 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13978 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13979 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13980 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13981 13982 mContext.sendBroadcastAsUser(intent, user, 13983 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13984 } 13985 13986 private ComponentName matchComponentForVerifier(String packageName, 13987 List<ResolveInfo> receivers) { 13988 ActivityInfo targetReceiver = null; 13989 13990 final int NR = receivers.size(); 13991 for (int i = 0; i < NR; i++) { 13992 final ResolveInfo info = receivers.get(i); 13993 if (info.activityInfo == null) { 13994 continue; 13995 } 13996 13997 if (packageName.equals(info.activityInfo.packageName)) { 13998 targetReceiver = info.activityInfo; 13999 break; 14000 } 14001 } 14002 14003 if (targetReceiver == null) { 14004 return null; 14005 } 14006 14007 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 14008 } 14009 14010 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 14011 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 14012 if (pkgInfo.verifiers.length == 0) { 14013 return null; 14014 } 14015 14016 final int N = pkgInfo.verifiers.length; 14017 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 14018 for (int i = 0; i < N; i++) { 14019 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 14020 14021 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 14022 receivers); 14023 if (comp == null) { 14024 continue; 14025 } 14026 14027 final int verifierUid = getUidForVerifier(verifierInfo); 14028 if (verifierUid == -1) { 14029 continue; 14030 } 14031 14032 if (DEBUG_VERIFY) { 14033 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 14034 + " with the correct signature"); 14035 } 14036 sufficientVerifiers.add(comp); 14037 verificationState.addSufficientVerifier(verifierUid); 14038 } 14039 14040 return sufficientVerifiers; 14041 } 14042 14043 private int getUidForVerifier(VerifierInfo verifierInfo) { 14044 synchronized (mPackages) { 14045 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 14046 if (pkg == null) { 14047 return -1; 14048 } else if (pkg.mSigningDetails.signatures.length != 1) { 14049 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14050 + " has more than one signature; ignoring"); 14051 return -1; 14052 } 14053 14054 /* 14055 * If the public key of the package's signature does not match 14056 * our expected public key, then this is a different package and 14057 * we should skip. 14058 */ 14059 14060 final byte[] expectedPublicKey; 14061 try { 14062 final Signature verifierSig = pkg.mSigningDetails.signatures[0]; 14063 final PublicKey publicKey = verifierSig.getPublicKey(); 14064 expectedPublicKey = publicKey.getEncoded(); 14065 } catch (CertificateException e) { 14066 return -1; 14067 } 14068 14069 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 14070 14071 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 14072 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14073 + " does not have the expected public key; ignoring"); 14074 return -1; 14075 } 14076 14077 return pkg.applicationInfo.uid; 14078 } 14079 } 14080 14081 @Override 14082 public void finishPackageInstall(int token, boolean didLaunch) { 14083 enforceSystemOrRoot("Only the system is allowed to finish installs"); 14084 14085 if (DEBUG_INSTALL) { 14086 Slog.v(TAG, "BM finishing package install for " + token); 14087 } 14088 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14089 14090 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 14091 mHandler.sendMessage(msg); 14092 } 14093 14094 /** 14095 * Get the verification agent timeout. Used for both the APK verifier and the 14096 * intent filter verifier. 14097 * 14098 * @return verification timeout in milliseconds 14099 */ 14100 private long getVerificationTimeout() { 14101 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 14102 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 14103 DEFAULT_VERIFICATION_TIMEOUT); 14104 } 14105 14106 /** 14107 * Get the default verification agent response code. 14108 * 14109 * @return default verification response code 14110 */ 14111 private int getDefaultVerificationResponse(UserHandle user) { 14112 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 14113 return PackageManager.VERIFICATION_REJECT; 14114 } 14115 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14116 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 14117 DEFAULT_VERIFICATION_RESPONSE); 14118 } 14119 14120 /** 14121 * Check whether or not package verification has been enabled. 14122 * 14123 * @return true if verification should be performed 14124 */ 14125 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 14126 if (!DEFAULT_VERIFY_ENABLE) { 14127 return false; 14128 } 14129 14130 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14131 14132 // Check if installing from ADB 14133 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14134 // Do not run verification in a test harness environment 14135 if (ActivityManager.isRunningInTestHarness()) { 14136 return false; 14137 } 14138 if (ensureVerifyAppsEnabled) { 14139 return true; 14140 } 14141 // Check if the developer does not want package verification for ADB installs 14142 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14143 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14144 return false; 14145 } 14146 } else { 14147 // only when not installed from ADB, skip verification for instant apps when 14148 // the installer and verifier are the same. 14149 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14150 if (mInstantAppInstallerActivity != null 14151 && mInstantAppInstallerActivity.packageName.equals( 14152 mRequiredVerifierPackage)) { 14153 try { 14154 mContext.getSystemService(AppOpsManager.class) 14155 .checkPackage(installerUid, mRequiredVerifierPackage); 14156 if (DEBUG_VERIFY) { 14157 Slog.i(TAG, "disable verification for instant app"); 14158 } 14159 return false; 14160 } catch (SecurityException ignore) { } 14161 } 14162 } 14163 } 14164 14165 if (ensureVerifyAppsEnabled) { 14166 return true; 14167 } 14168 14169 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14170 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14171 } 14172 14173 @Override 14174 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14175 throws RemoteException { 14176 mContext.enforceCallingOrSelfPermission( 14177 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14178 "Only intentfilter verification agents can verify applications"); 14179 14180 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14181 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14182 Binder.getCallingUid(), verificationCode, failedDomains); 14183 msg.arg1 = id; 14184 msg.obj = response; 14185 mHandler.sendMessage(msg); 14186 } 14187 14188 @Override 14189 public int getIntentVerificationStatus(String packageName, int userId) { 14190 final int callingUid = Binder.getCallingUid(); 14191 if (UserHandle.getUserId(callingUid) != userId) { 14192 mContext.enforceCallingOrSelfPermission( 14193 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14194 "getIntentVerificationStatus" + userId); 14195 } 14196 if (getInstantAppPackageName(callingUid) != null) { 14197 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14198 } 14199 synchronized (mPackages) { 14200 final PackageSetting ps = mSettings.mPackages.get(packageName); 14201 if (ps == null 14202 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14203 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14204 } 14205 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14206 } 14207 } 14208 14209 @Override 14210 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14211 mContext.enforceCallingOrSelfPermission( 14212 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14213 14214 boolean result = false; 14215 synchronized (mPackages) { 14216 final PackageSetting ps = mSettings.mPackages.get(packageName); 14217 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14218 return false; 14219 } 14220 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14221 } 14222 if (result) { 14223 scheduleWritePackageRestrictionsLocked(userId); 14224 } 14225 return result; 14226 } 14227 14228 @Override 14229 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14230 String packageName) { 14231 final int callingUid = Binder.getCallingUid(); 14232 if (getInstantAppPackageName(callingUid) != null) { 14233 return ParceledListSlice.emptyList(); 14234 } 14235 synchronized (mPackages) { 14236 final PackageSetting ps = mSettings.mPackages.get(packageName); 14237 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14238 return ParceledListSlice.emptyList(); 14239 } 14240 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14241 } 14242 } 14243 14244 @Override 14245 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14246 if (TextUtils.isEmpty(packageName)) { 14247 return ParceledListSlice.emptyList(); 14248 } 14249 final int callingUid = Binder.getCallingUid(); 14250 final int callingUserId = UserHandle.getUserId(callingUid); 14251 synchronized (mPackages) { 14252 PackageParser.Package pkg = mPackages.get(packageName); 14253 if (pkg == null || pkg.activities == null) { 14254 return ParceledListSlice.emptyList(); 14255 } 14256 if (pkg.mExtras == null) { 14257 return ParceledListSlice.emptyList(); 14258 } 14259 final PackageSetting ps = (PackageSetting) pkg.mExtras; 14260 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 14261 return ParceledListSlice.emptyList(); 14262 } 14263 final int count = pkg.activities.size(); 14264 ArrayList<IntentFilter> result = new ArrayList<>(); 14265 for (int n=0; n<count; n++) { 14266 PackageParser.Activity activity = pkg.activities.get(n); 14267 if (activity.intents != null && activity.intents.size() > 0) { 14268 result.addAll(activity.intents); 14269 } 14270 } 14271 return new ParceledListSlice<>(result); 14272 } 14273 } 14274 14275 @Override 14276 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14277 mContext.enforceCallingOrSelfPermission( 14278 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14279 if (UserHandle.getCallingUserId() != userId) { 14280 mContext.enforceCallingOrSelfPermission( 14281 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14282 } 14283 14284 synchronized (mPackages) { 14285 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14286 if (packageName != null) { 14287 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser( 14288 packageName, userId); 14289 } 14290 return result; 14291 } 14292 } 14293 14294 @Override 14295 public String getDefaultBrowserPackageName(int userId) { 14296 if (UserHandle.getCallingUserId() != userId) { 14297 mContext.enforceCallingOrSelfPermission( 14298 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14299 } 14300 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14301 return null; 14302 } 14303 synchronized (mPackages) { 14304 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14305 } 14306 } 14307 14308 /** 14309 * Get the "allow unknown sources" setting. 14310 * 14311 * @return the current "allow unknown sources" setting 14312 */ 14313 private int getUnknownSourcesSettings() { 14314 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14315 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14316 -1); 14317 } 14318 14319 @Override 14320 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14321 final int callingUid = Binder.getCallingUid(); 14322 if (getInstantAppPackageName(callingUid) != null) { 14323 return; 14324 } 14325 // writer 14326 synchronized (mPackages) { 14327 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14328 if (targetPackageSetting == null 14329 || filterAppAccessLPr( 14330 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 14331 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14332 } 14333 14334 PackageSetting installerPackageSetting; 14335 if (installerPackageName != null) { 14336 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14337 if (installerPackageSetting == null) { 14338 throw new IllegalArgumentException("Unknown installer package: " 14339 + installerPackageName); 14340 } 14341 } else { 14342 installerPackageSetting = null; 14343 } 14344 14345 Signature[] callerSignature; 14346 Object obj = mSettings.getUserIdLPr(callingUid); 14347 if (obj != null) { 14348 if (obj instanceof SharedUserSetting) { 14349 callerSignature = 14350 ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 14351 } else if (obj instanceof PackageSetting) { 14352 callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures; 14353 } else { 14354 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 14355 } 14356 } else { 14357 throw new SecurityException("Unknown calling UID: " + callingUid); 14358 } 14359 14360 // Verify: can't set installerPackageName to a package that is 14361 // not signed with the same cert as the caller. 14362 if (installerPackageSetting != null) { 14363 if (compareSignatures(callerSignature, 14364 installerPackageSetting.signatures.mSigningDetails.signatures) 14365 != PackageManager.SIGNATURE_MATCH) { 14366 throw new SecurityException( 14367 "Caller does not have same cert as new installer package " 14368 + installerPackageName); 14369 } 14370 } 14371 14372 // Verify: if target already has an installer package, it must 14373 // be signed with the same cert as the caller. 14374 if (targetPackageSetting.installerPackageName != null) { 14375 PackageSetting setting = mSettings.mPackages.get( 14376 targetPackageSetting.installerPackageName); 14377 // If the currently set package isn't valid, then it's always 14378 // okay to change it. 14379 if (setting != null) { 14380 if (compareSignatures(callerSignature, 14381 setting.signatures.mSigningDetails.signatures) 14382 != PackageManager.SIGNATURE_MATCH) { 14383 throw new SecurityException( 14384 "Caller does not have same cert as old installer package " 14385 + targetPackageSetting.installerPackageName); 14386 } 14387 } 14388 } 14389 14390 // Okay! 14391 targetPackageSetting.installerPackageName = installerPackageName; 14392 if (installerPackageName != null) { 14393 mSettings.mInstallerPackages.add(installerPackageName); 14394 } 14395 scheduleWriteSettingsLocked(); 14396 } 14397 } 14398 14399 @Override 14400 public void setApplicationCategoryHint(String packageName, int categoryHint, 14401 String callerPackageName) { 14402 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14403 throw new SecurityException("Instant applications don't have access to this method"); 14404 } 14405 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14406 callerPackageName); 14407 synchronized (mPackages) { 14408 PackageSetting ps = mSettings.mPackages.get(packageName); 14409 if (ps == null) { 14410 throw new IllegalArgumentException("Unknown target package " + packageName); 14411 } 14412 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14413 throw new IllegalArgumentException("Unknown target package " + packageName); 14414 } 14415 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14416 throw new IllegalArgumentException("Calling package " + callerPackageName 14417 + " is not installer for " + packageName); 14418 } 14419 14420 if (ps.categoryHint != categoryHint) { 14421 ps.categoryHint = categoryHint; 14422 scheduleWriteSettingsLocked(); 14423 } 14424 } 14425 } 14426 14427 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14428 // Queue up an async operation since the package installation may take a little while. 14429 mHandler.post(new Runnable() { 14430 public void run() { 14431 mHandler.removeCallbacks(this); 14432 // Result object to be returned 14433 PackageInstalledInfo res = new PackageInstalledInfo(); 14434 res.setReturnCode(currentStatus); 14435 res.uid = -1; 14436 res.pkg = null; 14437 res.removedInfo = null; 14438 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14439 args.doPreInstall(res.returnCode); 14440 synchronized (mInstallLock) { 14441 installPackageTracedLI(args, res); 14442 } 14443 args.doPostInstall(res.returnCode, res.uid); 14444 } 14445 14446 // A restore should be performed at this point if (a) the install 14447 // succeeded, (b) the operation is not an update, and (c) the new 14448 // package has not opted out of backup participation. 14449 final boolean update = res.removedInfo != null 14450 && res.removedInfo.removedPackage != null; 14451 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14452 boolean doRestore = !update 14453 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14454 14455 // Set up the post-install work request bookkeeping. This will be used 14456 // and cleaned up by the post-install event handling regardless of whether 14457 // there's a restore pass performed. Token values are >= 1. 14458 int token; 14459 if (mNextInstallToken < 0) mNextInstallToken = 1; 14460 token = mNextInstallToken++; 14461 14462 PostInstallData data = new PostInstallData(args, res); 14463 mRunningInstalls.put(token, data); 14464 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14465 14466 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14467 // Pass responsibility to the Backup Manager. It will perform a 14468 // restore if appropriate, then pass responsibility back to the 14469 // Package Manager to run the post-install observer callbacks 14470 // and broadcasts. 14471 IBackupManager bm = IBackupManager.Stub.asInterface( 14472 ServiceManager.getService(Context.BACKUP_SERVICE)); 14473 if (bm != null) { 14474 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14475 + " to BM for possible restore"); 14476 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14477 try { 14478 // TODO: http://b/22388012 14479 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14480 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14481 } else { 14482 doRestore = false; 14483 } 14484 } catch (RemoteException e) { 14485 // can't happen; the backup manager is local 14486 } catch (Exception e) { 14487 Slog.e(TAG, "Exception trying to enqueue restore", e); 14488 doRestore = false; 14489 } 14490 } else { 14491 Slog.e(TAG, "Backup Manager not found!"); 14492 doRestore = false; 14493 } 14494 } 14495 14496 if (!doRestore) { 14497 // No restore possible, or the Backup Manager was mysteriously not 14498 // available -- just fire the post-install work request directly. 14499 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14500 14501 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14502 14503 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14504 mHandler.sendMessage(msg); 14505 } 14506 } 14507 }); 14508 } 14509 14510 /** 14511 * Callback from PackageSettings whenever an app is first transitioned out of the 14512 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14513 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14514 * here whether the app is the target of an ongoing install, and only send the 14515 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14516 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14517 * handling. 14518 */ 14519 void notifyFirstLaunch(final String packageName, final String installerPackage, 14520 final int userId) { 14521 // Serialize this with the rest of the install-process message chain. In the 14522 // restore-at-install case, this Runnable will necessarily run before the 14523 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14524 // are coherent. In the non-restore case, the app has already completed install 14525 // and been launched through some other means, so it is not in a problematic 14526 // state for observers to see the FIRST_LAUNCH signal. 14527 mHandler.post(new Runnable() { 14528 @Override 14529 public void run() { 14530 for (int i = 0; i < mRunningInstalls.size(); i++) { 14531 final PostInstallData data = mRunningInstalls.valueAt(i); 14532 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14533 continue; 14534 } 14535 if (packageName.equals(data.res.pkg.applicationInfo.packageName)) { 14536 // right package; but is it for the right user? 14537 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14538 if (userId == data.res.newUsers[uIndex]) { 14539 if (DEBUG_BACKUP) { 14540 Slog.i(TAG, "Package " + packageName 14541 + " being restored so deferring FIRST_LAUNCH"); 14542 } 14543 return; 14544 } 14545 } 14546 } 14547 } 14548 // didn't find it, so not being restored 14549 if (DEBUG_BACKUP) { 14550 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH"); 14551 } 14552 final boolean isInstantApp = isInstantApp(packageName, userId); 14553 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 14554 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 14555 sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds); 14556 } 14557 }); 14558 } 14559 14560 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, 14561 int[] userIds, int[] instantUserIds) { 14562 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14563 installerPkg, null, userIds, instantUserIds); 14564 } 14565 14566 private abstract class HandlerParams { 14567 private static final int MAX_RETRIES = 4; 14568 14569 /** 14570 * Number of times startCopy() has been attempted and had a non-fatal 14571 * error. 14572 */ 14573 private int mRetries = 0; 14574 14575 /** User handle for the user requesting the information or installation. */ 14576 private final UserHandle mUser; 14577 String traceMethod; 14578 int traceCookie; 14579 14580 HandlerParams(UserHandle user) { 14581 mUser = user; 14582 } 14583 14584 UserHandle getUser() { 14585 return mUser; 14586 } 14587 14588 HandlerParams setTraceMethod(String traceMethod) { 14589 this.traceMethod = traceMethod; 14590 return this; 14591 } 14592 14593 HandlerParams setTraceCookie(int traceCookie) { 14594 this.traceCookie = traceCookie; 14595 return this; 14596 } 14597 14598 final boolean startCopy() { 14599 boolean res; 14600 try { 14601 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14602 14603 if (++mRetries > MAX_RETRIES) { 14604 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14605 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14606 handleServiceError(); 14607 return false; 14608 } else { 14609 handleStartCopy(); 14610 res = true; 14611 } 14612 } catch (RemoteException e) { 14613 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14614 mHandler.sendEmptyMessage(MCS_RECONNECT); 14615 res = false; 14616 } 14617 handleReturnCode(); 14618 return res; 14619 } 14620 14621 final void serviceError() { 14622 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14623 handleServiceError(); 14624 handleReturnCode(); 14625 } 14626 14627 abstract void handleStartCopy() throws RemoteException; 14628 abstract void handleServiceError(); 14629 abstract void handleReturnCode(); 14630 } 14631 14632 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14633 for (File path : paths) { 14634 try { 14635 mcs.clearDirectory(path.getAbsolutePath()); 14636 } catch (RemoteException e) { 14637 } 14638 } 14639 } 14640 14641 static class OriginInfo { 14642 /** 14643 * Location where install is coming from, before it has been 14644 * copied/renamed into place. This could be a single monolithic APK 14645 * file, or a cluster directory. This location may be untrusted. 14646 */ 14647 final File file; 14648 14649 /** 14650 * Flag indicating that {@link #file} or {@link #cid} has already been 14651 * staged, meaning downstream users don't need to defensively copy the 14652 * contents. 14653 */ 14654 final boolean staged; 14655 14656 /** 14657 * Flag indicating that {@link #file} or {@link #cid} is an already 14658 * installed app that is being moved. 14659 */ 14660 final boolean existing; 14661 14662 final String resolvedPath; 14663 final File resolvedFile; 14664 14665 static OriginInfo fromNothing() { 14666 return new OriginInfo(null, false, false); 14667 } 14668 14669 static OriginInfo fromUntrustedFile(File file) { 14670 return new OriginInfo(file, false, false); 14671 } 14672 14673 static OriginInfo fromExistingFile(File file) { 14674 return new OriginInfo(file, false, true); 14675 } 14676 14677 static OriginInfo fromStagedFile(File file) { 14678 return new OriginInfo(file, true, false); 14679 } 14680 14681 private OriginInfo(File file, boolean staged, boolean existing) { 14682 this.file = file; 14683 this.staged = staged; 14684 this.existing = existing; 14685 14686 if (file != null) { 14687 resolvedPath = file.getAbsolutePath(); 14688 resolvedFile = file; 14689 } else { 14690 resolvedPath = null; 14691 resolvedFile = null; 14692 } 14693 } 14694 } 14695 14696 static class MoveInfo { 14697 final int moveId; 14698 final String fromUuid; 14699 final String toUuid; 14700 final String packageName; 14701 final String dataAppName; 14702 final int appId; 14703 final String seinfo; 14704 final int targetSdkVersion; 14705 14706 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14707 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14708 this.moveId = moveId; 14709 this.fromUuid = fromUuid; 14710 this.toUuid = toUuid; 14711 this.packageName = packageName; 14712 this.dataAppName = dataAppName; 14713 this.appId = appId; 14714 this.seinfo = seinfo; 14715 this.targetSdkVersion = targetSdkVersion; 14716 } 14717 } 14718 14719 static class VerificationInfo { 14720 /** A constant used to indicate that a uid value is not present. */ 14721 public static final int NO_UID = -1; 14722 14723 /** URI referencing where the package was downloaded from. */ 14724 final Uri originatingUri; 14725 14726 /** HTTP referrer URI associated with the originatingURI. */ 14727 final Uri referrer; 14728 14729 /** UID of the application that the install request originated from. */ 14730 final int originatingUid; 14731 14732 /** UID of application requesting the install */ 14733 final int installerUid; 14734 14735 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14736 this.originatingUri = originatingUri; 14737 this.referrer = referrer; 14738 this.originatingUid = originatingUid; 14739 this.installerUid = installerUid; 14740 } 14741 } 14742 14743 class InstallParams extends HandlerParams { 14744 final OriginInfo origin; 14745 final MoveInfo move; 14746 final IPackageInstallObserver2 observer; 14747 int installFlags; 14748 final String installerPackageName; 14749 final String volumeUuid; 14750 private InstallArgs mArgs; 14751 private int mRet; 14752 final String packageAbiOverride; 14753 final String[] grantedRuntimePermissions; 14754 final VerificationInfo verificationInfo; 14755 final PackageParser.SigningDetails signingDetails; 14756 final int installReason; 14757 14758 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14759 int installFlags, String installerPackageName, String volumeUuid, 14760 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14761 String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) { 14762 super(user); 14763 this.origin = origin; 14764 this.move = move; 14765 this.observer = observer; 14766 this.installFlags = installFlags; 14767 this.installerPackageName = installerPackageName; 14768 this.volumeUuid = volumeUuid; 14769 this.verificationInfo = verificationInfo; 14770 this.packageAbiOverride = packageAbiOverride; 14771 this.grantedRuntimePermissions = grantedPermissions; 14772 this.signingDetails = signingDetails; 14773 this.installReason = installReason; 14774 } 14775 14776 @Override 14777 public String toString() { 14778 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14779 + " file=" + origin.file + "}"; 14780 } 14781 14782 private int installLocationPolicy(PackageInfoLite pkgLite) { 14783 String packageName = pkgLite.packageName; 14784 int installLocation = pkgLite.installLocation; 14785 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14786 // reader 14787 synchronized (mPackages) { 14788 // Currently installed package which the new package is attempting to replace or 14789 // null if no such package is installed. 14790 PackageParser.Package installedPkg = mPackages.get(packageName); 14791 // Package which currently owns the data which the new package will own if installed. 14792 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14793 // will be null whereas dataOwnerPkg will contain information about the package 14794 // which was uninstalled while keeping its data. 14795 PackageParser.Package dataOwnerPkg = installedPkg; 14796 if (dataOwnerPkg == null) { 14797 PackageSetting ps = mSettings.mPackages.get(packageName); 14798 if (ps != null) { 14799 dataOwnerPkg = ps.pkg; 14800 } 14801 } 14802 14803 if (dataOwnerPkg != null) { 14804 // If installed, the package will get access to data left on the device by its 14805 // predecessor. As a security measure, this is permited only if this is not a 14806 // version downgrade or if the predecessor package is marked as debuggable and 14807 // a downgrade is explicitly requested. 14808 // 14809 // On debuggable platform builds, downgrades are permitted even for 14810 // non-debuggable packages to make testing easier. Debuggable platform builds do 14811 // not offer security guarantees and thus it's OK to disable some security 14812 // mechanisms to make debugging/testing easier on those builds. However, even on 14813 // debuggable builds downgrades of packages are permitted only if requested via 14814 // installFlags. This is because we aim to keep the behavior of debuggable 14815 // platform builds as close as possible to the behavior of non-debuggable 14816 // platform builds. 14817 final boolean downgradeRequested = 14818 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14819 final boolean packageDebuggable = 14820 (dataOwnerPkg.applicationInfo.flags 14821 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14822 final boolean downgradePermitted = 14823 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14824 if (!downgradePermitted) { 14825 try { 14826 checkDowngrade(dataOwnerPkg, pkgLite); 14827 } catch (PackageManagerException e) { 14828 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14829 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14830 } 14831 } 14832 } 14833 14834 if (installedPkg != null) { 14835 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14836 // Check for updated system application. 14837 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14838 if (onSd) { 14839 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14840 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14841 } 14842 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14843 } else { 14844 if (onSd) { 14845 // Install flag overrides everything. 14846 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14847 } 14848 // If current upgrade specifies particular preference 14849 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14850 // Application explicitly specified internal. 14851 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14852 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14853 // App explictly prefers external. Let policy decide 14854 } else { 14855 // Prefer previous location 14856 if (isExternal(installedPkg)) { 14857 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14858 } 14859 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14860 } 14861 } 14862 } else { 14863 // Invalid install. Return error code 14864 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14865 } 14866 } 14867 } 14868 // All the special cases have been taken care of. 14869 // Return result based on recommended install location. 14870 if (onSd) { 14871 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14872 } 14873 return pkgLite.recommendedInstallLocation; 14874 } 14875 14876 /* 14877 * Invoke remote method to get package information and install 14878 * location values. Override install location based on default 14879 * policy if needed and then create install arguments based 14880 * on the install location. 14881 */ 14882 public void handleStartCopy() throws RemoteException { 14883 int ret = PackageManager.INSTALL_SUCCEEDED; 14884 14885 // If we're already staged, we've firmly committed to an install location 14886 if (origin.staged) { 14887 if (origin.file != null) { 14888 installFlags |= PackageManager.INSTALL_INTERNAL; 14889 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14890 } else { 14891 throw new IllegalStateException("Invalid stage location"); 14892 } 14893 } 14894 14895 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14896 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14897 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14898 PackageInfoLite pkgLite = null; 14899 14900 if (onInt && onSd) { 14901 // Check if both bits are set. 14902 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14903 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14904 } else if (onSd && ephemeral) { 14905 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14906 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14907 } else { 14908 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14909 packageAbiOverride); 14910 14911 if (DEBUG_EPHEMERAL && ephemeral) { 14912 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14913 } 14914 14915 /* 14916 * If we have too little free space, try to free cache 14917 * before giving up. 14918 */ 14919 if (!origin.staged && pkgLite.recommendedInstallLocation 14920 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14921 // TODO: focus freeing disk space on the target device 14922 final StorageManager storage = StorageManager.from(mContext); 14923 final long lowThreshold = storage.getStorageLowBytes( 14924 Environment.getDataDirectory()); 14925 14926 final long sizeBytes = mContainerService.calculateInstalledSize( 14927 origin.resolvedPath, packageAbiOverride); 14928 14929 try { 14930 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 14931 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14932 installFlags, packageAbiOverride); 14933 } catch (InstallerException e) { 14934 Slog.w(TAG, "Failed to free cache", e); 14935 } 14936 14937 /* 14938 * The cache free must have deleted the file we 14939 * downloaded to install. 14940 * 14941 * TODO: fix the "freeCache" call to not delete 14942 * the file we care about. 14943 */ 14944 if (pkgLite.recommendedInstallLocation 14945 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14946 pkgLite.recommendedInstallLocation 14947 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14948 } 14949 } 14950 } 14951 14952 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14953 int loc = pkgLite.recommendedInstallLocation; 14954 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14955 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14956 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14957 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14958 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14959 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14960 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14961 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14962 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14963 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14964 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14965 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14966 } else { 14967 // Override with defaults if needed. 14968 loc = installLocationPolicy(pkgLite); 14969 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14970 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14971 } else if (!onSd && !onInt) { 14972 // Override install location with flags 14973 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14974 // Set the flag to install on external media. 14975 installFlags |= PackageManager.INSTALL_EXTERNAL; 14976 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14977 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14978 if (DEBUG_EPHEMERAL) { 14979 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14980 } 14981 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14982 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14983 |PackageManager.INSTALL_INTERNAL); 14984 } else { 14985 // Make sure the flag for installing on external 14986 // media is unset 14987 installFlags |= PackageManager.INSTALL_INTERNAL; 14988 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14989 } 14990 } 14991 } 14992 } 14993 14994 final InstallArgs args = createInstallArgs(this); 14995 mArgs = args; 14996 14997 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14998 // TODO: http://b/22976637 14999 // Apps installed for "all" users use the device owner to verify the app 15000 UserHandle verifierUser = getUser(); 15001 if (verifierUser == UserHandle.ALL) { 15002 verifierUser = UserHandle.SYSTEM; 15003 } 15004 15005 /* 15006 * Determine if we have any installed package verifiers. If we 15007 * do, then we'll defer to them to verify the packages. 15008 */ 15009 final int requiredUid = mRequiredVerifierPackage == null ? -1 15010 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15011 verifierUser.getIdentifier()); 15012 final int installerUid = 15013 verificationInfo == null ? -1 : verificationInfo.installerUid; 15014 if (!origin.existing && requiredUid != -1 15015 && isVerificationEnabled( 15016 verifierUser.getIdentifier(), installFlags, installerUid)) { 15017 final Intent verification = new Intent( 15018 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 15019 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 15020 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 15021 PACKAGE_MIME_TYPE); 15022 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15023 15024 // Query all live verifiers based on current user state 15025 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 15026 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 15027 false /*allowDynamicSplits*/); 15028 15029 if (DEBUG_VERIFY) { 15030 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 15031 + verification.toString() + " with " + pkgLite.verifiers.length 15032 + " optional verifiers"); 15033 } 15034 15035 final int verificationId = mPendingVerificationToken++; 15036 15037 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 15038 15039 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 15040 installerPackageName); 15041 15042 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 15043 installFlags); 15044 15045 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 15046 pkgLite.packageName); 15047 15048 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 15049 pkgLite.versionCode); 15050 15051 verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE, 15052 pkgLite.getLongVersionCode()); 15053 15054 if (verificationInfo != null) { 15055 if (verificationInfo.originatingUri != null) { 15056 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 15057 verificationInfo.originatingUri); 15058 } 15059 if (verificationInfo.referrer != null) { 15060 verification.putExtra(Intent.EXTRA_REFERRER, 15061 verificationInfo.referrer); 15062 } 15063 if (verificationInfo.originatingUid >= 0) { 15064 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 15065 verificationInfo.originatingUid); 15066 } 15067 if (verificationInfo.installerUid >= 0) { 15068 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 15069 verificationInfo.installerUid); 15070 } 15071 } 15072 15073 final PackageVerificationState verificationState = new PackageVerificationState( 15074 requiredUid, args); 15075 15076 mPendingVerification.append(verificationId, verificationState); 15077 15078 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 15079 receivers, verificationState); 15080 15081 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 15082 final long idleDuration = getVerificationTimeout(); 15083 15084 /* 15085 * If any sufficient verifiers were listed in the package 15086 * manifest, attempt to ask them. 15087 */ 15088 if (sufficientVerifiers != null) { 15089 final int N = sufficientVerifiers.size(); 15090 if (N == 0) { 15091 Slog.i(TAG, "Additional verifiers required, but none installed."); 15092 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 15093 } else { 15094 for (int i = 0; i < N; i++) { 15095 final ComponentName verifierComponent = sufficientVerifiers.get(i); 15096 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15097 verifierComponent.getPackageName(), idleDuration, 15098 verifierUser.getIdentifier(), false, "package verifier"); 15099 15100 final Intent sufficientIntent = new Intent(verification); 15101 sufficientIntent.setComponent(verifierComponent); 15102 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 15103 } 15104 } 15105 } 15106 15107 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 15108 mRequiredVerifierPackage, receivers); 15109 if (ret == PackageManager.INSTALL_SUCCEEDED 15110 && mRequiredVerifierPackage != null) { 15111 Trace.asyncTraceBegin( 15112 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 15113 /* 15114 * Send the intent to the required verification agent, 15115 * but only start the verification timeout after the 15116 * target BroadcastReceivers have run. 15117 */ 15118 verification.setComponent(requiredVerifierComponent); 15119 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15120 mRequiredVerifierPackage, idleDuration, 15121 verifierUser.getIdentifier(), false, "package verifier"); 15122 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 15123 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15124 new BroadcastReceiver() { 15125 @Override 15126 public void onReceive(Context context, Intent intent) { 15127 final Message msg = mHandler 15128 .obtainMessage(CHECK_PENDING_VERIFICATION); 15129 msg.arg1 = verificationId; 15130 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15131 } 15132 }, null, 0, null, null); 15133 15134 /* 15135 * We don't want the copy to proceed until verification 15136 * succeeds, so null out this field. 15137 */ 15138 mArgs = null; 15139 } 15140 } else { 15141 /* 15142 * No package verification is enabled, so immediately start 15143 * the remote call to initiate copy using temporary file. 15144 */ 15145 ret = args.copyApk(mContainerService, true); 15146 } 15147 } 15148 15149 mRet = ret; 15150 } 15151 15152 @Override 15153 void handleReturnCode() { 15154 // If mArgs is null, then MCS couldn't be reached. When it 15155 // reconnects, it will try again to install. At that point, this 15156 // will succeed. 15157 if (mArgs != null) { 15158 processPendingInstall(mArgs, mRet); 15159 } 15160 } 15161 15162 @Override 15163 void handleServiceError() { 15164 mArgs = createInstallArgs(this); 15165 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15166 } 15167 } 15168 15169 private InstallArgs createInstallArgs(InstallParams params) { 15170 if (params.move != null) { 15171 return new MoveInstallArgs(params); 15172 } else { 15173 return new FileInstallArgs(params); 15174 } 15175 } 15176 15177 /** 15178 * Create args that describe an existing installed package. Typically used 15179 * when cleaning up old installs, or used as a move source. 15180 */ 15181 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 15182 String resourcePath, String[] instructionSets) { 15183 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15184 } 15185 15186 static abstract class InstallArgs { 15187 /** @see InstallParams#origin */ 15188 final OriginInfo origin; 15189 /** @see InstallParams#move */ 15190 final MoveInfo move; 15191 15192 final IPackageInstallObserver2 observer; 15193 // Always refers to PackageManager flags only 15194 final int installFlags; 15195 final String installerPackageName; 15196 final String volumeUuid; 15197 final UserHandle user; 15198 final String abiOverride; 15199 final String[] installGrantPermissions; 15200 /** If non-null, drop an async trace when the install completes */ 15201 final String traceMethod; 15202 final int traceCookie; 15203 final PackageParser.SigningDetails signingDetails; 15204 final int installReason; 15205 15206 // The list of instruction sets supported by this app. This is currently 15207 // only used during the rmdex() phase to clean up resources. We can get rid of this 15208 // if we move dex files under the common app path. 15209 /* nullable */ String[] instructionSets; 15210 15211 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15212 int installFlags, String installerPackageName, String volumeUuid, 15213 UserHandle user, String[] instructionSets, 15214 String abiOverride, String[] installGrantPermissions, 15215 String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails, 15216 int installReason) { 15217 this.origin = origin; 15218 this.move = move; 15219 this.installFlags = installFlags; 15220 this.observer = observer; 15221 this.installerPackageName = installerPackageName; 15222 this.volumeUuid = volumeUuid; 15223 this.user = user; 15224 this.instructionSets = instructionSets; 15225 this.abiOverride = abiOverride; 15226 this.installGrantPermissions = installGrantPermissions; 15227 this.traceMethod = traceMethod; 15228 this.traceCookie = traceCookie; 15229 this.signingDetails = signingDetails; 15230 this.installReason = installReason; 15231 } 15232 15233 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15234 abstract int doPreInstall(int status); 15235 15236 /** 15237 * Rename package into final resting place. All paths on the given 15238 * scanned package should be updated to reflect the rename. 15239 */ 15240 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15241 abstract int doPostInstall(int status, int uid); 15242 15243 /** @see PackageSettingBase#codePathString */ 15244 abstract String getCodePath(); 15245 /** @see PackageSettingBase#resourcePathString */ 15246 abstract String getResourcePath(); 15247 15248 // Need installer lock especially for dex file removal. 15249 abstract void cleanUpResourcesLI(); 15250 abstract boolean doPostDeleteLI(boolean delete); 15251 15252 /** 15253 * Called before the source arguments are copied. This is used mostly 15254 * for MoveParams when it needs to read the source file to put it in the 15255 * destination. 15256 */ 15257 int doPreCopy() { 15258 return PackageManager.INSTALL_SUCCEEDED; 15259 } 15260 15261 /** 15262 * Called after the source arguments are copied. This is used mostly for 15263 * MoveParams when it needs to read the source file to put it in the 15264 * destination. 15265 */ 15266 int doPostCopy(int uid) { 15267 return PackageManager.INSTALL_SUCCEEDED; 15268 } 15269 15270 protected boolean isFwdLocked() { 15271 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15272 } 15273 15274 protected boolean isExternalAsec() { 15275 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15276 } 15277 15278 protected boolean isEphemeral() { 15279 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15280 } 15281 15282 UserHandle getUser() { 15283 return user; 15284 } 15285 } 15286 15287 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15288 if (!allCodePaths.isEmpty()) { 15289 if (instructionSets == null) { 15290 throw new IllegalStateException("instructionSet == null"); 15291 } 15292 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15293 for (String codePath : allCodePaths) { 15294 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15295 try { 15296 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15297 } catch (InstallerException ignored) { 15298 } 15299 } 15300 } 15301 } 15302 } 15303 15304 /** 15305 * Logic to handle installation of non-ASEC applications, including copying 15306 * and renaming logic. 15307 */ 15308 class FileInstallArgs extends InstallArgs { 15309 private File codeFile; 15310 private File resourceFile; 15311 15312 // Example topology: 15313 // /data/app/com.example/base.apk 15314 // /data/app/com.example/split_foo.apk 15315 // /data/app/com.example/lib/arm/libfoo.so 15316 // /data/app/com.example/lib/arm64/libfoo.so 15317 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15318 15319 /** New install */ 15320 FileInstallArgs(InstallParams params) { 15321 super(params.origin, params.move, params.observer, params.installFlags, 15322 params.installerPackageName, params.volumeUuid, 15323 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15324 params.grantedRuntimePermissions, 15325 params.traceMethod, params.traceCookie, params.signingDetails, 15326 params.installReason); 15327 if (isFwdLocked()) { 15328 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15329 } 15330 } 15331 15332 /** Existing install */ 15333 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15334 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15335 null, null, null, 0, PackageParser.SigningDetails.UNKNOWN, 15336 PackageManager.INSTALL_REASON_UNKNOWN); 15337 this.codeFile = (codePath != null) ? new File(codePath) : null; 15338 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15339 } 15340 15341 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15342 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15343 try { 15344 return doCopyApk(imcs, temp); 15345 } finally { 15346 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15347 } 15348 } 15349 15350 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15351 if (origin.staged) { 15352 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15353 codeFile = origin.file; 15354 resourceFile = origin.file; 15355 return PackageManager.INSTALL_SUCCEEDED; 15356 } 15357 15358 try { 15359 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15360 final File tempDir = 15361 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15362 codeFile = tempDir; 15363 resourceFile = tempDir; 15364 } catch (IOException e) { 15365 Slog.w(TAG, "Failed to create copy file: " + e); 15366 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15367 } 15368 15369 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15370 @Override 15371 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15372 if (!FileUtils.isValidExtFilename(name)) { 15373 throw new IllegalArgumentException("Invalid filename: " + name); 15374 } 15375 try { 15376 final File file = new File(codeFile, name); 15377 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15378 O_RDWR | O_CREAT, 0644); 15379 Os.chmod(file.getAbsolutePath(), 0644); 15380 return new ParcelFileDescriptor(fd); 15381 } catch (ErrnoException e) { 15382 throw new RemoteException("Failed to open: " + e.getMessage()); 15383 } 15384 } 15385 }; 15386 15387 int ret = PackageManager.INSTALL_SUCCEEDED; 15388 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15389 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15390 Slog.e(TAG, "Failed to copy package"); 15391 return ret; 15392 } 15393 15394 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15395 NativeLibraryHelper.Handle handle = null; 15396 try { 15397 handle = NativeLibraryHelper.Handle.create(codeFile); 15398 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15399 abiOverride); 15400 } catch (IOException e) { 15401 Slog.e(TAG, "Copying native libraries failed", e); 15402 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15403 } finally { 15404 IoUtils.closeQuietly(handle); 15405 } 15406 15407 return ret; 15408 } 15409 15410 int doPreInstall(int status) { 15411 if (status != PackageManager.INSTALL_SUCCEEDED) { 15412 cleanUp(); 15413 } 15414 return status; 15415 } 15416 15417 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15418 if (status != PackageManager.INSTALL_SUCCEEDED) { 15419 cleanUp(); 15420 return false; 15421 } 15422 15423 final File targetDir = codeFile.getParentFile(); 15424 final File beforeCodeFile = codeFile; 15425 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15426 15427 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15428 try { 15429 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15430 } catch (ErrnoException e) { 15431 Slog.w(TAG, "Failed to rename", e); 15432 return false; 15433 } 15434 15435 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15436 Slog.w(TAG, "Failed to restorecon"); 15437 return false; 15438 } 15439 15440 // Reflect the rename internally 15441 codeFile = afterCodeFile; 15442 resourceFile = afterCodeFile; 15443 15444 // Reflect the rename in scanned details 15445 try { 15446 pkg.setCodePath(afterCodeFile.getCanonicalPath()); 15447 } catch (IOException e) { 15448 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e); 15449 return false; 15450 } 15451 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15452 afterCodeFile, pkg.baseCodePath)); 15453 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15454 afterCodeFile, pkg.splitCodePaths)); 15455 15456 // Reflect the rename in app info 15457 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15458 pkg.setApplicationInfoCodePath(pkg.codePath); 15459 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15460 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15461 pkg.setApplicationInfoResourcePath(pkg.codePath); 15462 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15463 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15464 15465 return true; 15466 } 15467 15468 int doPostInstall(int status, int uid) { 15469 if (status != PackageManager.INSTALL_SUCCEEDED) { 15470 cleanUp(); 15471 } 15472 return status; 15473 } 15474 15475 @Override 15476 String getCodePath() { 15477 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15478 } 15479 15480 @Override 15481 String getResourcePath() { 15482 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15483 } 15484 15485 private boolean cleanUp() { 15486 if (codeFile == null || !codeFile.exists()) { 15487 return false; 15488 } 15489 15490 removeCodePathLI(codeFile); 15491 15492 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15493 resourceFile.delete(); 15494 } 15495 15496 return true; 15497 } 15498 15499 void cleanUpResourcesLI() { 15500 // Try enumerating all code paths before deleting 15501 List<String> allCodePaths = Collections.EMPTY_LIST; 15502 if (codeFile != null && codeFile.exists()) { 15503 try { 15504 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15505 allCodePaths = pkg.getAllCodePaths(); 15506 } catch (PackageParserException e) { 15507 // Ignored; we tried our best 15508 } 15509 } 15510 15511 cleanUp(); 15512 removeDexFiles(allCodePaths, instructionSets); 15513 } 15514 15515 boolean doPostDeleteLI(boolean delete) { 15516 // XXX err, shouldn't we respect the delete flag? 15517 cleanUpResourcesLI(); 15518 return true; 15519 } 15520 } 15521 15522 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15523 PackageManagerException { 15524 if (copyRet < 0) { 15525 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15526 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15527 throw new PackageManagerException(copyRet, message); 15528 } 15529 } 15530 } 15531 15532 /** 15533 * Extract the StorageManagerService "container ID" from the full code path of an 15534 * .apk. 15535 */ 15536 static String cidFromCodePath(String fullCodePath) { 15537 int eidx = fullCodePath.lastIndexOf("/"); 15538 String subStr1 = fullCodePath.substring(0, eidx); 15539 int sidx = subStr1.lastIndexOf("/"); 15540 return subStr1.substring(sidx+1, eidx); 15541 } 15542 15543 /** 15544 * Logic to handle movement of existing installed applications. 15545 */ 15546 class MoveInstallArgs extends InstallArgs { 15547 private File codeFile; 15548 private File resourceFile; 15549 15550 /** New install */ 15551 MoveInstallArgs(InstallParams params) { 15552 super(params.origin, params.move, params.observer, params.installFlags, 15553 params.installerPackageName, params.volumeUuid, 15554 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15555 params.grantedRuntimePermissions, 15556 params.traceMethod, params.traceCookie, params.signingDetails, 15557 params.installReason); 15558 } 15559 15560 int copyApk(IMediaContainerService imcs, boolean temp) { 15561 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15562 + move.fromUuid + " to " + move.toUuid); 15563 synchronized (mInstaller) { 15564 try { 15565 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15566 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15567 } catch (InstallerException e) { 15568 Slog.w(TAG, "Failed to move app", e); 15569 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15570 } 15571 } 15572 15573 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15574 resourceFile = codeFile; 15575 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15576 15577 return PackageManager.INSTALL_SUCCEEDED; 15578 } 15579 15580 int doPreInstall(int status) { 15581 if (status != PackageManager.INSTALL_SUCCEEDED) { 15582 cleanUp(move.toUuid); 15583 } 15584 return status; 15585 } 15586 15587 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15588 if (status != PackageManager.INSTALL_SUCCEEDED) { 15589 cleanUp(move.toUuid); 15590 return false; 15591 } 15592 15593 // Reflect the move in app info 15594 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15595 pkg.setApplicationInfoCodePath(pkg.codePath); 15596 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15597 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15598 pkg.setApplicationInfoResourcePath(pkg.codePath); 15599 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15600 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15601 15602 return true; 15603 } 15604 15605 int doPostInstall(int status, int uid) { 15606 if (status == PackageManager.INSTALL_SUCCEEDED) { 15607 cleanUp(move.fromUuid); 15608 } else { 15609 cleanUp(move.toUuid); 15610 } 15611 return status; 15612 } 15613 15614 @Override 15615 String getCodePath() { 15616 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15617 } 15618 15619 @Override 15620 String getResourcePath() { 15621 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15622 } 15623 15624 private boolean cleanUp(String volumeUuid) { 15625 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15626 move.dataAppName); 15627 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15628 final int[] userIds = sUserManager.getUserIds(); 15629 synchronized (mInstallLock) { 15630 // Clean up both app data and code 15631 // All package moves are frozen until finished 15632 for (int userId : userIds) { 15633 try { 15634 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15635 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15636 } catch (InstallerException e) { 15637 Slog.w(TAG, String.valueOf(e)); 15638 } 15639 } 15640 removeCodePathLI(codeFile); 15641 } 15642 return true; 15643 } 15644 15645 void cleanUpResourcesLI() { 15646 throw new UnsupportedOperationException(); 15647 } 15648 15649 boolean doPostDeleteLI(boolean delete) { 15650 throw new UnsupportedOperationException(); 15651 } 15652 } 15653 15654 static String getAsecPackageName(String packageCid) { 15655 int idx = packageCid.lastIndexOf("-"); 15656 if (idx == -1) { 15657 return packageCid; 15658 } 15659 return packageCid.substring(0, idx); 15660 } 15661 15662 // Utility method used to create code paths based on package name and available index. 15663 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15664 String idxStr = ""; 15665 int idx = 1; 15666 // Fall back to default value of idx=1 if prefix is not 15667 // part of oldCodePath 15668 if (oldCodePath != null) { 15669 String subStr = oldCodePath; 15670 // Drop the suffix right away 15671 if (suffix != null && subStr.endsWith(suffix)) { 15672 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15673 } 15674 // If oldCodePath already contains prefix find out the 15675 // ending index to either increment or decrement. 15676 int sidx = subStr.lastIndexOf(prefix); 15677 if (sidx != -1) { 15678 subStr = subStr.substring(sidx + prefix.length()); 15679 if (subStr != null) { 15680 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15681 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15682 } 15683 try { 15684 idx = Integer.parseInt(subStr); 15685 if (idx <= 1) { 15686 idx++; 15687 } else { 15688 idx--; 15689 } 15690 } catch(NumberFormatException e) { 15691 } 15692 } 15693 } 15694 } 15695 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15696 return prefix + idxStr; 15697 } 15698 15699 private File getNextCodePath(File targetDir, String packageName) { 15700 File result; 15701 SecureRandom random = new SecureRandom(); 15702 byte[] bytes = new byte[16]; 15703 do { 15704 random.nextBytes(bytes); 15705 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15706 result = new File(targetDir, packageName + "-" + suffix); 15707 } while (result.exists()); 15708 return result; 15709 } 15710 15711 // Utility method that returns the relative package path with respect 15712 // to the installation directory. Like say for /data/data/com.test-1.apk 15713 // string com.test-1 is returned. 15714 static String deriveCodePathName(String codePath) { 15715 if (codePath == null) { 15716 return null; 15717 } 15718 final File codeFile = new File(codePath); 15719 final String name = codeFile.getName(); 15720 if (codeFile.isDirectory()) { 15721 return name; 15722 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15723 final int lastDot = name.lastIndexOf('.'); 15724 return name.substring(0, lastDot); 15725 } else { 15726 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15727 return null; 15728 } 15729 } 15730 15731 static class PackageInstalledInfo { 15732 String name; 15733 int uid; 15734 // The set of users that originally had this package installed. 15735 int[] origUsers; 15736 // The set of users that now have this package installed. 15737 int[] newUsers; 15738 PackageParser.Package pkg; 15739 int returnCode; 15740 String returnMsg; 15741 String installerPackageName; 15742 PackageRemovedInfo removedInfo; 15743 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15744 15745 public void setError(int code, String msg) { 15746 setReturnCode(code); 15747 setReturnMessage(msg); 15748 Slog.w(TAG, msg); 15749 } 15750 15751 public void setError(String msg, PackageParserException e) { 15752 setReturnCode(e.error); 15753 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15754 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15755 for (int i = 0; i < childCount; i++) { 15756 addedChildPackages.valueAt(i).setError(msg, e); 15757 } 15758 Slog.w(TAG, msg, e); 15759 } 15760 15761 public void setError(String msg, PackageManagerException e) { 15762 returnCode = e.error; 15763 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15764 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15765 for (int i = 0; i < childCount; i++) { 15766 addedChildPackages.valueAt(i).setError(msg, e); 15767 } 15768 Slog.w(TAG, msg, e); 15769 } 15770 15771 public void setReturnCode(int returnCode) { 15772 this.returnCode = returnCode; 15773 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15774 for (int i = 0; i < childCount; i++) { 15775 addedChildPackages.valueAt(i).returnCode = returnCode; 15776 } 15777 } 15778 15779 private void setReturnMessage(String returnMsg) { 15780 this.returnMsg = returnMsg; 15781 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15782 for (int i = 0; i < childCount; i++) { 15783 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15784 } 15785 } 15786 15787 // In some error cases we want to convey more info back to the observer 15788 String origPackage; 15789 String origPermission; 15790 } 15791 15792 /* 15793 * Install a non-existing package. 15794 */ 15795 private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15796 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15797 String volumeUuid, PackageInstalledInfo res, int installReason) { 15798 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15799 15800 // Remember this for later, in case we need to rollback this install 15801 String pkgName = pkg.packageName; 15802 15803 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15804 15805 synchronized(mPackages) { 15806 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15807 if (renamedPackage != null) { 15808 // A package with the same name is already installed, though 15809 // it has been renamed to an older name. The package we 15810 // are trying to install should be installed as an update to 15811 // the existing one, but that has not been requested, so bail. 15812 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15813 + " without first uninstalling package running as " 15814 + renamedPackage); 15815 return; 15816 } 15817 if (mPackages.containsKey(pkgName)) { 15818 // Don't allow installation over an existing package with the same name. 15819 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15820 + " without first uninstalling."); 15821 return; 15822 } 15823 } 15824 15825 try { 15826 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 15827 System.currentTimeMillis(), user); 15828 15829 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15830 15831 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15832 prepareAppDataAfterInstallLIF(newPackage); 15833 15834 } else { 15835 // Remove package from internal structures, but keep around any 15836 // data that might have already existed 15837 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15838 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15839 } 15840 } catch (PackageManagerException e) { 15841 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15842 } 15843 15844 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15845 } 15846 15847 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15848 try (DigestInputStream digestStream = 15849 new DigestInputStream(new FileInputStream(file), digest)) { 15850 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15851 } 15852 } 15853 15854 private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15855 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15856 PackageInstalledInfo res, int installReason) { 15857 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15858 15859 final PackageParser.Package oldPackage; 15860 final PackageSetting ps; 15861 final String pkgName = pkg.packageName; 15862 final int[] allUsers; 15863 final int[] installedUsers; 15864 15865 synchronized(mPackages) { 15866 oldPackage = mPackages.get(pkgName); 15867 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15868 15869 // don't allow upgrade to target a release SDK from a pre-release SDK 15870 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15871 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15872 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15873 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15874 if (oldTargetsPreRelease 15875 && !newTargetsPreRelease 15876 && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15877 Slog.w(TAG, "Can't install package targeting released sdk"); 15878 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15879 return; 15880 } 15881 15882 ps = mSettings.mPackages.get(pkgName); 15883 15884 // verify signatures are valid 15885 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 15886 if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) { 15887 if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) { 15888 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15889 "New package not signed by keys specified by upgrade-keysets: " 15890 + pkgName); 15891 return; 15892 } 15893 } else { 15894 // default to original signature matching 15895 if (compareSignatures(oldPackage.mSigningDetails.signatures, 15896 pkg.mSigningDetails.signatures) 15897 != PackageManager.SIGNATURE_MATCH) { 15898 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15899 "New package has a different signature: " + pkgName); 15900 return; 15901 } 15902 } 15903 15904 // don't allow a system upgrade unless the upgrade hash matches 15905 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) { 15906 byte[] digestBytes = null; 15907 try { 15908 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15909 updateDigest(digest, new File(pkg.baseCodePath)); 15910 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15911 for (String path : pkg.splitCodePaths) { 15912 updateDigest(digest, new File(path)); 15913 } 15914 } 15915 digestBytes = digest.digest(); 15916 } catch (NoSuchAlgorithmException | IOException e) { 15917 res.setError(INSTALL_FAILED_INVALID_APK, 15918 "Could not compute hash: " + pkgName); 15919 return; 15920 } 15921 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15922 res.setError(INSTALL_FAILED_INVALID_APK, 15923 "New package fails restrict-update check: " + pkgName); 15924 return; 15925 } 15926 // retain upgrade restriction 15927 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15928 } 15929 15930 // Check for shared user id changes 15931 String invalidPackageName = 15932 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15933 if (invalidPackageName != null) { 15934 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15935 "Package " + invalidPackageName + " tried to change user " 15936 + oldPackage.mSharedUserId); 15937 return; 15938 } 15939 15940 // check if the new package supports all of the abis which the old package supports 15941 boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null; 15942 boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null; 15943 if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) { 15944 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15945 "Update to package " + pkgName + " doesn't support multi arch"); 15946 return; 15947 } 15948 15949 // In case of rollback, remember per-user/profile install state 15950 allUsers = sUserManager.getUserIds(); 15951 installedUsers = ps.queryInstalledUsers(allUsers, true); 15952 15953 // don't allow an upgrade from full to ephemeral 15954 if (isInstantApp) { 15955 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 15956 for (int currentUser : allUsers) { 15957 if (!ps.getInstantApp(currentUser)) { 15958 // can't downgrade from full to instant 15959 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15960 + " for user: " + currentUser); 15961 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15962 return; 15963 } 15964 } 15965 } else if (!ps.getInstantApp(user.getIdentifier())) { 15966 // can't downgrade from full to instant 15967 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15968 + " for user: " + user.getIdentifier()); 15969 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15970 return; 15971 } 15972 } 15973 } 15974 15975 // Update what is removed 15976 res.removedInfo = new PackageRemovedInfo(this); 15977 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15978 res.removedInfo.removedPackage = oldPackage.packageName; 15979 res.removedInfo.installerPackageName = ps.installerPackageName; 15980 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15981 res.removedInfo.isUpdate = true; 15982 res.removedInfo.origUsers = installedUsers; 15983 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15984 for (int i = 0; i < installedUsers.length; i++) { 15985 final int userId = installedUsers[i]; 15986 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15987 } 15988 15989 final int childCount = (oldPackage.childPackages != null) 15990 ? oldPackage.childPackages.size() : 0; 15991 for (int i = 0; i < childCount; i++) { 15992 boolean childPackageUpdated = false; 15993 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15994 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15995 if (res.addedChildPackages != null) { 15996 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15997 if (childRes != null) { 15998 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15999 childRes.removedInfo.removedPackage = childPkg.packageName; 16000 if (childPs != null) { 16001 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16002 } 16003 childRes.removedInfo.isUpdate = true; 16004 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16005 childPackageUpdated = true; 16006 } 16007 } 16008 if (!childPackageUpdated) { 16009 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 16010 childRemovedRes.removedPackage = childPkg.packageName; 16011 if (childPs != null) { 16012 childRemovedRes.installerPackageName = childPs.installerPackageName; 16013 } 16014 childRemovedRes.isUpdate = false; 16015 childRemovedRes.dataRemoved = true; 16016 synchronized (mPackages) { 16017 if (childPs != null) { 16018 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16019 } 16020 } 16021 if (res.removedInfo.removedChildPackages == null) { 16022 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16023 } 16024 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16025 } 16026 } 16027 16028 boolean sysPkg = (isSystemApp(oldPackage)); 16029 if (sysPkg) { 16030 // Set the system/privileged/oem/vendor flags as needed 16031 final boolean privileged = 16032 (oldPackage.applicationInfo.privateFlags 16033 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16034 final boolean oem = 16035 (oldPackage.applicationInfo.privateFlags 16036 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 16037 final boolean vendor = 16038 (oldPackage.applicationInfo.privateFlags 16039 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 16040 final @ParseFlags int systemParseFlags = parseFlags; 16041 final @ScanFlags int systemScanFlags = scanFlags 16042 | SCAN_AS_SYSTEM 16043 | (privileged ? SCAN_AS_PRIVILEGED : 0) 16044 | (oem ? SCAN_AS_OEM : 0) 16045 | (vendor ? SCAN_AS_VENDOR : 0); 16046 16047 replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags, 16048 user, allUsers, installerPackageName, res, installReason); 16049 } else { 16050 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 16051 user, allUsers, installerPackageName, res, installReason); 16052 } 16053 } 16054 16055 @Override 16056 public List<String> getPreviousCodePaths(String packageName) { 16057 final int callingUid = Binder.getCallingUid(); 16058 final List<String> result = new ArrayList<>(); 16059 if (getInstantAppPackageName(callingUid) != null) { 16060 return result; 16061 } 16062 final PackageSetting ps = mSettings.mPackages.get(packageName); 16063 if (ps != null 16064 && ps.oldCodePaths != null 16065 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 16066 result.addAll(ps.oldCodePaths); 16067 } 16068 return result; 16069 } 16070 16071 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16072 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16073 final @ScanFlags int scanFlags, UserHandle user, int[] allUsers, 16074 String installerPackageName, PackageInstalledInfo res, int installReason) { 16075 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16076 + deletedPackage); 16077 16078 String pkgName = deletedPackage.packageName; 16079 boolean deletedPkg = true; 16080 boolean addedPkg = false; 16081 boolean updatedSettings = false; 16082 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16083 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16084 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16085 16086 final long origUpdateTime = (pkg.mExtras != null) 16087 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16088 16089 // First delete the existing package while retaining the data directory 16090 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16091 res.removedInfo, true, pkg)) { 16092 // If the existing package wasn't successfully deleted 16093 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16094 deletedPkg = false; 16095 } else { 16096 // Successfully deleted the old package; proceed with replace. 16097 16098 // If deleted package lived in a container, give users a chance to 16099 // relinquish resources before killing. 16100 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16101 if (DEBUG_INSTALL) { 16102 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16103 } 16104 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16105 final ArrayList<String> pkgList = new ArrayList<String>(1); 16106 pkgList.add(deletedPackage.applicationInfo.packageName); 16107 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16108 } 16109 16110 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16111 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16112 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16113 16114 try { 16115 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 16116 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16117 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16118 installReason); 16119 16120 // Update the in-memory copy of the previous code paths. 16121 PackageSetting ps = mSettings.mPackages.get(pkgName); 16122 if (!killApp) { 16123 if (ps.oldCodePaths == null) { 16124 ps.oldCodePaths = new ArraySet<>(); 16125 } 16126 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16127 if (deletedPackage.splitCodePaths != null) { 16128 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16129 } 16130 } else { 16131 ps.oldCodePaths = null; 16132 } 16133 if (ps.childPackageNames != null) { 16134 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16135 final String childPkgName = ps.childPackageNames.get(i); 16136 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16137 childPs.oldCodePaths = ps.oldCodePaths; 16138 } 16139 } 16140 // set instant app status, but, only if it's explicitly specified 16141 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16142 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16143 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16144 prepareAppDataAfterInstallLIF(newPackage); 16145 addedPkg = true; 16146 mDexManager.notifyPackageUpdated(newPackage.packageName, 16147 newPackage.baseCodePath, newPackage.splitCodePaths); 16148 } catch (PackageManagerException e) { 16149 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16150 } 16151 } 16152 16153 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16154 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16155 16156 // Revert all internal state mutations and added folders for the failed install 16157 if (addedPkg) { 16158 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16159 res.removedInfo, true, null); 16160 } 16161 16162 // Restore the old package 16163 if (deletedPkg) { 16164 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16165 File restoreFile = new File(deletedPackage.codePath); 16166 // Parse old package 16167 boolean oldExternal = isExternal(deletedPackage); 16168 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16169 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16170 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16171 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16172 try { 16173 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16174 null); 16175 } catch (PackageManagerException e) { 16176 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16177 + e.getMessage()); 16178 return; 16179 } 16180 16181 synchronized (mPackages) { 16182 // Ensure the installer package name up to date 16183 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16184 16185 // Update permissions for restored package 16186 mPermissionManager.updatePermissions( 16187 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16188 mPermissionCallback); 16189 16190 mSettings.writeLPr(); 16191 } 16192 16193 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16194 } 16195 } else { 16196 synchronized (mPackages) { 16197 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16198 if (ps != null) { 16199 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16200 if (res.removedInfo.removedChildPackages != null) { 16201 final int childCount = res.removedInfo.removedChildPackages.size(); 16202 // Iterate in reverse as we may modify the collection 16203 for (int i = childCount - 1; i >= 0; i--) { 16204 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16205 if (res.addedChildPackages.containsKey(childPackageName)) { 16206 res.removedInfo.removedChildPackages.removeAt(i); 16207 } else { 16208 PackageRemovedInfo childInfo = res.removedInfo 16209 .removedChildPackages.valueAt(i); 16210 childInfo.removedForAllUsers = mPackages.get( 16211 childInfo.removedPackage) == null; 16212 } 16213 } 16214 } 16215 } 16216 } 16217 } 16218 } 16219 16220 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16221 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16222 final @ScanFlags int scanFlags, UserHandle user, 16223 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16224 int installReason) { 16225 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16226 + ", old=" + deletedPackage); 16227 16228 final boolean disabledSystem; 16229 16230 // Remove existing system package 16231 removePackageLI(deletedPackage, true); 16232 16233 synchronized (mPackages) { 16234 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16235 } 16236 if (!disabledSystem) { 16237 // We didn't need to disable the .apk as a current system package, 16238 // which means we are replacing another update that is already 16239 // installed. We need to make sure to delete the older one's .apk. 16240 res.removedInfo.args = createInstallArgsForExisting(0, 16241 deletedPackage.applicationInfo.getCodePath(), 16242 deletedPackage.applicationInfo.getResourcePath(), 16243 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16244 } else { 16245 res.removedInfo.args = null; 16246 } 16247 16248 // Successfully disabled the old package. Now proceed with re-installation 16249 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16250 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16251 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16252 16253 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16254 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16255 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16256 16257 PackageParser.Package newPackage = null; 16258 try { 16259 // Add the package to the internal data structures 16260 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 16261 16262 // Set the update and install times 16263 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16264 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16265 System.currentTimeMillis()); 16266 16267 // Update the package dynamic state if succeeded 16268 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16269 // Now that the install succeeded make sure we remove data 16270 // directories for any child package the update removed. 16271 final int deletedChildCount = (deletedPackage.childPackages != null) 16272 ? deletedPackage.childPackages.size() : 0; 16273 final int newChildCount = (newPackage.childPackages != null) 16274 ? newPackage.childPackages.size() : 0; 16275 for (int i = 0; i < deletedChildCount; i++) { 16276 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16277 boolean childPackageDeleted = true; 16278 for (int j = 0; j < newChildCount; j++) { 16279 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16280 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16281 childPackageDeleted = false; 16282 break; 16283 } 16284 } 16285 if (childPackageDeleted) { 16286 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16287 deletedChildPkg.packageName); 16288 if (ps != null && res.removedInfo.removedChildPackages != null) { 16289 PackageRemovedInfo removedChildRes = res.removedInfo 16290 .removedChildPackages.get(deletedChildPkg.packageName); 16291 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16292 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16293 } 16294 } 16295 } 16296 16297 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16298 installReason); 16299 prepareAppDataAfterInstallLIF(newPackage); 16300 16301 mDexManager.notifyPackageUpdated(newPackage.packageName, 16302 newPackage.baseCodePath, newPackage.splitCodePaths); 16303 } 16304 } catch (PackageManagerException e) { 16305 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16306 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16307 } 16308 16309 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16310 // Re installation failed. Restore old information 16311 // Remove new pkg information 16312 if (newPackage != null) { 16313 removeInstalledPackageLI(newPackage, true); 16314 } 16315 // Add back the old system package 16316 try { 16317 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16318 } catch (PackageManagerException e) { 16319 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16320 } 16321 16322 synchronized (mPackages) { 16323 if (disabledSystem) { 16324 enableSystemPackageLPw(deletedPackage); 16325 } 16326 16327 // Ensure the installer package name up to date 16328 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16329 16330 // Update permissions for restored package 16331 mPermissionManager.updatePermissions( 16332 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16333 mPermissionCallback); 16334 16335 mSettings.writeLPr(); 16336 } 16337 16338 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16339 + " after failed upgrade"); 16340 } 16341 } 16342 16343 /** 16344 * Checks whether the parent or any of the child packages have a change shared 16345 * user. For a package to be a valid update the shred users of the parent and 16346 * the children should match. We may later support changing child shared users. 16347 * @param oldPkg The updated package. 16348 * @param newPkg The update package. 16349 * @return The shared user that change between the versions. 16350 */ 16351 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16352 PackageParser.Package newPkg) { 16353 // Check parent shared user 16354 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16355 return newPkg.packageName; 16356 } 16357 // Check child shared users 16358 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16359 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16360 for (int i = 0; i < newChildCount; i++) { 16361 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16362 // If this child was present, did it have the same shared user? 16363 for (int j = 0; j < oldChildCount; j++) { 16364 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16365 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16366 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16367 return newChildPkg.packageName; 16368 } 16369 } 16370 } 16371 return null; 16372 } 16373 16374 private void removeNativeBinariesLI(PackageSetting ps) { 16375 // Remove the lib path for the parent package 16376 if (ps != null) { 16377 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16378 // Remove the lib path for the child packages 16379 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16380 for (int i = 0; i < childCount; i++) { 16381 PackageSetting childPs = null; 16382 synchronized (mPackages) { 16383 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16384 } 16385 if (childPs != null) { 16386 NativeLibraryHelper.removeNativeBinariesLI(childPs 16387 .legacyNativeLibraryPathString); 16388 } 16389 } 16390 } 16391 } 16392 16393 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16394 // Enable the parent package 16395 mSettings.enableSystemPackageLPw(pkg.packageName); 16396 // Enable the child packages 16397 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16398 for (int i = 0; i < childCount; i++) { 16399 PackageParser.Package childPkg = pkg.childPackages.get(i); 16400 mSettings.enableSystemPackageLPw(childPkg.packageName); 16401 } 16402 } 16403 16404 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16405 PackageParser.Package newPkg) { 16406 // Disable the parent package (parent always replaced) 16407 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16408 // Disable the child packages 16409 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16410 for (int i = 0; i < childCount; i++) { 16411 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16412 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16413 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16414 } 16415 return disabled; 16416 } 16417 16418 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16419 String installerPackageName) { 16420 // Enable the parent package 16421 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16422 // Enable the child packages 16423 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16424 for (int i = 0; i < childCount; i++) { 16425 PackageParser.Package childPkg = pkg.childPackages.get(i); 16426 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16427 } 16428 } 16429 16430 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16431 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16432 // Update the parent package setting 16433 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16434 res, user, installReason); 16435 // Update the child packages setting 16436 final int childCount = (newPackage.childPackages != null) 16437 ? newPackage.childPackages.size() : 0; 16438 for (int i = 0; i < childCount; i++) { 16439 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16440 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16441 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16442 childRes.origUsers, childRes, user, installReason); 16443 } 16444 } 16445 16446 private void updateSettingsInternalLI(PackageParser.Package pkg, 16447 String installerPackageName, int[] allUsers, int[] installedForUsers, 16448 PackageInstalledInfo res, UserHandle user, int installReason) { 16449 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16450 16451 String pkgName = pkg.packageName; 16452 synchronized (mPackages) { 16453 //write settings. the installStatus will be incomplete at this stage. 16454 //note that the new package setting would have already been 16455 //added to mPackages. It hasn't been persisted yet. 16456 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16457 // TODO: Remove this write? It's also written at the end of this method 16458 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16459 mSettings.writeLPr(); 16460 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16461 } 16462 16463 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath); 16464 synchronized (mPackages) { 16465// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions 16466 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 16467 mPermissionCallback); 16468 // For system-bundled packages, we assume that installing an upgraded version 16469 // of the package implies that the user actually wants to run that new code, 16470 // so we enable the package. 16471 PackageSetting ps = mSettings.mPackages.get(pkgName); 16472 final int userId = user.getIdentifier(); 16473 if (ps != null) { 16474 if (isSystemApp(pkg)) { 16475 if (DEBUG_INSTALL) { 16476 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16477 } 16478 // Enable system package for requested users 16479 if (res.origUsers != null) { 16480 for (int origUserId : res.origUsers) { 16481 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16482 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16483 origUserId, installerPackageName); 16484 } 16485 } 16486 } 16487 // Also convey the prior install/uninstall state 16488 if (allUsers != null && installedForUsers != null) { 16489 for (int currentUserId : allUsers) { 16490 final boolean installed = ArrayUtils.contains( 16491 installedForUsers, currentUserId); 16492 if (DEBUG_INSTALL) { 16493 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16494 } 16495 ps.setInstalled(installed, currentUserId); 16496 } 16497 // these install state changes will be persisted in the 16498 // upcoming call to mSettings.writeLPr(). 16499 } 16500 } 16501 // It's implied that when a user requests installation, they want the app to be 16502 // installed and enabled. 16503 if (userId != UserHandle.USER_ALL) { 16504 ps.setInstalled(true, userId); 16505 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16506 } 16507 16508 // When replacing an existing package, preserve the original install reason for all 16509 // users that had the package installed before. 16510 final Set<Integer> previousUserIds = new ArraySet<>(); 16511 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16512 final int installReasonCount = res.removedInfo.installReasons.size(); 16513 for (int i = 0; i < installReasonCount; i++) { 16514 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16515 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16516 ps.setInstallReason(previousInstallReason, previousUserId); 16517 previousUserIds.add(previousUserId); 16518 } 16519 } 16520 16521 // Set install reason for users that are having the package newly installed. 16522 if (userId == UserHandle.USER_ALL) { 16523 for (int currentUserId : sUserManager.getUserIds()) { 16524 if (!previousUserIds.contains(currentUserId)) { 16525 ps.setInstallReason(installReason, currentUserId); 16526 } 16527 } 16528 } else if (!previousUserIds.contains(userId)) { 16529 ps.setInstallReason(installReason, userId); 16530 } 16531 mSettings.writeKernelMappingLPr(ps); 16532 } 16533 res.name = pkgName; 16534 res.uid = pkg.applicationInfo.uid; 16535 res.pkg = pkg; 16536 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16537 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16538 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16539 //to update install status 16540 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16541 mSettings.writeLPr(); 16542 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16543 } 16544 16545 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16546 } 16547 16548 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16549 try { 16550 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16551 installPackageLI(args, res); 16552 } finally { 16553 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16554 } 16555 } 16556 16557 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16558 final int installFlags = args.installFlags; 16559 final String installerPackageName = args.installerPackageName; 16560 final String volumeUuid = args.volumeUuid; 16561 final File tmpPackageFile = new File(args.getCodePath()); 16562 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16563 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16564 || (args.volumeUuid != null)); 16565 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16566 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16567 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16568 final boolean virtualPreload = 16569 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 16570 boolean replace = false; 16571 @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16572 if (args.move != null) { 16573 // moving a complete application; perform an initial scan on the new install location 16574 scanFlags |= SCAN_INITIAL; 16575 } 16576 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16577 scanFlags |= SCAN_DONT_KILL_APP; 16578 } 16579 if (instantApp) { 16580 scanFlags |= SCAN_AS_INSTANT_APP; 16581 } 16582 if (fullApp) { 16583 scanFlags |= SCAN_AS_FULL_APP; 16584 } 16585 if (virtualPreload) { 16586 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 16587 } 16588 16589 // Result object to be returned 16590 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16591 res.installerPackageName = installerPackageName; 16592 16593 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16594 16595 // Sanity check 16596 if (instantApp && (forwardLocked || onExternal)) { 16597 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16598 + " external=" + onExternal); 16599 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16600 return; 16601 } 16602 16603 // Retrieve PackageSettings and parse package 16604 @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16605 | PackageParser.PARSE_ENFORCE_CODE 16606 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16607 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16608 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16609 PackageParser pp = new PackageParser(); 16610 pp.setSeparateProcesses(mSeparateProcesses); 16611 pp.setDisplayMetrics(mMetrics); 16612 pp.setCallback(mPackageParserCallback); 16613 16614 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16615 final PackageParser.Package pkg; 16616 try { 16617 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16618 DexMetadataHelper.validatePackageDexMetadata(pkg); 16619 } catch (PackageParserException e) { 16620 res.setError("Failed parse during installPackageLI", e); 16621 return; 16622 } finally { 16623 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16624 } 16625 16626 // Instant apps have several additional install-time checks. 16627 if (instantApp) { 16628 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 16629 Slog.w(TAG, 16630 "Instant app package " + pkg.packageName + " does not target at least O"); 16631 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16632 "Instant app package must target at least O"); 16633 return; 16634 } 16635 if (pkg.applicationInfo.targetSandboxVersion != 2) { 16636 Slog.w(TAG, "Instant app package " + pkg.packageName 16637 + " does not target targetSandboxVersion 2"); 16638 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16639 "Instant app package must use targetSandboxVersion 2"); 16640 return; 16641 } 16642 if (pkg.mSharedUserId != null) { 16643 Slog.w(TAG, "Instant app package " + pkg.packageName 16644 + " may not declare sharedUserId."); 16645 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16646 "Instant app package may not declare a sharedUserId"); 16647 return; 16648 } 16649 } 16650 16651 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16652 // Static shared libraries have synthetic package names 16653 renameStaticSharedLibraryPackage(pkg); 16654 16655 // No static shared libs on external storage 16656 if (onExternal) { 16657 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16658 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16659 "Packages declaring static-shared libs cannot be updated"); 16660 return; 16661 } 16662 } 16663 16664 // If we are installing a clustered package add results for the children 16665 if (pkg.childPackages != null) { 16666 synchronized (mPackages) { 16667 final int childCount = pkg.childPackages.size(); 16668 for (int i = 0; i < childCount; i++) { 16669 PackageParser.Package childPkg = pkg.childPackages.get(i); 16670 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16671 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16672 childRes.pkg = childPkg; 16673 childRes.name = childPkg.packageName; 16674 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16675 if (childPs != null) { 16676 childRes.origUsers = childPs.queryInstalledUsers( 16677 sUserManager.getUserIds(), true); 16678 } 16679 if ((mPackages.containsKey(childPkg.packageName))) { 16680 childRes.removedInfo = new PackageRemovedInfo(this); 16681 childRes.removedInfo.removedPackage = childPkg.packageName; 16682 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16683 } 16684 if (res.addedChildPackages == null) { 16685 res.addedChildPackages = new ArrayMap<>(); 16686 } 16687 res.addedChildPackages.put(childPkg.packageName, childRes); 16688 } 16689 } 16690 } 16691 16692 // If package doesn't declare API override, mark that we have an install 16693 // time CPU ABI override. 16694 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16695 pkg.cpuAbiOverride = args.abiOverride; 16696 } 16697 16698 String pkgName = res.name = pkg.packageName; 16699 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16700 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16701 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16702 return; 16703 } 16704 } 16705 16706 try { 16707 // either use what we've been given or parse directly from the APK 16708 if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) { 16709 pkg.setSigningDetails(args.signingDetails); 16710 } else { 16711 PackageParser.collectCertificates(pkg, parseFlags); 16712 } 16713 } catch (PackageParserException e) { 16714 res.setError("Failed collect during installPackageLI", e); 16715 return; 16716 } 16717 16718 if (instantApp && pkg.mSigningDetails.signatureSchemeVersion 16719 < SignatureSchemeVersion.SIGNING_BLOCK_V2) { 16720 Slog.w(TAG, "Instant app package " + pkg.packageName 16721 + " is not signed with at least APK Signature Scheme v2"); 16722 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16723 "Instant app package must be signed with APK Signature Scheme v2 or greater"); 16724 return; 16725 } 16726 16727 // Get rid of all references to package scan path via parser. 16728 pp = null; 16729 String oldCodePath = null; 16730 boolean systemApp = false; 16731 synchronized (mPackages) { 16732 // Check if installing already existing package 16733 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16734 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16735 if (pkg.mOriginalPackages != null 16736 && pkg.mOriginalPackages.contains(oldName) 16737 && mPackages.containsKey(oldName)) { 16738 // This package is derived from an original package, 16739 // and this device has been updating from that original 16740 // name. We must continue using the original name, so 16741 // rename the new package here. 16742 pkg.setPackageName(oldName); 16743 pkgName = pkg.packageName; 16744 replace = true; 16745 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16746 + oldName + " pkgName=" + pkgName); 16747 } else if (mPackages.containsKey(pkgName)) { 16748 // This package, under its official name, already exists 16749 // on the device; we should replace it. 16750 replace = true; 16751 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16752 } 16753 16754 // Child packages are installed through the parent package 16755 if (pkg.parentPackage != null) { 16756 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16757 "Package " + pkg.packageName + " is child of package " 16758 + pkg.parentPackage.parentPackage + ". Child packages " 16759 + "can be updated only through the parent package."); 16760 return; 16761 } 16762 16763 if (replace) { 16764 // Prevent apps opting out from runtime permissions 16765 PackageParser.Package oldPackage = mPackages.get(pkgName); 16766 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16767 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16768 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16769 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16770 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16771 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16772 + " doesn't support runtime permissions but the old" 16773 + " target SDK " + oldTargetSdk + " does."); 16774 return; 16775 } 16776 // Prevent persistent apps from being updated 16777 if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) { 16778 res.setError(PackageManager.INSTALL_FAILED_INVALID_APK, 16779 "Package " + oldPackage.packageName + " is a persistent app. " 16780 + "Persistent apps are not updateable."); 16781 return; 16782 } 16783 // Prevent apps from downgrading their targetSandbox. 16784 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16785 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16786 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16787 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16788 "Package " + pkg.packageName + " new target sandbox " 16789 + newTargetSandbox + " is incompatible with the previous value of" 16790 + oldTargetSandbox + "."); 16791 return; 16792 } 16793 16794 // Prevent installing of child packages 16795 if (oldPackage.parentPackage != null) { 16796 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16797 "Package " + pkg.packageName + " is child of package " 16798 + oldPackage.parentPackage + ". Child packages " 16799 + "can be updated only through the parent package."); 16800 return; 16801 } 16802 } 16803 } 16804 16805 PackageSetting ps = mSettings.mPackages.get(pkgName); 16806 if (ps != null) { 16807 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16808 16809 // Static shared libs have same package with different versions where 16810 // we internally use a synthetic package name to allow multiple versions 16811 // of the same package, therefore we need to compare signatures against 16812 // the package setting for the latest library version. 16813 PackageSetting signatureCheckPs = ps; 16814 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16815 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16816 if (libraryEntry != null) { 16817 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16818 } 16819 } 16820 16821 // Quick sanity check that we're signed correctly if updating; 16822 // we'll check this again later when scanning, but we want to 16823 // bail early here before tripping over redefined permissions. 16824 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16825 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 16826 if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 16827 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16828 + pkg.packageName + " upgrade keys do not match the " 16829 + "previously installed version"); 16830 return; 16831 } 16832 } else { 16833 try { 16834 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 16835 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 16836 // We don't care about disabledPkgSetting on install for now. 16837 final boolean compatMatch = verifySignatures( 16838 signatureCheckPs, null, pkg.mSigningDetails, compareCompat, 16839 compareRecover); 16840 // The new KeySets will be re-added later in the scanning process. 16841 if (compatMatch) { 16842 synchronized (mPackages) { 16843 ksms.removeAppKeySetDataLPw(pkg.packageName); 16844 } 16845 } 16846 } catch (PackageManagerException e) { 16847 res.setError(e.error, e.getMessage()); 16848 return; 16849 } 16850 } 16851 16852 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16853 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16854 systemApp = (ps.pkg.applicationInfo.flags & 16855 ApplicationInfo.FLAG_SYSTEM) != 0; 16856 } 16857 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16858 } 16859 16860 int N = pkg.permissions.size(); 16861 for (int i = N-1; i >= 0; i--) { 16862 final PackageParser.Permission perm = pkg.permissions.get(i); 16863 final BasePermission bp = 16864 (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name); 16865 16866 // Don't allow anyone but the system to define ephemeral permissions. 16867 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 16868 && !systemApp) { 16869 Slog.w(TAG, "Non-System package " + pkg.packageName 16870 + " attempting to delcare ephemeral permission " 16871 + perm.info.name + "; Removing ephemeral."); 16872 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 16873 } 16874 16875 // Check whether the newly-scanned package wants to define an already-defined perm 16876 if (bp != null) { 16877 // If the defining package is signed with our cert, it's okay. This 16878 // also includes the "updating the same package" case, of course. 16879 // "updating same package" could also involve key-rotation. 16880 final boolean sigsOk; 16881 final String sourcePackageName = bp.getSourcePackageName(); 16882 final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting(); 16883 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16884 if (sourcePackageName.equals(pkg.packageName) 16885 && (ksms.shouldCheckUpgradeKeySetLocked( 16886 sourcePackageSetting, scanFlags))) { 16887 sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg); 16888 } else { 16889 sigsOk = compareSignatures( 16890 sourcePackageSetting.signatures.mSigningDetails.signatures, 16891 pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH; 16892 } 16893 if (!sigsOk) { 16894 // If the owning package is the system itself, we log but allow 16895 // install to proceed; we fail the install on all other permission 16896 // redefinitions. 16897 if (!sourcePackageName.equals("android")) { 16898 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16899 + pkg.packageName + " attempting to redeclare permission " 16900 + perm.info.name + " already owned by " + sourcePackageName); 16901 res.origPermission = perm.info.name; 16902 res.origPackage = sourcePackageName; 16903 return; 16904 } else { 16905 Slog.w(TAG, "Package " + pkg.packageName 16906 + " attempting to redeclare system permission " 16907 + perm.info.name + "; ignoring new declaration"); 16908 pkg.permissions.remove(i); 16909 } 16910 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16911 // Prevent apps to change protection level to dangerous from any other 16912 // type as this would allow a privilege escalation where an app adds a 16913 // normal/signature permission in other app's group and later redefines 16914 // it as dangerous leading to the group auto-grant. 16915 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16916 == PermissionInfo.PROTECTION_DANGEROUS) { 16917 if (bp != null && !bp.isRuntime()) { 16918 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16919 + "non-runtime permission " + perm.info.name 16920 + " to runtime; keeping old protection level"); 16921 perm.info.protectionLevel = bp.getProtectionLevel(); 16922 } 16923 } 16924 } 16925 } 16926 } 16927 } 16928 16929 if (systemApp) { 16930 if (onExternal) { 16931 // Abort update; system app can't be replaced with app on sdcard 16932 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16933 "Cannot install updates to system apps on sdcard"); 16934 return; 16935 } else if (instantApp) { 16936 // Abort update; system app can't be replaced with an instant app 16937 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16938 "Cannot update a system app with an instant app"); 16939 return; 16940 } 16941 } 16942 16943 if (args.move != null) { 16944 // We did an in-place move, so dex is ready to roll 16945 scanFlags |= SCAN_NO_DEX; 16946 scanFlags |= SCAN_MOVE; 16947 16948 synchronized (mPackages) { 16949 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16950 if (ps == null) { 16951 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16952 "Missing settings for moved package " + pkgName); 16953 } 16954 16955 // We moved the entire application as-is, so bring over the 16956 // previously derived ABI information. 16957 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16958 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16959 } 16960 16961 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16962 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16963 scanFlags |= SCAN_NO_DEX; 16964 16965 try { 16966 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16967 args.abiOverride : pkg.cpuAbiOverride); 16968 final boolean extractNativeLibs = !pkg.isLibrary(); 16969 derivePackageAbi(pkg, abiOverride, extractNativeLibs); 16970 } catch (PackageManagerException pme) { 16971 Slog.e(TAG, "Error deriving application ABI", pme); 16972 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16973 return; 16974 } 16975 16976 // Shared libraries for the package need to be updated. 16977 synchronized (mPackages) { 16978 try { 16979 updateSharedLibrariesLPr(pkg, null); 16980 } catch (PackageManagerException e) { 16981 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16982 } 16983 } 16984 } 16985 16986 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16987 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16988 return; 16989 } 16990 16991 if (PackageManagerServiceUtils.isApkVerityEnabled()) { 16992 String apkPath = null; 16993 synchronized (mPackages) { 16994 // Note that if the attacker managed to skip verify setup, for example by tampering 16995 // with the package settings, upon reboot we will do full apk verification when 16996 // verity is not detected. 16997 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16998 if (ps != null && ps.isPrivileged()) { 16999 apkPath = pkg.baseCodePath; 17000 } 17001 } 17002 17003 if (apkPath != null) { 17004 final VerityUtils.SetupResult result = 17005 VerityUtils.generateApkVeritySetupData(apkPath); 17006 if (result.isOk()) { 17007 if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath); 17008 FileDescriptor fd = result.getUnownedFileDescriptor(); 17009 try { 17010 mInstaller.installApkVerity(apkPath, fd); 17011 } catch (InstallerException e) { 17012 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17013 "Failed to set up verity: " + e); 17014 return; 17015 } finally { 17016 IoUtils.closeQuietly(fd); 17017 } 17018 } else if (result.isFailed()) { 17019 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity"); 17020 return; 17021 } else { 17022 // Do nothing if verity is skipped. Will fall back to full apk verification on 17023 // reboot. 17024 } 17025 } 17026 } 17027 17028 if (!instantApp) { 17029 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17030 } else { 17031 if (DEBUG_DOMAIN_VERIFICATION) { 17032 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName); 17033 } 17034 } 17035 17036 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17037 "installPackageLI")) { 17038 if (replace) { 17039 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17040 // Static libs have a synthetic package name containing the version 17041 // and cannot be updated as an update would get a new package name, 17042 // unless this is the exact same version code which is useful for 17043 // development. 17044 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17045 if (existingPkg != null && 17046 existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) { 17047 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17048 + "static-shared libs cannot be updated"); 17049 return; 17050 } 17051 } 17052 replacePackageLIF(pkg, parseFlags, scanFlags, args.user, 17053 installerPackageName, res, args.installReason); 17054 } else { 17055 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17056 args.user, installerPackageName, volumeUuid, res, args.installReason); 17057 } 17058 } 17059 17060 // Check whether we need to dexopt the app. 17061 // 17062 // NOTE: it is IMPORTANT to call dexopt: 17063 // - after doRename which will sync the package data from PackageParser.Package and its 17064 // corresponding ApplicationInfo. 17065 // - after installNewPackageLIF or replacePackageLIF which will update result with the 17066 // uid of the application (pkg.applicationInfo.uid). 17067 // This update happens in place! 17068 // 17069 // We only need to dexopt if the package meets ALL of the following conditions: 17070 // 1) it is not forward locked. 17071 // 2) it is not on on an external ASEC container. 17072 // 3) it is not an instant app or if it is then dexopt is enabled via gservices. 17073 // 17074 // Note that we do not dexopt instant apps by default. dexopt can take some time to 17075 // complete, so we skip this step during installation. Instead, we'll take extra time 17076 // the first time the instant app starts. It's preferred to do it this way to provide 17077 // continuous progress to the useur instead of mysteriously blocking somewhere in the 17078 // middle of running an instant app. The default behaviour can be overridden 17079 // via gservices. 17080 final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED) 17081 && !forwardLocked 17082 && !pkg.applicationInfo.isExternalAsec() 17083 && (!instantApp || Global.getInt(mContext.getContentResolver(), 17084 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0); 17085 17086 if (performDexopt) { 17087 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17088 // Do not run PackageDexOptimizer through the local performDexOpt 17089 // method because `pkg` may not be in `mPackages` yet. 17090 // 17091 // Also, don't fail application installs if the dexopt step fails. 17092 DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName, 17093 REASON_INSTALL, 17094 DexoptOptions.DEXOPT_BOOT_COMPLETE); 17095 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17096 null /* instructionSets */, 17097 getOrCreateCompilerPackageStats(pkg), 17098 mDexManager.getPackageUseInfoOrDefault(pkg.packageName), 17099 dexoptOptions); 17100 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17101 } 17102 17103 // Notify BackgroundDexOptService that the package has been changed. 17104 // If this is an update of a package which used to fail to compile, 17105 // BackgroundDexOptService will remove it from its blacklist. 17106 // TODO: Layering violation 17107 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17108 17109 synchronized (mPackages) { 17110 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17111 if (ps != null) { 17112 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17113 ps.setUpdateAvailable(false /*updateAvailable*/); 17114 } 17115 17116 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17117 for (int i = 0; i < childCount; i++) { 17118 PackageParser.Package childPkg = pkg.childPackages.get(i); 17119 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17120 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17121 if (childPs != null) { 17122 childRes.newUsers = childPs.queryInstalledUsers( 17123 sUserManager.getUserIds(), true); 17124 } 17125 } 17126 17127 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17128 updateSequenceNumberLP(ps, res.newUsers); 17129 updateInstantAppInstallerLocked(pkgName); 17130 } 17131 } 17132 } 17133 17134 private void startIntentFilterVerifications(int userId, boolean replacing, 17135 PackageParser.Package pkg) { 17136 if (mIntentFilterVerifierComponent == null) { 17137 Slog.w(TAG, "No IntentFilter verification will not be done as " 17138 + "there is no IntentFilterVerifier available!"); 17139 return; 17140 } 17141 17142 final int verifierUid = getPackageUid( 17143 mIntentFilterVerifierComponent.getPackageName(), 17144 MATCH_DEBUG_TRIAGED_MISSING, 17145 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17146 17147 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17148 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17149 mHandler.sendMessage(msg); 17150 17151 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17152 for (int i = 0; i < childCount; i++) { 17153 PackageParser.Package childPkg = pkg.childPackages.get(i); 17154 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17155 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17156 mHandler.sendMessage(msg); 17157 } 17158 } 17159 17160 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17161 PackageParser.Package pkg) { 17162 int size = pkg.activities.size(); 17163 if (size == 0) { 17164 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17165 "No activity, so no need to verify any IntentFilter!"); 17166 return; 17167 } 17168 17169 final boolean hasDomainURLs = hasDomainURLs(pkg); 17170 if (!hasDomainURLs) { 17171 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17172 "No domain URLs, so no need to verify any IntentFilter!"); 17173 return; 17174 } 17175 17176 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17177 + " if any IntentFilter from the " + size 17178 + " Activities needs verification ..."); 17179 17180 int count = 0; 17181 final String packageName = pkg.packageName; 17182 17183 synchronized (mPackages) { 17184 // If this is a new install and we see that we've already run verification for this 17185 // package, we have nothing to do: it means the state was restored from backup. 17186 if (!replacing) { 17187 IntentFilterVerificationInfo ivi = 17188 mSettings.getIntentFilterVerificationLPr(packageName); 17189 if (ivi != null) { 17190 if (DEBUG_DOMAIN_VERIFICATION) { 17191 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17192 + ivi.getStatusString()); 17193 } 17194 return; 17195 } 17196 } 17197 17198 // If any filters need to be verified, then all need to be. 17199 boolean needToVerify = false; 17200 for (PackageParser.Activity a : pkg.activities) { 17201 for (ActivityIntentInfo filter : a.intents) { 17202 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17203 if (DEBUG_DOMAIN_VERIFICATION) { 17204 Slog.d(TAG, 17205 "Intent filter needs verification, so processing all filters"); 17206 } 17207 needToVerify = true; 17208 break; 17209 } 17210 } 17211 } 17212 17213 if (needToVerify) { 17214 final int verificationId = mIntentFilterVerificationToken++; 17215 for (PackageParser.Activity a : pkg.activities) { 17216 for (ActivityIntentInfo filter : a.intents) { 17217 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17218 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17219 "Verification needed for IntentFilter:" + filter.toString()); 17220 mIntentFilterVerifier.addOneIntentFilterVerification( 17221 verifierUid, userId, verificationId, filter, packageName); 17222 count++; 17223 } 17224 } 17225 } 17226 } 17227 } 17228 17229 if (count > 0) { 17230 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17231 + " IntentFilter verification" + (count > 1 ? "s" : "") 17232 + " for userId:" + userId); 17233 mIntentFilterVerifier.startVerifications(userId); 17234 } else { 17235 if (DEBUG_DOMAIN_VERIFICATION) { 17236 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17237 } 17238 } 17239 } 17240 17241 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17242 final ComponentName cn = filter.activity.getComponentName(); 17243 final String packageName = cn.getPackageName(); 17244 17245 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17246 packageName); 17247 if (ivi == null) { 17248 return true; 17249 } 17250 int status = ivi.getStatus(); 17251 switch (status) { 17252 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17253 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17254 return true; 17255 17256 default: 17257 // Nothing to do 17258 return false; 17259 } 17260 } 17261 17262 private static boolean isMultiArch(ApplicationInfo info) { 17263 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17264 } 17265 17266 private static boolean isExternal(PackageParser.Package pkg) { 17267 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17268 } 17269 17270 private static boolean isExternal(PackageSetting ps) { 17271 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17272 } 17273 17274 private static boolean isSystemApp(PackageParser.Package pkg) { 17275 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17276 } 17277 17278 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17279 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17280 } 17281 17282 private static boolean isOemApp(PackageParser.Package pkg) { 17283 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 17284 } 17285 17286 private static boolean isVendorApp(PackageParser.Package pkg) { 17287 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 17288 } 17289 17290 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17291 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17292 } 17293 17294 private static boolean isSystemApp(PackageSetting ps) { 17295 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17296 } 17297 17298 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17299 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17300 } 17301 17302 private int packageFlagsToInstallFlags(PackageSetting ps) { 17303 int installFlags = 0; 17304 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17305 // This existing package was an external ASEC install when we have 17306 // the external flag without a UUID 17307 installFlags |= PackageManager.INSTALL_EXTERNAL; 17308 } 17309 if (ps.isForwardLocked()) { 17310 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17311 } 17312 return installFlags; 17313 } 17314 17315 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17316 if (isExternal(pkg)) { 17317 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17318 return mSettings.getExternalVersion(); 17319 } else { 17320 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17321 } 17322 } else { 17323 return mSettings.getInternalVersion(); 17324 } 17325 } 17326 17327 private void deleteTempPackageFiles() { 17328 final FilenameFilter filter = new FilenameFilter() { 17329 public boolean accept(File dir, String name) { 17330 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17331 } 17332 }; 17333 for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) { 17334 file.delete(); 17335 } 17336 } 17337 17338 @Override 17339 public void deletePackageAsUser(String packageName, int versionCode, 17340 IPackageDeleteObserver observer, int userId, int flags) { 17341 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17342 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17343 } 17344 17345 @Override 17346 public void deletePackageVersioned(VersionedPackage versionedPackage, 17347 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17348 final int callingUid = Binder.getCallingUid(); 17349 mContext.enforceCallingOrSelfPermission( 17350 android.Manifest.permission.DELETE_PACKAGES, null); 17351 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 17352 Preconditions.checkNotNull(versionedPackage); 17353 Preconditions.checkNotNull(observer); 17354 Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(), 17355 PackageManager.VERSION_CODE_HIGHEST, 17356 Long.MAX_VALUE, "versionCode must be >= -1"); 17357 17358 final String packageName = versionedPackage.getPackageName(); 17359 final long versionCode = versionedPackage.getLongVersionCode(); 17360 final String internalPackageName; 17361 synchronized (mPackages) { 17362 // Normalize package name to handle renamed packages and static libs 17363 internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode); 17364 } 17365 17366 final int uid = Binder.getCallingUid(); 17367 if (!isOrphaned(internalPackageName) 17368 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17369 try { 17370 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17371 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17372 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17373 observer.onUserActionRequired(intent); 17374 } catch (RemoteException re) { 17375 } 17376 return; 17377 } 17378 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17379 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17380 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17381 mContext.enforceCallingOrSelfPermission( 17382 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17383 "deletePackage for user " + userId); 17384 } 17385 17386 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17387 try { 17388 observer.onPackageDeleted(packageName, 17389 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17390 } catch (RemoteException re) { 17391 } 17392 return; 17393 } 17394 17395 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17396 try { 17397 observer.onPackageDeleted(packageName, 17398 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17399 } catch (RemoteException re) { 17400 } 17401 return; 17402 } 17403 17404 if (DEBUG_REMOVE) { 17405 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17406 + " deleteAllUsers: " + deleteAllUsers + " version=" 17407 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17408 ? "VERSION_CODE_HIGHEST" : versionCode)); 17409 } 17410 // Queue up an async operation since the package deletion may take a little while. 17411 mHandler.post(new Runnable() { 17412 public void run() { 17413 mHandler.removeCallbacks(this); 17414 int returnCode; 17415 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 17416 boolean doDeletePackage = true; 17417 if (ps != null) { 17418 final boolean targetIsInstantApp = 17419 ps.getInstantApp(UserHandle.getUserId(callingUid)); 17420 doDeletePackage = !targetIsInstantApp 17421 || canViewInstantApps; 17422 } 17423 if (doDeletePackage) { 17424 if (!deleteAllUsers) { 17425 returnCode = deletePackageX(internalPackageName, versionCode, 17426 userId, deleteFlags); 17427 } else { 17428 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17429 internalPackageName, users); 17430 // If nobody is blocking uninstall, proceed with delete for all users 17431 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17432 returnCode = deletePackageX(internalPackageName, versionCode, 17433 userId, deleteFlags); 17434 } else { 17435 // Otherwise uninstall individually for users with blockUninstalls=false 17436 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17437 for (int userId : users) { 17438 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17439 returnCode = deletePackageX(internalPackageName, versionCode, 17440 userId, userFlags); 17441 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17442 Slog.w(TAG, "Package delete failed for user " + userId 17443 + ", returnCode " + returnCode); 17444 } 17445 } 17446 } 17447 // The app has only been marked uninstalled for certain users. 17448 // We still need to report that delete was blocked 17449 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17450 } 17451 } 17452 } else { 17453 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17454 } 17455 try { 17456 observer.onPackageDeleted(packageName, returnCode, null); 17457 } catch (RemoteException e) { 17458 Log.i(TAG, "Observer no longer exists."); 17459 } //end catch 17460 } //end run 17461 }); 17462 } 17463 17464 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17465 if (pkg.staticSharedLibName != null) { 17466 return pkg.manifestPackageName; 17467 } 17468 return pkg.packageName; 17469 } 17470 17471 private String resolveInternalPackageNameLPr(String packageName, long versionCode) { 17472 // Handle renamed packages 17473 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17474 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17475 17476 // Is this a static library? 17477 LongSparseArray<SharedLibraryEntry> versionedLib = 17478 mStaticLibsByDeclaringPackage.get(packageName); 17479 if (versionedLib == null || versionedLib.size() <= 0) { 17480 return packageName; 17481 } 17482 17483 // Figure out which lib versions the caller can see 17484 LongSparseLongArray versionsCallerCanSee = null; 17485 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17486 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17487 && callingAppId != Process.ROOT_UID) { 17488 versionsCallerCanSee = new LongSparseLongArray(); 17489 String libName = versionedLib.valueAt(0).info.getName(); 17490 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17491 if (uidPackages != null) { 17492 for (String uidPackage : uidPackages) { 17493 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17494 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17495 if (libIdx >= 0) { 17496 final long libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17497 versionsCallerCanSee.append(libVersion, libVersion); 17498 } 17499 } 17500 } 17501 } 17502 17503 // Caller can see nothing - done 17504 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17505 return packageName; 17506 } 17507 17508 // Find the version the caller can see and the app version code 17509 SharedLibraryEntry highestVersion = null; 17510 final int versionCount = versionedLib.size(); 17511 for (int i = 0; i < versionCount; i++) { 17512 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17513 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17514 libEntry.info.getLongVersion()) < 0) { 17515 continue; 17516 } 17517 final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode(); 17518 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17519 if (libVersionCode == versionCode) { 17520 return libEntry.apk; 17521 } 17522 } else if (highestVersion == null) { 17523 highestVersion = libEntry; 17524 } else if (libVersionCode > highestVersion.info 17525 .getDeclaringPackage().getLongVersionCode()) { 17526 highestVersion = libEntry; 17527 } 17528 } 17529 17530 if (highestVersion != null) { 17531 return highestVersion.apk; 17532 } 17533 17534 return packageName; 17535 } 17536 17537 boolean isCallerVerifier(int callingUid) { 17538 final int callingUserId = UserHandle.getUserId(callingUid); 17539 return mRequiredVerifierPackage != null && 17540 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 17541 } 17542 17543 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17544 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17545 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17546 return true; 17547 } 17548 final int callingUserId = UserHandle.getUserId(callingUid); 17549 // If the caller installed the pkgName, then allow it to silently uninstall. 17550 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17551 return true; 17552 } 17553 17554 // Allow package verifier to silently uninstall. 17555 if (mRequiredVerifierPackage != null && 17556 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17557 return true; 17558 } 17559 17560 // Allow package uninstaller to silently uninstall. 17561 if (mRequiredUninstallerPackage != null && 17562 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17563 return true; 17564 } 17565 17566 // Allow storage manager to silently uninstall. 17567 if (mStorageManagerPackage != null && 17568 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17569 return true; 17570 } 17571 17572 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 17573 // uninstall for device owner provisioning. 17574 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 17575 == PERMISSION_GRANTED) { 17576 return true; 17577 } 17578 17579 return false; 17580 } 17581 17582 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17583 int[] result = EMPTY_INT_ARRAY; 17584 for (int userId : userIds) { 17585 if (getBlockUninstallForUser(packageName, userId)) { 17586 result = ArrayUtils.appendInt(result, userId); 17587 } 17588 } 17589 return result; 17590 } 17591 17592 @Override 17593 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17594 final int callingUid = Binder.getCallingUid(); 17595 if (getInstantAppPackageName(callingUid) != null 17596 && !isCallerSameApp(packageName, callingUid)) { 17597 return false; 17598 } 17599 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17600 } 17601 17602 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17603 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17604 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17605 try { 17606 if (dpm != null) { 17607 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17608 /* callingUserOnly =*/ false); 17609 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17610 : deviceOwnerComponentName.getPackageName(); 17611 // Does the package contains the device owner? 17612 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17613 // this check is probably not needed, since DO should be registered as a device 17614 // admin on some user too. (Original bug for this: b/17657954) 17615 if (packageName.equals(deviceOwnerPackageName)) { 17616 return true; 17617 } 17618 // Does it contain a device admin for any user? 17619 int[] users; 17620 if (userId == UserHandle.USER_ALL) { 17621 users = sUserManager.getUserIds(); 17622 } else { 17623 users = new int[]{userId}; 17624 } 17625 for (int i = 0; i < users.length; ++i) { 17626 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17627 return true; 17628 } 17629 } 17630 } 17631 } catch (RemoteException e) { 17632 } 17633 return false; 17634 } 17635 17636 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17637 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17638 } 17639 17640 /** 17641 * This method is an internal method that could be get invoked either 17642 * to delete an installed package or to clean up a failed installation. 17643 * After deleting an installed package, a broadcast is sent to notify any 17644 * listeners that the package has been removed. For cleaning up a failed 17645 * installation, the broadcast is not necessary since the package's 17646 * installation wouldn't have sent the initial broadcast either 17647 * The key steps in deleting a package are 17648 * deleting the package information in internal structures like mPackages, 17649 * deleting the packages base directories through installd 17650 * updating mSettings to reflect current status 17651 * persisting settings for later use 17652 * sending a broadcast if necessary 17653 */ 17654 int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) { 17655 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17656 final boolean res; 17657 17658 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17659 ? UserHandle.USER_ALL : userId; 17660 17661 if (isPackageDeviceAdmin(packageName, removeUser)) { 17662 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17663 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17664 } 17665 17666 PackageSetting uninstalledPs = null; 17667 PackageParser.Package pkg = null; 17668 17669 // for the uninstall-updates case and restricted profiles, remember the per- 17670 // user handle installed state 17671 int[] allUsers; 17672 synchronized (mPackages) { 17673 uninstalledPs = mSettings.mPackages.get(packageName); 17674 if (uninstalledPs == null) { 17675 Slog.w(TAG, "Not removing non-existent package " + packageName); 17676 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17677 } 17678 17679 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17680 && uninstalledPs.versionCode != versionCode) { 17681 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17682 + uninstalledPs.versionCode + " != " + versionCode); 17683 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17684 } 17685 17686 // Static shared libs can be declared by any package, so let us not 17687 // allow removing a package if it provides a lib others depend on. 17688 pkg = mPackages.get(packageName); 17689 17690 allUsers = sUserManager.getUserIds(); 17691 17692 if (pkg != null && pkg.staticSharedLibName != null) { 17693 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17694 pkg.staticSharedLibVersion); 17695 if (libEntry != null) { 17696 for (int currUserId : allUsers) { 17697 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 17698 continue; 17699 } 17700 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17701 libEntry.info, 0, currUserId); 17702 if (!ArrayUtils.isEmpty(libClientPackages)) { 17703 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17704 + " hosting lib " + libEntry.info.getName() + " version " 17705 + libEntry.info.getLongVersion() + " used by " + libClientPackages 17706 + " for user " + currUserId); 17707 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17708 } 17709 } 17710 } 17711 } 17712 17713 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17714 } 17715 17716 final int freezeUser; 17717 if (isUpdatedSystemApp(uninstalledPs) 17718 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17719 // We're downgrading a system app, which will apply to all users, so 17720 // freeze them all during the downgrade 17721 freezeUser = UserHandle.USER_ALL; 17722 } else { 17723 freezeUser = removeUser; 17724 } 17725 17726 synchronized (mInstallLock) { 17727 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17728 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17729 deleteFlags, "deletePackageX")) { 17730 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17731 deleteFlags | PackageManager.DELETE_CHATTY, info, true, null); 17732 } 17733 synchronized (mPackages) { 17734 if (res) { 17735 if (pkg != null) { 17736 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17737 } 17738 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 17739 updateInstantAppInstallerLocked(packageName); 17740 } 17741 } 17742 } 17743 17744 if (res) { 17745 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17746 info.sendPackageRemovedBroadcasts(killApp); 17747 info.sendSystemPackageUpdatedBroadcasts(); 17748 info.sendSystemPackageAppearedBroadcasts(); 17749 } 17750 // Force a gc here. 17751 Runtime.getRuntime().gc(); 17752 // Delete the resources here after sending the broadcast to let 17753 // other processes clean up before deleting resources. 17754 if (info.args != null) { 17755 synchronized (mInstallLock) { 17756 info.args.doPostDeleteLI(true); 17757 } 17758 } 17759 17760 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17761 } 17762 17763 static class PackageRemovedInfo { 17764 final PackageSender packageSender; 17765 String removedPackage; 17766 String installerPackageName; 17767 int uid = -1; 17768 int removedAppId = -1; 17769 int[] origUsers; 17770 int[] removedUsers = null; 17771 int[] broadcastUsers = null; 17772 int[] instantUserIds = null; 17773 SparseArray<Integer> installReasons; 17774 boolean isRemovedPackageSystemUpdate = false; 17775 boolean isUpdate; 17776 boolean dataRemoved; 17777 boolean removedForAllUsers; 17778 boolean isStaticSharedLib; 17779 // Clean up resources deleted packages. 17780 InstallArgs args = null; 17781 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17782 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17783 17784 PackageRemovedInfo(PackageSender packageSender) { 17785 this.packageSender = packageSender; 17786 } 17787 17788 void sendPackageRemovedBroadcasts(boolean killApp) { 17789 sendPackageRemovedBroadcastInternal(killApp); 17790 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17791 for (int i = 0; i < childCount; i++) { 17792 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17793 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17794 } 17795 } 17796 17797 void sendSystemPackageUpdatedBroadcasts() { 17798 if (isRemovedPackageSystemUpdate) { 17799 sendSystemPackageUpdatedBroadcastsInternal(); 17800 final int childCount = (removedChildPackages != null) 17801 ? removedChildPackages.size() : 0; 17802 for (int i = 0; i < childCount; i++) { 17803 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17804 if (childInfo.isRemovedPackageSystemUpdate) { 17805 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17806 } 17807 } 17808 } 17809 } 17810 17811 void sendSystemPackageAppearedBroadcasts() { 17812 final int packageCount = (appearedChildPackages != null) 17813 ? appearedChildPackages.size() : 0; 17814 for (int i = 0; i < packageCount; i++) { 17815 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17816 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 17817 true /*sendBootCompleted*/, false /*startReceiver*/, 17818 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null); 17819 } 17820 } 17821 17822 private void sendSystemPackageUpdatedBroadcastsInternal() { 17823 Bundle extras = new Bundle(2); 17824 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17825 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17826 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17827 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 17828 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17829 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 17830 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 17831 null, null, 0, removedPackage, null, null, null); 17832 if (installerPackageName != null) { 17833 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17834 removedPackage, extras, 0 /*flags*/, 17835 installerPackageName, null, null, null); 17836 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17837 removedPackage, extras, 0 /*flags*/, 17838 installerPackageName, null, null, null); 17839 } 17840 } 17841 17842 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17843 // Don't send static shared library removal broadcasts as these 17844 // libs are visible only the the apps that depend on them an one 17845 // cannot remove the library if it has a dependency. 17846 if (isStaticSharedLib) { 17847 return; 17848 } 17849 Bundle extras = new Bundle(2); 17850 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17851 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17852 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17853 if (isUpdate || isRemovedPackageSystemUpdate) { 17854 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17855 } 17856 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17857 if (removedPackage != null) { 17858 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 17859 removedPackage, extras, 0, null /*targetPackage*/, null, 17860 broadcastUsers, instantUserIds); 17861 if (installerPackageName != null) { 17862 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 17863 removedPackage, extras, 0 /*flags*/, 17864 installerPackageName, null, broadcastUsers, instantUserIds); 17865 } 17866 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17867 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17868 removedPackage, extras, 17869 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17870 null, null, broadcastUsers, instantUserIds); 17871 packageSender.notifyPackageRemoved(removedPackage); 17872 } 17873 } 17874 if (removedAppId >= 0) { 17875 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 17876 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17877 null, null, broadcastUsers, instantUserIds); 17878 } 17879 } 17880 17881 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 17882 removedUsers = userIds; 17883 if (removedUsers == null) { 17884 broadcastUsers = null; 17885 return; 17886 } 17887 17888 broadcastUsers = EMPTY_INT_ARRAY; 17889 instantUserIds = EMPTY_INT_ARRAY; 17890 for (int i = userIds.length - 1; i >= 0; --i) { 17891 final int userId = userIds[i]; 17892 if (deletedPackageSetting.getInstantApp(userId)) { 17893 instantUserIds = ArrayUtils.appendInt(instantUserIds, userId); 17894 } else { 17895 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 17896 } 17897 } 17898 } 17899 } 17900 17901 /* 17902 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17903 * flag is not set, the data directory is removed as well. 17904 * make sure this flag is set for partially installed apps. If not its meaningless to 17905 * delete a partially installed application. 17906 */ 17907 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17908 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17909 String packageName = ps.name; 17910 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17911 // Retrieve object to delete permissions for shared user later on 17912 final PackageParser.Package deletedPkg; 17913 final PackageSetting deletedPs; 17914 // reader 17915 synchronized (mPackages) { 17916 deletedPkg = mPackages.get(packageName); 17917 deletedPs = mSettings.mPackages.get(packageName); 17918 if (outInfo != null) { 17919 outInfo.removedPackage = packageName; 17920 outInfo.installerPackageName = ps.installerPackageName; 17921 outInfo.isStaticSharedLib = deletedPkg != null 17922 && deletedPkg.staticSharedLibName != null; 17923 outInfo.populateUsers(deletedPs == null ? null 17924 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 17925 } 17926 } 17927 17928 removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0); 17929 17930 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17931 final PackageParser.Package resolvedPkg; 17932 if (deletedPkg != null) { 17933 resolvedPkg = deletedPkg; 17934 } else { 17935 // We don't have a parsed package when it lives on an ejected 17936 // adopted storage device, so fake something together 17937 resolvedPkg = new PackageParser.Package(ps.name); 17938 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17939 } 17940 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17941 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17942 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17943 if (outInfo != null) { 17944 outInfo.dataRemoved = true; 17945 } 17946 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17947 } 17948 17949 int removedAppId = -1; 17950 17951 // writer 17952 synchronized (mPackages) { 17953 boolean installedStateChanged = false; 17954 if (deletedPs != null) { 17955 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17956 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17957 clearDefaultBrowserIfNeeded(packageName); 17958 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17959 removedAppId = mSettings.removePackageLPw(packageName); 17960 if (outInfo != null) { 17961 outInfo.removedAppId = removedAppId; 17962 } 17963 mPermissionManager.updatePermissions( 17964 deletedPs.name, null, false, mPackages.values(), mPermissionCallback); 17965 if (deletedPs.sharedUser != null) { 17966 // Remove permissions associated with package. Since runtime 17967 // permissions are per user we have to kill the removed package 17968 // or packages running under the shared user of the removed 17969 // package if revoking the permissions requested only by the removed 17970 // package is successful and this causes a change in gids. 17971 for (int userId : UserManagerService.getInstance().getUserIds()) { 17972 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17973 userId); 17974 if (userIdToKill == UserHandle.USER_ALL 17975 || userIdToKill >= UserHandle.USER_SYSTEM) { 17976 // If gids changed for this user, kill all affected packages. 17977 mHandler.post(new Runnable() { 17978 @Override 17979 public void run() { 17980 // This has to happen with no lock held. 17981 killApplication(deletedPs.name, deletedPs.appId, 17982 KILL_APP_REASON_GIDS_CHANGED); 17983 } 17984 }); 17985 break; 17986 } 17987 } 17988 } 17989 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17990 } 17991 // make sure to preserve per-user disabled state if this removal was just 17992 // a downgrade of a system app to the factory package 17993 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17994 if (DEBUG_REMOVE) { 17995 Slog.d(TAG, "Propagating install state across downgrade"); 17996 } 17997 for (int userId : allUserHandles) { 17998 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17999 if (DEBUG_REMOVE) { 18000 Slog.d(TAG, " user " + userId + " => " + installed); 18001 } 18002 if (installed != ps.getInstalled(userId)) { 18003 installedStateChanged = true; 18004 } 18005 ps.setInstalled(installed, userId); 18006 } 18007 } 18008 } 18009 // can downgrade to reader 18010 if (writeSettings) { 18011 // Save settings now 18012 mSettings.writeLPr(); 18013 } 18014 if (installedStateChanged) { 18015 mSettings.writeKernelMappingLPr(ps); 18016 } 18017 } 18018 if (removedAppId != -1) { 18019 // A user ID was deleted here. Go through all users and remove it 18020 // from KeyStore. 18021 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 18022 } 18023 } 18024 18025 static boolean locationIsPrivileged(String path) { 18026 try { 18027 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 18028 final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 18029 return path.startsWith(privilegedAppDir.getCanonicalPath()) 18030 || path.startsWith(privilegedVendorAppDir.getCanonicalPath()); 18031 } catch (IOException e) { 18032 Slog.e(TAG, "Unable to access code path " + path); 18033 } 18034 return false; 18035 } 18036 18037 static boolean locationIsOem(String path) { 18038 try { 18039 return path.startsWith(Environment.getOemDirectory().getCanonicalPath()); 18040 } catch (IOException e) { 18041 Slog.e(TAG, "Unable to access code path " + path); 18042 } 18043 return false; 18044 } 18045 18046 static boolean locationIsVendor(String path) { 18047 try { 18048 return path.startsWith(Environment.getVendorDirectory().getCanonicalPath()); 18049 } catch (IOException e) { 18050 Slog.e(TAG, "Unable to access code path " + path); 18051 } 18052 return false; 18053 } 18054 18055 /* 18056 * Tries to delete system package. 18057 */ 18058 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 18059 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 18060 boolean writeSettings) { 18061 if (deletedPs.parentPackageName != null) { 18062 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 18063 return false; 18064 } 18065 18066 final boolean applyUserRestrictions 18067 = (allUserHandles != null) && (outInfo.origUsers != null); 18068 final PackageSetting disabledPs; 18069 // Confirm if the system package has been updated 18070 // An updated system app can be deleted. This will also have to restore 18071 // the system pkg from system partition 18072 // reader 18073 synchronized (mPackages) { 18074 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 18075 } 18076 18077 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 18078 + " disabledPs=" + disabledPs); 18079 18080 if (disabledPs == null) { 18081 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 18082 return false; 18083 } else if (DEBUG_REMOVE) { 18084 Slog.d(TAG, "Deleting system pkg from data partition"); 18085 } 18086 18087 if (DEBUG_REMOVE) { 18088 if (applyUserRestrictions) { 18089 Slog.d(TAG, "Remembering install states:"); 18090 for (int userId : allUserHandles) { 18091 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 18092 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 18093 } 18094 } 18095 } 18096 18097 // Delete the updated package 18098 outInfo.isRemovedPackageSystemUpdate = true; 18099 if (outInfo.removedChildPackages != null) { 18100 final int childCount = (deletedPs.childPackageNames != null) 18101 ? deletedPs.childPackageNames.size() : 0; 18102 for (int i = 0; i < childCount; i++) { 18103 String childPackageName = deletedPs.childPackageNames.get(i); 18104 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 18105 .contains(childPackageName)) { 18106 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18107 childPackageName); 18108 if (childInfo != null) { 18109 childInfo.isRemovedPackageSystemUpdate = true; 18110 } 18111 } 18112 } 18113 } 18114 18115 if (disabledPs.versionCode < deletedPs.versionCode) { 18116 // Delete data for downgrades 18117 flags &= ~PackageManager.DELETE_KEEP_DATA; 18118 } else { 18119 // Preserve data by setting flag 18120 flags |= PackageManager.DELETE_KEEP_DATA; 18121 } 18122 18123 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 18124 outInfo, writeSettings, disabledPs.pkg); 18125 if (!ret) { 18126 return false; 18127 } 18128 18129 // writer 18130 synchronized (mPackages) { 18131 // NOTE: The system package always needs to be enabled; even if it's for 18132 // a compressed stub. If we don't, installing the system package fails 18133 // during scan [scanning checks the disabled packages]. We will reverse 18134 // this later, after we've "installed" the stub. 18135 // Reinstate the old system package 18136 enableSystemPackageLPw(disabledPs.pkg); 18137 // Remove any native libraries from the upgraded package. 18138 removeNativeBinariesLI(deletedPs); 18139 } 18140 18141 // Install the system package 18142 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18143 try { 18144 installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles, 18145 outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings); 18146 } catch (PackageManagerException e) { 18147 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18148 + e.getMessage()); 18149 return false; 18150 } finally { 18151 if (disabledPs.pkg.isStub) { 18152 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/); 18153 } 18154 } 18155 return true; 18156 } 18157 18158 /** 18159 * Installs a package that's already on the system partition. 18160 */ 18161 private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString, 18162 boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 18163 @Nullable PermissionsState origPermissionState, boolean writeSettings) 18164 throws PackageManagerException { 18165 @ParseFlags int parseFlags = 18166 mDefParseFlags 18167 | PackageParser.PARSE_MUST_BE_APK 18168 | PackageParser.PARSE_IS_SYSTEM_DIR; 18169 @ScanFlags int scanFlags = SCAN_AS_SYSTEM; 18170 if (isPrivileged || locationIsPrivileged(codePathString)) { 18171 scanFlags |= SCAN_AS_PRIVILEGED; 18172 } 18173 if (locationIsOem(codePathString)) { 18174 scanFlags |= SCAN_AS_OEM; 18175 } 18176 if (locationIsVendor(codePathString)) { 18177 scanFlags |= SCAN_AS_VENDOR; 18178 } 18179 18180 final File codePath = new File(codePathString); 18181 final PackageParser.Package pkg = 18182 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null); 18183 18184 try { 18185 // update shared libraries for the newly re-installed system package 18186 updateSharedLibrariesLPr(pkg, null); 18187 } catch (PackageManagerException e) { 18188 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18189 } 18190 18191 prepareAppDataAfterInstallLIF(pkg); 18192 18193 // writer 18194 synchronized (mPackages) { 18195 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 18196 18197 // Propagate the permissions state as we do not want to drop on the floor 18198 // runtime permissions. The update permissions method below will take 18199 // care of removing obsolete permissions and grant install permissions. 18200 if (origPermissionState != null) { 18201 ps.getPermissionsState().copyFrom(origPermissionState); 18202 } 18203 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 18204 mPermissionCallback); 18205 18206 final boolean applyUserRestrictions 18207 = (allUserHandles != null) && (origUserHandles != null); 18208 if (applyUserRestrictions) { 18209 boolean installedStateChanged = false; 18210 if (DEBUG_REMOVE) { 18211 Slog.d(TAG, "Propagating install state across reinstall"); 18212 } 18213 for (int userId : allUserHandles) { 18214 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 18215 if (DEBUG_REMOVE) { 18216 Slog.d(TAG, " user " + userId + " => " + installed); 18217 } 18218 if (installed != ps.getInstalled(userId)) { 18219 installedStateChanged = true; 18220 } 18221 ps.setInstalled(installed, userId); 18222 18223 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18224 } 18225 // Regardless of writeSettings we need to ensure that this restriction 18226 // state propagation is persisted 18227 mSettings.writeAllUsersPackageRestrictionsLPr(); 18228 if (installedStateChanged) { 18229 mSettings.writeKernelMappingLPr(ps); 18230 } 18231 } 18232 // can downgrade to reader here 18233 if (writeSettings) { 18234 mSettings.writeLPr(); 18235 } 18236 } 18237 return pkg; 18238 } 18239 18240 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18241 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18242 PackageRemovedInfo outInfo, boolean writeSettings, 18243 PackageParser.Package replacingPackage) { 18244 synchronized (mPackages) { 18245 if (outInfo != null) { 18246 outInfo.uid = ps.appId; 18247 } 18248 18249 if (outInfo != null && outInfo.removedChildPackages != null) { 18250 final int childCount = (ps.childPackageNames != null) 18251 ? ps.childPackageNames.size() : 0; 18252 for (int i = 0; i < childCount; i++) { 18253 String childPackageName = ps.childPackageNames.get(i); 18254 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18255 if (childPs == null) { 18256 return false; 18257 } 18258 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18259 childPackageName); 18260 if (childInfo != null) { 18261 childInfo.uid = childPs.appId; 18262 } 18263 } 18264 } 18265 } 18266 18267 // Delete package data from internal structures and also remove data if flag is set 18268 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18269 18270 // Delete the child packages data 18271 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18272 for (int i = 0; i < childCount; i++) { 18273 PackageSetting childPs; 18274 synchronized (mPackages) { 18275 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18276 } 18277 if (childPs != null) { 18278 PackageRemovedInfo childOutInfo = (outInfo != null 18279 && outInfo.removedChildPackages != null) 18280 ? outInfo.removedChildPackages.get(childPs.name) : null; 18281 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18282 && (replacingPackage != null 18283 && !replacingPackage.hasChildPackage(childPs.name)) 18284 ? flags & ~DELETE_KEEP_DATA : flags; 18285 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18286 deleteFlags, writeSettings); 18287 } 18288 } 18289 18290 // Delete application code and resources only for parent packages 18291 if (ps.parentPackageName == null) { 18292 if (deleteCodeAndResources && (outInfo != null)) { 18293 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18294 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18295 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18296 } 18297 } 18298 18299 return true; 18300 } 18301 18302 @Override 18303 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18304 int userId) { 18305 mContext.enforceCallingOrSelfPermission( 18306 android.Manifest.permission.DELETE_PACKAGES, null); 18307 synchronized (mPackages) { 18308 // Cannot block uninstall of static shared libs as they are 18309 // considered a part of the using app (emulating static linking). 18310 // Also static libs are installed always on internal storage. 18311 PackageParser.Package pkg = mPackages.get(packageName); 18312 if (pkg != null && pkg.staticSharedLibName != null) { 18313 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18314 + " providing static shared library: " + pkg.staticSharedLibName); 18315 return false; 18316 } 18317 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 18318 mSettings.writePackageRestrictionsLPr(userId); 18319 } 18320 return true; 18321 } 18322 18323 @Override 18324 public boolean getBlockUninstallForUser(String packageName, int userId) { 18325 synchronized (mPackages) { 18326 final PackageSetting ps = mSettings.mPackages.get(packageName); 18327 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 18328 return false; 18329 } 18330 return mSettings.getBlockUninstallLPr(userId, packageName); 18331 } 18332 } 18333 18334 @Override 18335 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18336 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 18337 synchronized (mPackages) { 18338 PackageSetting ps = mSettings.mPackages.get(packageName); 18339 if (ps == null) { 18340 Log.w(TAG, "Package doesn't exist: " + packageName); 18341 return false; 18342 } 18343 if (systemUserApp) { 18344 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18345 } else { 18346 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18347 } 18348 mSettings.writeLPr(); 18349 } 18350 return true; 18351 } 18352 18353 /* 18354 * This method handles package deletion in general 18355 */ 18356 private boolean deletePackageLIF(String packageName, UserHandle user, 18357 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18358 PackageRemovedInfo outInfo, boolean writeSettings, 18359 PackageParser.Package replacingPackage) { 18360 if (packageName == null) { 18361 Slog.w(TAG, "Attempt to delete null packageName."); 18362 return false; 18363 } 18364 18365 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18366 18367 PackageSetting ps; 18368 synchronized (mPackages) { 18369 ps = mSettings.mPackages.get(packageName); 18370 if (ps == null) { 18371 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18372 return false; 18373 } 18374 18375 if (ps.parentPackageName != null && (!isSystemApp(ps) 18376 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18377 if (DEBUG_REMOVE) { 18378 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18379 + ((user == null) ? UserHandle.USER_ALL : user)); 18380 } 18381 final int removedUserId = (user != null) ? user.getIdentifier() 18382 : UserHandle.USER_ALL; 18383 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18384 return false; 18385 } 18386 markPackageUninstalledForUserLPw(ps, user); 18387 scheduleWritePackageRestrictionsLocked(user); 18388 return true; 18389 } 18390 } 18391 18392 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18393 && user.getIdentifier() != UserHandle.USER_ALL)) { 18394 // The caller is asking that the package only be deleted for a single 18395 // user. To do this, we just mark its uninstalled state and delete 18396 // its data. If this is a system app, we only allow this to happen if 18397 // they have set the special DELETE_SYSTEM_APP which requests different 18398 // semantics than normal for uninstalling system apps. 18399 markPackageUninstalledForUserLPw(ps, user); 18400 18401 if (!isSystemApp(ps)) { 18402 // Do not uninstall the APK if an app should be cached 18403 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18404 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18405 // Other user still have this package installed, so all 18406 // we need to do is clear this user's data and save that 18407 // it is uninstalled. 18408 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18409 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18410 return false; 18411 } 18412 scheduleWritePackageRestrictionsLocked(user); 18413 return true; 18414 } else { 18415 // We need to set it back to 'installed' so the uninstall 18416 // broadcasts will be sent correctly. 18417 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18418 ps.setInstalled(true, user.getIdentifier()); 18419 mSettings.writeKernelMappingLPr(ps); 18420 } 18421 } else { 18422 // This is a system app, so we assume that the 18423 // other users still have this package installed, so all 18424 // we need to do is clear this user's data and save that 18425 // it is uninstalled. 18426 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18427 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18428 return false; 18429 } 18430 scheduleWritePackageRestrictionsLocked(user); 18431 return true; 18432 } 18433 } 18434 18435 // If we are deleting a composite package for all users, keep track 18436 // of result for each child. 18437 if (ps.childPackageNames != null && outInfo != null) { 18438 synchronized (mPackages) { 18439 final int childCount = ps.childPackageNames.size(); 18440 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18441 for (int i = 0; i < childCount; i++) { 18442 String childPackageName = ps.childPackageNames.get(i); 18443 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18444 childInfo.removedPackage = childPackageName; 18445 childInfo.installerPackageName = ps.installerPackageName; 18446 outInfo.removedChildPackages.put(childPackageName, childInfo); 18447 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18448 if (childPs != null) { 18449 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18450 } 18451 } 18452 } 18453 } 18454 18455 boolean ret = false; 18456 if (isSystemApp(ps)) { 18457 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18458 // When an updated system application is deleted we delete the existing resources 18459 // as well and fall back to existing code in system partition 18460 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18461 } else { 18462 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18463 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18464 outInfo, writeSettings, replacingPackage); 18465 } 18466 18467 // Take a note whether we deleted the package for all users 18468 if (outInfo != null) { 18469 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18470 if (outInfo.removedChildPackages != null) { 18471 synchronized (mPackages) { 18472 final int childCount = outInfo.removedChildPackages.size(); 18473 for (int i = 0; i < childCount; i++) { 18474 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18475 if (childInfo != null) { 18476 childInfo.removedForAllUsers = mPackages.get( 18477 childInfo.removedPackage) == null; 18478 } 18479 } 18480 } 18481 } 18482 // If we uninstalled an update to a system app there may be some 18483 // child packages that appeared as they are declared in the system 18484 // app but were not declared in the update. 18485 if (isSystemApp(ps)) { 18486 synchronized (mPackages) { 18487 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18488 final int childCount = (updatedPs.childPackageNames != null) 18489 ? updatedPs.childPackageNames.size() : 0; 18490 for (int i = 0; i < childCount; i++) { 18491 String childPackageName = updatedPs.childPackageNames.get(i); 18492 if (outInfo.removedChildPackages == null 18493 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18494 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18495 if (childPs == null) { 18496 continue; 18497 } 18498 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18499 installRes.name = childPackageName; 18500 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18501 installRes.pkg = mPackages.get(childPackageName); 18502 installRes.uid = childPs.pkg.applicationInfo.uid; 18503 if (outInfo.appearedChildPackages == null) { 18504 outInfo.appearedChildPackages = new ArrayMap<>(); 18505 } 18506 outInfo.appearedChildPackages.put(childPackageName, installRes); 18507 } 18508 } 18509 } 18510 } 18511 } 18512 18513 return ret; 18514 } 18515 18516 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18517 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18518 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18519 for (int nextUserId : userIds) { 18520 if (DEBUG_REMOVE) { 18521 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18522 } 18523 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18524 false /*installed*/, 18525 true /*stopped*/, 18526 true /*notLaunched*/, 18527 false /*hidden*/, 18528 false /*suspended*/, 18529 false /*instantApp*/, 18530 false /*virtualPreload*/, 18531 null /*lastDisableAppCaller*/, 18532 null /*enabledComponents*/, 18533 null /*disabledComponents*/, 18534 ps.readUserState(nextUserId).domainVerificationStatus, 18535 0, PackageManager.INSTALL_REASON_UNKNOWN, 18536 null /*harmfulAppWarning*/); 18537 } 18538 mSettings.writeKernelMappingLPr(ps); 18539 } 18540 18541 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18542 PackageRemovedInfo outInfo) { 18543 final PackageParser.Package pkg; 18544 synchronized (mPackages) { 18545 pkg = mPackages.get(ps.name); 18546 } 18547 18548 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18549 : new int[] {userId}; 18550 for (int nextUserId : userIds) { 18551 if (DEBUG_REMOVE) { 18552 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18553 + nextUserId); 18554 } 18555 18556 destroyAppDataLIF(pkg, userId, 18557 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18558 destroyAppProfilesLIF(pkg, userId); 18559 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18560 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18561 schedulePackageCleaning(ps.name, nextUserId, false); 18562 synchronized (mPackages) { 18563 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18564 scheduleWritePackageRestrictionsLocked(nextUserId); 18565 } 18566 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18567 } 18568 } 18569 18570 if (outInfo != null) { 18571 outInfo.removedPackage = ps.name; 18572 outInfo.installerPackageName = ps.installerPackageName; 18573 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18574 outInfo.removedAppId = ps.appId; 18575 outInfo.removedUsers = userIds; 18576 outInfo.broadcastUsers = userIds; 18577 } 18578 18579 return true; 18580 } 18581 18582 private final class ClearStorageConnection implements ServiceConnection { 18583 IMediaContainerService mContainerService; 18584 18585 @Override 18586 public void onServiceConnected(ComponentName name, IBinder service) { 18587 synchronized (this) { 18588 mContainerService = IMediaContainerService.Stub 18589 .asInterface(Binder.allowBlocking(service)); 18590 notifyAll(); 18591 } 18592 } 18593 18594 @Override 18595 public void onServiceDisconnected(ComponentName name) { 18596 } 18597 } 18598 18599 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18600 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18601 18602 final boolean mounted; 18603 if (Environment.isExternalStorageEmulated()) { 18604 mounted = true; 18605 } else { 18606 final String status = Environment.getExternalStorageState(); 18607 18608 mounted = status.equals(Environment.MEDIA_MOUNTED) 18609 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18610 } 18611 18612 if (!mounted) { 18613 return; 18614 } 18615 18616 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18617 int[] users; 18618 if (userId == UserHandle.USER_ALL) { 18619 users = sUserManager.getUserIds(); 18620 } else { 18621 users = new int[] { userId }; 18622 } 18623 final ClearStorageConnection conn = new ClearStorageConnection(); 18624 if (mContext.bindServiceAsUser( 18625 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18626 try { 18627 for (int curUser : users) { 18628 long timeout = SystemClock.uptimeMillis() + 5000; 18629 synchronized (conn) { 18630 long now; 18631 while (conn.mContainerService == null && 18632 (now = SystemClock.uptimeMillis()) < timeout) { 18633 try { 18634 conn.wait(timeout - now); 18635 } catch (InterruptedException e) { 18636 } 18637 } 18638 } 18639 if (conn.mContainerService == null) { 18640 return; 18641 } 18642 18643 final UserEnvironment userEnv = new UserEnvironment(curUser); 18644 clearDirectory(conn.mContainerService, 18645 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18646 if (allData) { 18647 clearDirectory(conn.mContainerService, 18648 userEnv.buildExternalStorageAppDataDirs(packageName)); 18649 clearDirectory(conn.mContainerService, 18650 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18651 } 18652 } 18653 } finally { 18654 mContext.unbindService(conn); 18655 } 18656 } 18657 } 18658 18659 @Override 18660 public void clearApplicationProfileData(String packageName) { 18661 enforceSystemOrRoot("Only the system can clear all profile data"); 18662 18663 final PackageParser.Package pkg; 18664 synchronized (mPackages) { 18665 pkg = mPackages.get(packageName); 18666 } 18667 18668 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18669 synchronized (mInstallLock) { 18670 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18671 } 18672 } 18673 } 18674 18675 @Override 18676 public void clearApplicationUserData(final String packageName, 18677 final IPackageDataObserver observer, final int userId) { 18678 mContext.enforceCallingOrSelfPermission( 18679 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18680 18681 final int callingUid = Binder.getCallingUid(); 18682 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18683 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18684 18685 final PackageSetting ps = mSettings.getPackageLPr(packageName); 18686 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 18687 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18688 throw new SecurityException("Cannot clear data for a protected package: " 18689 + packageName); 18690 } 18691 // Queue up an async operation since the package deletion may take a little while. 18692 mHandler.post(new Runnable() { 18693 public void run() { 18694 mHandler.removeCallbacks(this); 18695 final boolean succeeded; 18696 if (!filterApp) { 18697 try (PackageFreezer freezer = freezePackage(packageName, 18698 "clearApplicationUserData")) { 18699 synchronized (mInstallLock) { 18700 succeeded = clearApplicationUserDataLIF(packageName, userId); 18701 } 18702 clearExternalStorageDataSync(packageName, userId, true); 18703 synchronized (mPackages) { 18704 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18705 packageName, userId); 18706 } 18707 } 18708 if (succeeded) { 18709 // invoke DeviceStorageMonitor's update method to clear any notifications 18710 DeviceStorageMonitorInternal dsm = LocalServices 18711 .getService(DeviceStorageMonitorInternal.class); 18712 if (dsm != null) { 18713 dsm.checkMemory(); 18714 } 18715 } 18716 } else { 18717 succeeded = false; 18718 } 18719 if (observer != null) { 18720 try { 18721 observer.onRemoveCompleted(packageName, succeeded); 18722 } catch (RemoteException e) { 18723 Log.i(TAG, "Observer no longer exists."); 18724 } 18725 } //end if observer 18726 } //end run 18727 }); 18728 } 18729 18730 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18731 if (packageName == null) { 18732 Slog.w(TAG, "Attempt to delete null packageName."); 18733 return false; 18734 } 18735 18736 // Try finding details about the requested package 18737 PackageParser.Package pkg; 18738 synchronized (mPackages) { 18739 pkg = mPackages.get(packageName); 18740 if (pkg == null) { 18741 final PackageSetting ps = mSettings.mPackages.get(packageName); 18742 if (ps != null) { 18743 pkg = ps.pkg; 18744 } 18745 } 18746 18747 if (pkg == null) { 18748 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18749 return false; 18750 } 18751 18752 PackageSetting ps = (PackageSetting) pkg.mExtras; 18753 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18754 } 18755 18756 clearAppDataLIF(pkg, userId, 18757 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18758 18759 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18760 removeKeystoreDataIfNeeded(userId, appId); 18761 18762 UserManagerInternal umInternal = getUserManagerInternal(); 18763 final int flags; 18764 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18765 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18766 } else if (umInternal.isUserRunning(userId)) { 18767 flags = StorageManager.FLAG_STORAGE_DE; 18768 } else { 18769 flags = 0; 18770 } 18771 prepareAppDataContentsLIF(pkg, userId, flags); 18772 18773 return true; 18774 } 18775 18776 /** 18777 * Reverts user permission state changes (permissions and flags) in 18778 * all packages for a given user. 18779 * 18780 * @param userId The device user for which to do a reset. 18781 */ 18782 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18783 final int packageCount = mPackages.size(); 18784 for (int i = 0; i < packageCount; i++) { 18785 PackageParser.Package pkg = mPackages.valueAt(i); 18786 PackageSetting ps = (PackageSetting) pkg.mExtras; 18787 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18788 } 18789 } 18790 18791 private void resetNetworkPolicies(int userId) { 18792 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18793 } 18794 18795 /** 18796 * Reverts user permission state changes (permissions and flags). 18797 * 18798 * @param ps The package for which to reset. 18799 * @param userId The device user for which to do a reset. 18800 */ 18801 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18802 final PackageSetting ps, final int userId) { 18803 if (ps.pkg == null) { 18804 return; 18805 } 18806 18807 // These are flags that can change base on user actions. 18808 final int userSettableMask = FLAG_PERMISSION_USER_SET 18809 | FLAG_PERMISSION_USER_FIXED 18810 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18811 | FLAG_PERMISSION_REVIEW_REQUIRED; 18812 18813 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18814 | FLAG_PERMISSION_POLICY_FIXED; 18815 18816 boolean writeInstallPermissions = false; 18817 boolean writeRuntimePermissions = false; 18818 18819 final int permissionCount = ps.pkg.requestedPermissions.size(); 18820 for (int i = 0; i < permissionCount; i++) { 18821 final String permName = ps.pkg.requestedPermissions.get(i); 18822 final BasePermission bp = 18823 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 18824 if (bp == null) { 18825 continue; 18826 } 18827 18828 // If shared user we just reset the state to which only this app contributed. 18829 if (ps.sharedUser != null) { 18830 boolean used = false; 18831 final int packageCount = ps.sharedUser.packages.size(); 18832 for (int j = 0; j < packageCount; j++) { 18833 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18834 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18835 && pkg.pkg.requestedPermissions.contains(permName)) { 18836 used = true; 18837 break; 18838 } 18839 } 18840 if (used) { 18841 continue; 18842 } 18843 } 18844 18845 final PermissionsState permissionsState = ps.getPermissionsState(); 18846 18847 final int oldFlags = permissionsState.getPermissionFlags(permName, userId); 18848 18849 // Always clear the user settable flags. 18850 final boolean hasInstallState = 18851 permissionsState.getInstallPermissionState(permName) != null; 18852 // If permission review is enabled and this is a legacy app, mark the 18853 // permission as requiring a review as this is the initial state. 18854 int flags = 0; 18855 if (mSettings.mPermissions.mPermissionReviewRequired 18856 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18857 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18858 } 18859 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18860 if (hasInstallState) { 18861 writeInstallPermissions = true; 18862 } else { 18863 writeRuntimePermissions = true; 18864 } 18865 } 18866 18867 // Below is only runtime permission handling. 18868 if (!bp.isRuntime()) { 18869 continue; 18870 } 18871 18872 // Never clobber system or policy. 18873 if ((oldFlags & policyOrSystemFlags) != 0) { 18874 continue; 18875 } 18876 18877 // If this permission was granted by default, make sure it is. 18878 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18879 if (permissionsState.grantRuntimePermission(bp, userId) 18880 != PERMISSION_OPERATION_FAILURE) { 18881 writeRuntimePermissions = true; 18882 } 18883 // If permission review is enabled the permissions for a legacy apps 18884 // are represented as constantly granted runtime ones, so don't revoke. 18885 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18886 // Otherwise, reset the permission. 18887 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18888 switch (revokeResult) { 18889 case PERMISSION_OPERATION_SUCCESS: 18890 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18891 writeRuntimePermissions = true; 18892 final int appId = ps.appId; 18893 mHandler.post(new Runnable() { 18894 @Override 18895 public void run() { 18896 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18897 } 18898 }); 18899 } break; 18900 } 18901 } 18902 } 18903 18904 // Synchronously write as we are taking permissions away. 18905 if (writeRuntimePermissions) { 18906 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18907 } 18908 18909 // Synchronously write as we are taking permissions away. 18910 if (writeInstallPermissions) { 18911 mSettings.writeLPr(); 18912 } 18913 } 18914 18915 /** 18916 * Remove entries from the keystore daemon. Will only remove it if the 18917 * {@code appId} is valid. 18918 */ 18919 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18920 if (appId < 0) { 18921 return; 18922 } 18923 18924 final KeyStore keyStore = KeyStore.getInstance(); 18925 if (keyStore != null) { 18926 if (userId == UserHandle.USER_ALL) { 18927 for (final int individual : sUserManager.getUserIds()) { 18928 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18929 } 18930 } else { 18931 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18932 } 18933 } else { 18934 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18935 } 18936 } 18937 18938 @Override 18939 public void deleteApplicationCacheFiles(final String packageName, 18940 final IPackageDataObserver observer) { 18941 final int userId = UserHandle.getCallingUserId(); 18942 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18943 } 18944 18945 @Override 18946 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18947 final IPackageDataObserver observer) { 18948 final int callingUid = Binder.getCallingUid(); 18949 mContext.enforceCallingOrSelfPermission( 18950 android.Manifest.permission.DELETE_CACHE_FILES, null); 18951 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18952 /* requireFullPermission= */ true, /* checkShell= */ false, 18953 "delete application cache files"); 18954 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 18955 android.Manifest.permission.ACCESS_INSTANT_APPS); 18956 18957 final PackageParser.Package pkg; 18958 synchronized (mPackages) { 18959 pkg = mPackages.get(packageName); 18960 } 18961 18962 // Queue up an async operation since the package deletion may take a little while. 18963 mHandler.post(new Runnable() { 18964 public void run() { 18965 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 18966 boolean doClearData = true; 18967 if (ps != null) { 18968 final boolean targetIsInstantApp = 18969 ps.getInstantApp(UserHandle.getUserId(callingUid)); 18970 doClearData = !targetIsInstantApp 18971 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 18972 } 18973 if (doClearData) { 18974 synchronized (mInstallLock) { 18975 final int flags = StorageManager.FLAG_STORAGE_DE 18976 | StorageManager.FLAG_STORAGE_CE; 18977 // We're only clearing cache files, so we don't care if the 18978 // app is unfrozen and still able to run 18979 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18980 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18981 } 18982 clearExternalStorageDataSync(packageName, userId, false); 18983 } 18984 if (observer != null) { 18985 try { 18986 observer.onRemoveCompleted(packageName, true); 18987 } catch (RemoteException e) { 18988 Log.i(TAG, "Observer no longer exists."); 18989 } 18990 } 18991 } 18992 }); 18993 } 18994 18995 @Override 18996 public void getPackageSizeInfo(final String packageName, int userHandle, 18997 final IPackageStatsObserver observer) { 18998 throw new UnsupportedOperationException( 18999 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 19000 } 19001 19002 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 19003 final PackageSetting ps; 19004 synchronized (mPackages) { 19005 ps = mSettings.mPackages.get(packageName); 19006 if (ps == null) { 19007 Slog.w(TAG, "Failed to find settings for " + packageName); 19008 return false; 19009 } 19010 } 19011 19012 final String[] packageNames = { packageName }; 19013 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 19014 final String[] codePaths = { ps.codePathString }; 19015 19016 try { 19017 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 19018 ps.appId, ceDataInodes, codePaths, stats); 19019 19020 // For now, ignore code size of packages on system partition 19021 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 19022 stats.codeSize = 0; 19023 } 19024 19025 // External clients expect these to be tracked separately 19026 stats.dataSize -= stats.cacheSize; 19027 19028 } catch (InstallerException e) { 19029 Slog.w(TAG, String.valueOf(e)); 19030 return false; 19031 } 19032 19033 return true; 19034 } 19035 19036 private int getUidTargetSdkVersionLockedLPr(int uid) { 19037 Object obj = mSettings.getUserIdLPr(uid); 19038 if (obj instanceof SharedUserSetting) { 19039 final SharedUserSetting sus = (SharedUserSetting) obj; 19040 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 19041 final Iterator<PackageSetting> it = sus.packages.iterator(); 19042 while (it.hasNext()) { 19043 final PackageSetting ps = it.next(); 19044 if (ps.pkg != null) { 19045 int v = ps.pkg.applicationInfo.targetSdkVersion; 19046 if (v < vers) vers = v; 19047 } 19048 } 19049 return vers; 19050 } else if (obj instanceof PackageSetting) { 19051 final PackageSetting ps = (PackageSetting) obj; 19052 if (ps.pkg != null) { 19053 return ps.pkg.applicationInfo.targetSdkVersion; 19054 } 19055 } 19056 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19057 } 19058 19059 private int getPackageTargetSdkVersionLockedLPr(String packageName) { 19060 final PackageParser.Package p = mPackages.get(packageName); 19061 if (p != null) { 19062 return p.applicationInfo.targetSdkVersion; 19063 } 19064 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19065 } 19066 19067 @Override 19068 public void addPreferredActivity(IntentFilter filter, int match, 19069 ComponentName[] set, ComponentName activity, int userId) { 19070 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19071 "Adding preferred"); 19072 } 19073 19074 private void addPreferredActivityInternal(IntentFilter filter, int match, 19075 ComponentName[] set, ComponentName activity, boolean always, int userId, 19076 String opname) { 19077 // writer 19078 int callingUid = Binder.getCallingUid(); 19079 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19080 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 19081 if (filter.countActions() == 0) { 19082 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19083 return; 19084 } 19085 synchronized (mPackages) { 19086 if (mContext.checkCallingOrSelfPermission( 19087 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19088 != PackageManager.PERMISSION_GRANTED) { 19089 if (getUidTargetSdkVersionLockedLPr(callingUid) 19090 < Build.VERSION_CODES.FROYO) { 19091 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 19092 + callingUid); 19093 return; 19094 } 19095 mContext.enforceCallingOrSelfPermission( 19096 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19097 } 19098 19099 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 19100 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 19101 + userId + ":"); 19102 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19103 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 19104 scheduleWritePackageRestrictionsLocked(userId); 19105 postPreferredActivityChangedBroadcast(userId); 19106 } 19107 } 19108 19109 private void postPreferredActivityChangedBroadcast(int userId) { 19110 mHandler.post(() -> { 19111 final IActivityManager am = ActivityManager.getService(); 19112 if (am == null) { 19113 return; 19114 } 19115 19116 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 19117 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 19118 try { 19119 am.broadcastIntent(null, intent, null, null, 19120 0, null, null, null, android.app.AppOpsManager.OP_NONE, 19121 null, false, false, userId); 19122 } catch (RemoteException e) { 19123 } 19124 }); 19125 } 19126 19127 @Override 19128 public void replacePreferredActivity(IntentFilter filter, int match, 19129 ComponentName[] set, ComponentName activity, int userId) { 19130 if (filter.countActions() != 1) { 19131 throw new IllegalArgumentException( 19132 "replacePreferredActivity expects filter to have only 1 action."); 19133 } 19134 if (filter.countDataAuthorities() != 0 19135 || filter.countDataPaths() != 0 19136 || filter.countDataSchemes() > 1 19137 || filter.countDataTypes() != 0) { 19138 throw new IllegalArgumentException( 19139 "replacePreferredActivity expects filter to have no data authorities, " + 19140 "paths, or types; and at most one scheme."); 19141 } 19142 19143 final int callingUid = Binder.getCallingUid(); 19144 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19145 true /* requireFullPermission */, false /* checkShell */, 19146 "replace preferred activity"); 19147 synchronized (mPackages) { 19148 if (mContext.checkCallingOrSelfPermission( 19149 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19150 != PackageManager.PERMISSION_GRANTED) { 19151 if (getUidTargetSdkVersionLockedLPr(callingUid) 19152 < Build.VERSION_CODES.FROYO) { 19153 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 19154 + Binder.getCallingUid()); 19155 return; 19156 } 19157 mContext.enforceCallingOrSelfPermission( 19158 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19159 } 19160 19161 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19162 if (pir != null) { 19163 // Get all of the existing entries that exactly match this filter. 19164 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 19165 if (existing != null && existing.size() == 1) { 19166 PreferredActivity cur = existing.get(0); 19167 if (DEBUG_PREFERRED) { 19168 Slog.i(TAG, "Checking replace of preferred:"); 19169 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19170 if (!cur.mPref.mAlways) { 19171 Slog.i(TAG, " -- CUR; not mAlways!"); 19172 } else { 19173 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19174 Slog.i(TAG, " -- CUR: mSet=" 19175 + Arrays.toString(cur.mPref.mSetComponents)); 19176 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19177 Slog.i(TAG, " -- NEW: mMatch=" 19178 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19179 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19180 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19181 } 19182 } 19183 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19184 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19185 && cur.mPref.sameSet(set)) { 19186 // Setting the preferred activity to what it happens to be already 19187 if (DEBUG_PREFERRED) { 19188 Slog.i(TAG, "Replacing with same preferred activity " 19189 + cur.mPref.mShortComponent + " for user " 19190 + userId + ":"); 19191 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19192 } 19193 return; 19194 } 19195 } 19196 19197 if (existing != null) { 19198 if (DEBUG_PREFERRED) { 19199 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19200 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19201 } 19202 for (int i = 0; i < existing.size(); i++) { 19203 PreferredActivity pa = existing.get(i); 19204 if (DEBUG_PREFERRED) { 19205 Slog.i(TAG, "Removing existing preferred activity " 19206 + pa.mPref.mComponent + ":"); 19207 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19208 } 19209 pir.removeFilter(pa); 19210 } 19211 } 19212 } 19213 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19214 "Replacing preferred"); 19215 } 19216 } 19217 19218 @Override 19219 public void clearPackagePreferredActivities(String packageName) { 19220 final int callingUid = Binder.getCallingUid(); 19221 if (getInstantAppPackageName(callingUid) != null) { 19222 return; 19223 } 19224 // writer 19225 synchronized (mPackages) { 19226 PackageParser.Package pkg = mPackages.get(packageName); 19227 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 19228 if (mContext.checkCallingOrSelfPermission( 19229 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19230 != PackageManager.PERMISSION_GRANTED) { 19231 if (getUidTargetSdkVersionLockedLPr(callingUid) 19232 < Build.VERSION_CODES.FROYO) { 19233 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19234 + callingUid); 19235 return; 19236 } 19237 mContext.enforceCallingOrSelfPermission( 19238 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19239 } 19240 } 19241 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19242 if (ps != null 19243 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 19244 return; 19245 } 19246 int user = UserHandle.getCallingUserId(); 19247 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19248 scheduleWritePackageRestrictionsLocked(user); 19249 } 19250 } 19251 } 19252 19253 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19254 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19255 ArrayList<PreferredActivity> removed = null; 19256 boolean changed = false; 19257 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19258 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19259 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19260 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19261 continue; 19262 } 19263 Iterator<PreferredActivity> it = pir.filterIterator(); 19264 while (it.hasNext()) { 19265 PreferredActivity pa = it.next(); 19266 // Mark entry for removal only if it matches the package name 19267 // and the entry is of type "always". 19268 if (packageName == null || 19269 (pa.mPref.mComponent.getPackageName().equals(packageName) 19270 && pa.mPref.mAlways)) { 19271 if (removed == null) { 19272 removed = new ArrayList<PreferredActivity>(); 19273 } 19274 removed.add(pa); 19275 } 19276 } 19277 if (removed != null) { 19278 for (int j=0; j<removed.size(); j++) { 19279 PreferredActivity pa = removed.get(j); 19280 pir.removeFilter(pa); 19281 } 19282 changed = true; 19283 } 19284 } 19285 if (changed) { 19286 postPreferredActivityChangedBroadcast(userId); 19287 } 19288 return changed; 19289 } 19290 19291 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19292 private void clearIntentFilterVerificationsLPw(int userId) { 19293 final int packageCount = mPackages.size(); 19294 for (int i = 0; i < packageCount; i++) { 19295 PackageParser.Package pkg = mPackages.valueAt(i); 19296 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19297 } 19298 } 19299 19300 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19301 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19302 if (userId == UserHandle.USER_ALL) { 19303 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19304 sUserManager.getUserIds())) { 19305 for (int oneUserId : sUserManager.getUserIds()) { 19306 scheduleWritePackageRestrictionsLocked(oneUserId); 19307 } 19308 } 19309 } else { 19310 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19311 scheduleWritePackageRestrictionsLocked(userId); 19312 } 19313 } 19314 } 19315 19316 /** Clears state for all users, and touches intent filter verification policy */ 19317 void clearDefaultBrowserIfNeeded(String packageName) { 19318 for (int oneUserId : sUserManager.getUserIds()) { 19319 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19320 } 19321 } 19322 19323 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19324 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19325 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19326 if (packageName.equals(defaultBrowserPackageName)) { 19327 setDefaultBrowserPackageName(null, userId); 19328 } 19329 } 19330 } 19331 19332 @Override 19333 public void resetApplicationPreferences(int userId) { 19334 mContext.enforceCallingOrSelfPermission( 19335 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19336 final long identity = Binder.clearCallingIdentity(); 19337 // writer 19338 try { 19339 synchronized (mPackages) { 19340 clearPackagePreferredActivitiesLPw(null, userId); 19341 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19342 // TODO: We have to reset the default SMS and Phone. This requires 19343 // significant refactoring to keep all default apps in the package 19344 // manager (cleaner but more work) or have the services provide 19345 // callbacks to the package manager to request a default app reset. 19346 applyFactoryDefaultBrowserLPw(userId); 19347 clearIntentFilterVerificationsLPw(userId); 19348 primeDomainVerificationsLPw(userId); 19349 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19350 scheduleWritePackageRestrictionsLocked(userId); 19351 } 19352 resetNetworkPolicies(userId); 19353 } finally { 19354 Binder.restoreCallingIdentity(identity); 19355 } 19356 } 19357 19358 @Override 19359 public int getPreferredActivities(List<IntentFilter> outFilters, 19360 List<ComponentName> outActivities, String packageName) { 19361 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19362 return 0; 19363 } 19364 int num = 0; 19365 final int userId = UserHandle.getCallingUserId(); 19366 // reader 19367 synchronized (mPackages) { 19368 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19369 if (pir != null) { 19370 final Iterator<PreferredActivity> it = pir.filterIterator(); 19371 while (it.hasNext()) { 19372 final PreferredActivity pa = it.next(); 19373 if (packageName == null 19374 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19375 && pa.mPref.mAlways)) { 19376 if (outFilters != null) { 19377 outFilters.add(new IntentFilter(pa)); 19378 } 19379 if (outActivities != null) { 19380 outActivities.add(pa.mPref.mComponent); 19381 } 19382 } 19383 } 19384 } 19385 } 19386 19387 return num; 19388 } 19389 19390 @Override 19391 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19392 int userId) { 19393 int callingUid = Binder.getCallingUid(); 19394 if (callingUid != Process.SYSTEM_UID) { 19395 throw new SecurityException( 19396 "addPersistentPreferredActivity can only be run by the system"); 19397 } 19398 if (filter.countActions() == 0) { 19399 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19400 return; 19401 } 19402 synchronized (mPackages) { 19403 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19404 ":"); 19405 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19406 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19407 new PersistentPreferredActivity(filter, activity)); 19408 scheduleWritePackageRestrictionsLocked(userId); 19409 postPreferredActivityChangedBroadcast(userId); 19410 } 19411 } 19412 19413 @Override 19414 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19415 int callingUid = Binder.getCallingUid(); 19416 if (callingUid != Process.SYSTEM_UID) { 19417 throw new SecurityException( 19418 "clearPackagePersistentPreferredActivities can only be run by the system"); 19419 } 19420 ArrayList<PersistentPreferredActivity> removed = null; 19421 boolean changed = false; 19422 synchronized (mPackages) { 19423 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19424 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19425 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19426 .valueAt(i); 19427 if (userId != thisUserId) { 19428 continue; 19429 } 19430 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19431 while (it.hasNext()) { 19432 PersistentPreferredActivity ppa = it.next(); 19433 // Mark entry for removal only if it matches the package name. 19434 if (ppa.mComponent.getPackageName().equals(packageName)) { 19435 if (removed == null) { 19436 removed = new ArrayList<PersistentPreferredActivity>(); 19437 } 19438 removed.add(ppa); 19439 } 19440 } 19441 if (removed != null) { 19442 for (int j=0; j<removed.size(); j++) { 19443 PersistentPreferredActivity ppa = removed.get(j); 19444 ppir.removeFilter(ppa); 19445 } 19446 changed = true; 19447 } 19448 } 19449 19450 if (changed) { 19451 scheduleWritePackageRestrictionsLocked(userId); 19452 postPreferredActivityChangedBroadcast(userId); 19453 } 19454 } 19455 } 19456 19457 /** 19458 * Common machinery for picking apart a restored XML blob and passing 19459 * it to a caller-supplied functor to be applied to the running system. 19460 */ 19461 private void restoreFromXml(XmlPullParser parser, int userId, 19462 String expectedStartTag, BlobXmlRestorer functor) 19463 throws IOException, XmlPullParserException { 19464 int type; 19465 while ((type = parser.next()) != XmlPullParser.START_TAG 19466 && type != XmlPullParser.END_DOCUMENT) { 19467 } 19468 if (type != XmlPullParser.START_TAG) { 19469 // oops didn't find a start tag?! 19470 if (DEBUG_BACKUP) { 19471 Slog.e(TAG, "Didn't find start tag during restore"); 19472 } 19473 return; 19474 } 19475Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19476 // this is supposed to be TAG_PREFERRED_BACKUP 19477 if (!expectedStartTag.equals(parser.getName())) { 19478 if (DEBUG_BACKUP) { 19479 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19480 } 19481 return; 19482 } 19483 19484 // skip interfering stuff, then we're aligned with the backing implementation 19485 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19486Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19487 functor.apply(parser, userId); 19488 } 19489 19490 private interface BlobXmlRestorer { 19491 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19492 } 19493 19494 /** 19495 * Non-Binder method, support for the backup/restore mechanism: write the 19496 * full set of preferred activities in its canonical XML format. Returns the 19497 * XML output as a byte array, or null if there is none. 19498 */ 19499 @Override 19500 public byte[] getPreferredActivityBackup(int userId) { 19501 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19502 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19503 } 19504 19505 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19506 try { 19507 final XmlSerializer serializer = new FastXmlSerializer(); 19508 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19509 serializer.startDocument(null, true); 19510 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19511 19512 synchronized (mPackages) { 19513 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19514 } 19515 19516 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19517 serializer.endDocument(); 19518 serializer.flush(); 19519 } catch (Exception e) { 19520 if (DEBUG_BACKUP) { 19521 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19522 } 19523 return null; 19524 } 19525 19526 return dataStream.toByteArray(); 19527 } 19528 19529 @Override 19530 public void restorePreferredActivities(byte[] backup, int userId) { 19531 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19532 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19533 } 19534 19535 try { 19536 final XmlPullParser parser = Xml.newPullParser(); 19537 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19538 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19539 new BlobXmlRestorer() { 19540 @Override 19541 public void apply(XmlPullParser parser, int userId) 19542 throws XmlPullParserException, IOException { 19543 synchronized (mPackages) { 19544 mSettings.readPreferredActivitiesLPw(parser, userId); 19545 } 19546 } 19547 } ); 19548 } catch (Exception e) { 19549 if (DEBUG_BACKUP) { 19550 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19551 } 19552 } 19553 } 19554 19555 /** 19556 * Non-Binder method, support for the backup/restore mechanism: write the 19557 * default browser (etc) settings in its canonical XML format. Returns the default 19558 * browser XML representation as a byte array, or null if there is none. 19559 */ 19560 @Override 19561 public byte[] getDefaultAppsBackup(int userId) { 19562 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19563 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19564 } 19565 19566 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19567 try { 19568 final XmlSerializer serializer = new FastXmlSerializer(); 19569 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19570 serializer.startDocument(null, true); 19571 serializer.startTag(null, TAG_DEFAULT_APPS); 19572 19573 synchronized (mPackages) { 19574 mSettings.writeDefaultAppsLPr(serializer, userId); 19575 } 19576 19577 serializer.endTag(null, TAG_DEFAULT_APPS); 19578 serializer.endDocument(); 19579 serializer.flush(); 19580 } catch (Exception e) { 19581 if (DEBUG_BACKUP) { 19582 Slog.e(TAG, "Unable to write default apps for backup", e); 19583 } 19584 return null; 19585 } 19586 19587 return dataStream.toByteArray(); 19588 } 19589 19590 @Override 19591 public void restoreDefaultApps(byte[] backup, int userId) { 19592 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19593 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19594 } 19595 19596 try { 19597 final XmlPullParser parser = Xml.newPullParser(); 19598 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19599 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19600 new BlobXmlRestorer() { 19601 @Override 19602 public void apply(XmlPullParser parser, int userId) 19603 throws XmlPullParserException, IOException { 19604 synchronized (mPackages) { 19605 mSettings.readDefaultAppsLPw(parser, userId); 19606 } 19607 } 19608 } ); 19609 } catch (Exception e) { 19610 if (DEBUG_BACKUP) { 19611 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19612 } 19613 } 19614 } 19615 19616 @Override 19617 public byte[] getIntentFilterVerificationBackup(int userId) { 19618 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19619 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19620 } 19621 19622 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19623 try { 19624 final XmlSerializer serializer = new FastXmlSerializer(); 19625 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19626 serializer.startDocument(null, true); 19627 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19628 19629 synchronized (mPackages) { 19630 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19631 } 19632 19633 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19634 serializer.endDocument(); 19635 serializer.flush(); 19636 } catch (Exception e) { 19637 if (DEBUG_BACKUP) { 19638 Slog.e(TAG, "Unable to write default apps for backup", e); 19639 } 19640 return null; 19641 } 19642 19643 return dataStream.toByteArray(); 19644 } 19645 19646 @Override 19647 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19648 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19649 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19650 } 19651 19652 try { 19653 final XmlPullParser parser = Xml.newPullParser(); 19654 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19655 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19656 new BlobXmlRestorer() { 19657 @Override 19658 public void apply(XmlPullParser parser, int userId) 19659 throws XmlPullParserException, IOException { 19660 synchronized (mPackages) { 19661 mSettings.readAllDomainVerificationsLPr(parser, userId); 19662 mSettings.writeLPr(); 19663 } 19664 } 19665 } ); 19666 } catch (Exception e) { 19667 if (DEBUG_BACKUP) { 19668 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19669 } 19670 } 19671 } 19672 19673 @Override 19674 public byte[] getPermissionGrantBackup(int userId) { 19675 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19676 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19677 } 19678 19679 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19680 try { 19681 final XmlSerializer serializer = new FastXmlSerializer(); 19682 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19683 serializer.startDocument(null, true); 19684 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19685 19686 synchronized (mPackages) { 19687 serializeRuntimePermissionGrantsLPr(serializer, userId); 19688 } 19689 19690 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19691 serializer.endDocument(); 19692 serializer.flush(); 19693 } catch (Exception e) { 19694 if (DEBUG_BACKUP) { 19695 Slog.e(TAG, "Unable to write default apps for backup", e); 19696 } 19697 return null; 19698 } 19699 19700 return dataStream.toByteArray(); 19701 } 19702 19703 @Override 19704 public void restorePermissionGrants(byte[] backup, int userId) { 19705 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19706 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19707 } 19708 19709 try { 19710 final XmlPullParser parser = Xml.newPullParser(); 19711 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19712 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19713 new BlobXmlRestorer() { 19714 @Override 19715 public void apply(XmlPullParser parser, int userId) 19716 throws XmlPullParserException, IOException { 19717 synchronized (mPackages) { 19718 processRestoredPermissionGrantsLPr(parser, userId); 19719 } 19720 } 19721 } ); 19722 } catch (Exception e) { 19723 if (DEBUG_BACKUP) { 19724 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19725 } 19726 } 19727 } 19728 19729 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19730 throws IOException { 19731 serializer.startTag(null, TAG_ALL_GRANTS); 19732 19733 final int N = mSettings.mPackages.size(); 19734 for (int i = 0; i < N; i++) { 19735 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19736 boolean pkgGrantsKnown = false; 19737 19738 PermissionsState packagePerms = ps.getPermissionsState(); 19739 19740 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19741 final int grantFlags = state.getFlags(); 19742 // only look at grants that are not system/policy fixed 19743 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19744 final boolean isGranted = state.isGranted(); 19745 // And only back up the user-twiddled state bits 19746 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19747 final String packageName = mSettings.mPackages.keyAt(i); 19748 if (!pkgGrantsKnown) { 19749 serializer.startTag(null, TAG_GRANT); 19750 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19751 pkgGrantsKnown = true; 19752 } 19753 19754 final boolean userSet = 19755 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19756 final boolean userFixed = 19757 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19758 final boolean revoke = 19759 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19760 19761 serializer.startTag(null, TAG_PERMISSION); 19762 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19763 if (isGranted) { 19764 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19765 } 19766 if (userSet) { 19767 serializer.attribute(null, ATTR_USER_SET, "true"); 19768 } 19769 if (userFixed) { 19770 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19771 } 19772 if (revoke) { 19773 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19774 } 19775 serializer.endTag(null, TAG_PERMISSION); 19776 } 19777 } 19778 } 19779 19780 if (pkgGrantsKnown) { 19781 serializer.endTag(null, TAG_GRANT); 19782 } 19783 } 19784 19785 serializer.endTag(null, TAG_ALL_GRANTS); 19786 } 19787 19788 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19789 throws XmlPullParserException, IOException { 19790 String pkgName = null; 19791 int outerDepth = parser.getDepth(); 19792 int type; 19793 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19794 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19795 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19796 continue; 19797 } 19798 19799 final String tagName = parser.getName(); 19800 if (tagName.equals(TAG_GRANT)) { 19801 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19802 if (DEBUG_BACKUP) { 19803 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19804 } 19805 } else if (tagName.equals(TAG_PERMISSION)) { 19806 19807 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19808 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19809 19810 int newFlagSet = 0; 19811 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19812 newFlagSet |= FLAG_PERMISSION_USER_SET; 19813 } 19814 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19815 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19816 } 19817 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19818 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19819 } 19820 if (DEBUG_BACKUP) { 19821 Slog.v(TAG, " + Restoring grant:" 19822 + " pkg=" + pkgName 19823 + " perm=" + permName 19824 + " granted=" + isGranted 19825 + " bits=0x" + Integer.toHexString(newFlagSet)); 19826 } 19827 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19828 if (ps != null) { 19829 // Already installed so we apply the grant immediately 19830 if (DEBUG_BACKUP) { 19831 Slog.v(TAG, " + already installed; applying"); 19832 } 19833 PermissionsState perms = ps.getPermissionsState(); 19834 BasePermission bp = 19835 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 19836 if (bp != null) { 19837 if (isGranted) { 19838 perms.grantRuntimePermission(bp, userId); 19839 } 19840 if (newFlagSet != 0) { 19841 perms.updatePermissionFlags( 19842 bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19843 } 19844 } 19845 } else { 19846 // Need to wait for post-restore install to apply the grant 19847 if (DEBUG_BACKUP) { 19848 Slog.v(TAG, " - not yet installed; saving for later"); 19849 } 19850 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19851 isGranted, newFlagSet, userId); 19852 } 19853 } else { 19854 PackageManagerService.reportSettingsProblem(Log.WARN, 19855 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19856 XmlUtils.skipCurrentTag(parser); 19857 } 19858 } 19859 19860 scheduleWriteSettingsLocked(); 19861 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19862 } 19863 19864 @Override 19865 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19866 int sourceUserId, int targetUserId, int flags) { 19867 mContext.enforceCallingOrSelfPermission( 19868 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19869 int callingUid = Binder.getCallingUid(); 19870 enforceOwnerRights(ownerPackage, callingUid); 19871 PackageManagerServiceUtils.enforceShellRestriction( 19872 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19873 if (intentFilter.countActions() == 0) { 19874 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19875 return; 19876 } 19877 synchronized (mPackages) { 19878 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19879 ownerPackage, targetUserId, flags); 19880 CrossProfileIntentResolver resolver = 19881 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19882 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19883 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19884 if (existing != null) { 19885 int size = existing.size(); 19886 for (int i = 0; i < size; i++) { 19887 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19888 return; 19889 } 19890 } 19891 } 19892 resolver.addFilter(newFilter); 19893 scheduleWritePackageRestrictionsLocked(sourceUserId); 19894 } 19895 } 19896 19897 @Override 19898 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19899 mContext.enforceCallingOrSelfPermission( 19900 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19901 final int callingUid = Binder.getCallingUid(); 19902 enforceOwnerRights(ownerPackage, callingUid); 19903 PackageManagerServiceUtils.enforceShellRestriction( 19904 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19905 synchronized (mPackages) { 19906 CrossProfileIntentResolver resolver = 19907 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19908 ArraySet<CrossProfileIntentFilter> set = 19909 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19910 for (CrossProfileIntentFilter filter : set) { 19911 if (filter.getOwnerPackage().equals(ownerPackage)) { 19912 resolver.removeFilter(filter); 19913 } 19914 } 19915 scheduleWritePackageRestrictionsLocked(sourceUserId); 19916 } 19917 } 19918 19919 // Enforcing that callingUid is owning pkg on userId 19920 private void enforceOwnerRights(String pkg, int callingUid) { 19921 // The system owns everything. 19922 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19923 return; 19924 } 19925 final int callingUserId = UserHandle.getUserId(callingUid); 19926 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19927 if (pi == null) { 19928 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19929 + callingUserId); 19930 } 19931 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19932 throw new SecurityException("Calling uid " + callingUid 19933 + " does not own package " + pkg); 19934 } 19935 } 19936 19937 @Override 19938 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19939 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19940 return null; 19941 } 19942 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19943 } 19944 19945 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 19946 UserManagerService ums = UserManagerService.getInstance(); 19947 if (ums != null) { 19948 final UserInfo parent = ums.getProfileParent(userId); 19949 final int launcherUid = (parent != null) ? parent.id : userId; 19950 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 19951 if (launcherComponent != null) { 19952 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 19953 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 19954 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 19955 .setPackage(launcherComponent.getPackageName()); 19956 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 19957 } 19958 } 19959 } 19960 19961 /** 19962 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19963 * then reports the most likely home activity or null if there are more than one. 19964 */ 19965 private ComponentName getDefaultHomeActivity(int userId) { 19966 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19967 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19968 if (cn != null) { 19969 return cn; 19970 } 19971 19972 // Find the launcher with the highest priority and return that component if there are no 19973 // other home activity with the same priority. 19974 int lastPriority = Integer.MIN_VALUE; 19975 ComponentName lastComponent = null; 19976 final int size = allHomeCandidates.size(); 19977 for (int i = 0; i < size; i++) { 19978 final ResolveInfo ri = allHomeCandidates.get(i); 19979 if (ri.priority > lastPriority) { 19980 lastComponent = ri.activityInfo.getComponentName(); 19981 lastPriority = ri.priority; 19982 } else if (ri.priority == lastPriority) { 19983 // Two components found with same priority. 19984 lastComponent = null; 19985 } 19986 } 19987 return lastComponent; 19988 } 19989 19990 private Intent getHomeIntent() { 19991 Intent intent = new Intent(Intent.ACTION_MAIN); 19992 intent.addCategory(Intent.CATEGORY_HOME); 19993 intent.addCategory(Intent.CATEGORY_DEFAULT); 19994 return intent; 19995 } 19996 19997 private IntentFilter getHomeFilter() { 19998 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19999 filter.addCategory(Intent.CATEGORY_HOME); 20000 filter.addCategory(Intent.CATEGORY_DEFAULT); 20001 return filter; 20002 } 20003 20004 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20005 int userId) { 20006 Intent intent = getHomeIntent(); 20007 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 20008 PackageManager.GET_META_DATA, userId); 20009 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 20010 true, false, false, userId); 20011 20012 allHomeCandidates.clear(); 20013 if (list != null) { 20014 for (ResolveInfo ri : list) { 20015 allHomeCandidates.add(ri); 20016 } 20017 } 20018 return (preferred == null || preferred.activityInfo == null) 20019 ? null 20020 : new ComponentName(preferred.activityInfo.packageName, 20021 preferred.activityInfo.name); 20022 } 20023 20024 @Override 20025 public void setHomeActivity(ComponentName comp, int userId) { 20026 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20027 return; 20028 } 20029 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 20030 getHomeActivitiesAsUser(homeActivities, userId); 20031 20032 boolean found = false; 20033 20034 final int size = homeActivities.size(); 20035 final ComponentName[] set = new ComponentName[size]; 20036 for (int i = 0; i < size; i++) { 20037 final ResolveInfo candidate = homeActivities.get(i); 20038 final ActivityInfo info = candidate.activityInfo; 20039 final ComponentName activityName = new ComponentName(info.packageName, info.name); 20040 set[i] = activityName; 20041 if (!found && activityName.equals(comp)) { 20042 found = true; 20043 } 20044 } 20045 if (!found) { 20046 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 20047 + userId); 20048 } 20049 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 20050 set, comp, userId); 20051 } 20052 20053 private @Nullable String getSetupWizardPackageName() { 20054 final Intent intent = new Intent(Intent.ACTION_MAIN); 20055 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 20056 20057 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20058 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20059 | MATCH_DISABLED_COMPONENTS, 20060 UserHandle.myUserId()); 20061 if (matches.size() == 1) { 20062 return matches.get(0).getComponentInfo().packageName; 20063 } else { 20064 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 20065 + ": matches=" + matches); 20066 return null; 20067 } 20068 } 20069 20070 private @Nullable String getStorageManagerPackageName() { 20071 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 20072 20073 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20074 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20075 | MATCH_DISABLED_COMPONENTS, 20076 UserHandle.myUserId()); 20077 if (matches.size() == 1) { 20078 return matches.get(0).getComponentInfo().packageName; 20079 } else { 20080 Slog.e(TAG, "There should probably be exactly one storage manager; found " 20081 + matches.size() + ": matches=" + matches); 20082 return null; 20083 } 20084 } 20085 20086 @Override 20087 public void setApplicationEnabledSetting(String appPackageName, 20088 int newState, int flags, int userId, String callingPackage) { 20089 if (!sUserManager.exists(userId)) return; 20090 if (callingPackage == null) { 20091 callingPackage = Integer.toString(Binder.getCallingUid()); 20092 } 20093 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 20094 } 20095 20096 @Override 20097 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 20098 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 20099 synchronized (mPackages) { 20100 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 20101 if (pkgSetting != null) { 20102 pkgSetting.setUpdateAvailable(updateAvailable); 20103 } 20104 } 20105 } 20106 20107 @Override 20108 public void setComponentEnabledSetting(ComponentName componentName, 20109 int newState, int flags, int userId) { 20110 if (!sUserManager.exists(userId)) return; 20111 setEnabledSetting(componentName.getPackageName(), 20112 componentName.getClassName(), newState, flags, userId, null); 20113 } 20114 20115 private void setEnabledSetting(final String packageName, String className, int newState, 20116 final int flags, int userId, String callingPackage) { 20117 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 20118 || newState == COMPONENT_ENABLED_STATE_ENABLED 20119 || newState == COMPONENT_ENABLED_STATE_DISABLED 20120 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20121 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 20122 throw new IllegalArgumentException("Invalid new component state: " 20123 + newState); 20124 } 20125 PackageSetting pkgSetting; 20126 final int callingUid = Binder.getCallingUid(); 20127 final int permission; 20128 if (callingUid == Process.SYSTEM_UID) { 20129 permission = PackageManager.PERMISSION_GRANTED; 20130 } else { 20131 permission = mContext.checkCallingOrSelfPermission( 20132 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20133 } 20134 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20135 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 20136 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20137 boolean sendNow = false; 20138 boolean isApp = (className == null); 20139 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 20140 String componentName = isApp ? packageName : className; 20141 int packageUid = -1; 20142 ArrayList<String> components; 20143 20144 // reader 20145 synchronized (mPackages) { 20146 pkgSetting = mSettings.mPackages.get(packageName); 20147 if (pkgSetting == null) { 20148 if (!isCallerInstantApp) { 20149 if (className == null) { 20150 throw new IllegalArgumentException("Unknown package: " + packageName); 20151 } 20152 throw new IllegalArgumentException( 20153 "Unknown component: " + packageName + "/" + className); 20154 } else { 20155 // throw SecurityException to prevent leaking package information 20156 throw new SecurityException( 20157 "Attempt to change component state; " 20158 + "pid=" + Binder.getCallingPid() 20159 + ", uid=" + callingUid 20160 + (className == null 20161 ? ", package=" + packageName 20162 : ", component=" + packageName + "/" + className)); 20163 } 20164 } 20165 } 20166 20167 // Limit who can change which apps 20168 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 20169 // Don't allow apps that don't have permission to modify other apps 20170 if (!allowedByPermission 20171 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 20172 throw new SecurityException( 20173 "Attempt to change component state; " 20174 + "pid=" + Binder.getCallingPid() 20175 + ", uid=" + callingUid 20176 + (className == null 20177 ? ", package=" + packageName 20178 : ", component=" + packageName + "/" + className)); 20179 } 20180 // Don't allow changing protected packages. 20181 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 20182 throw new SecurityException("Cannot disable a protected package: " + packageName); 20183 } 20184 } 20185 20186 synchronized (mPackages) { 20187 if (callingUid == Process.SHELL_UID 20188 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 20189 // Shell can only change whole packages between ENABLED and DISABLED_USER states 20190 // unless it is a test package. 20191 int oldState = pkgSetting.getEnabled(userId); 20192 if (className == null 20193 && 20194 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 20195 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 20196 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 20197 && 20198 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20199 || newState == COMPONENT_ENABLED_STATE_DEFAULT 20200 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 20201 // ok 20202 } else { 20203 throw new SecurityException( 20204 "Shell cannot change component state for " + packageName + "/" 20205 + className + " to " + newState); 20206 } 20207 } 20208 } 20209 if (className == null) { 20210 // We're dealing with an application/package level state change 20211 synchronized (mPackages) { 20212 if (pkgSetting.getEnabled(userId) == newState) { 20213 // Nothing to do 20214 return; 20215 } 20216 } 20217 // If we're enabling a system stub, there's a little more work to do. 20218 // Prior to enabling the package, we need to decompress the APK(s) to the 20219 // data partition and then replace the version on the system partition. 20220 final PackageParser.Package deletedPkg = pkgSetting.pkg; 20221 final boolean isSystemStub = deletedPkg.isStub 20222 && deletedPkg.isSystem(); 20223 if (isSystemStub 20224 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20225 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 20226 final File codePath = decompressPackage(deletedPkg); 20227 if (codePath == null) { 20228 Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name); 20229 return; 20230 } 20231 // TODO remove direct parsing of the package object during internal cleanup 20232 // of scan package 20233 // We need to call parse directly here for no other reason than we need 20234 // the new package in order to disable the old one [we use the information 20235 // for some internal optimization to optionally create a new package setting 20236 // object on replace]. However, we can't get the package from the scan 20237 // because the scan modifies live structures and we need to remove the 20238 // old [system] package from the system before a scan can be attempted. 20239 // Once scan is indempotent we can remove this parse and use the package 20240 // object we scanned, prior to adding it to package settings. 20241 final PackageParser pp = new PackageParser(); 20242 pp.setSeparateProcesses(mSeparateProcesses); 20243 pp.setDisplayMetrics(mMetrics); 20244 pp.setCallback(mPackageParserCallback); 20245 final PackageParser.Package tmpPkg; 20246 try { 20247 final @ParseFlags int parseFlags = mDefParseFlags 20248 | PackageParser.PARSE_MUST_BE_APK 20249 | PackageParser.PARSE_IS_SYSTEM_DIR; 20250 tmpPkg = pp.parsePackage(codePath, parseFlags); 20251 } catch (PackageParserException e) { 20252 Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e); 20253 return; 20254 } 20255 synchronized (mInstallLock) { 20256 // Disable the stub and remove any package entries 20257 removePackageLI(deletedPkg, true); 20258 synchronized (mPackages) { 20259 disableSystemPackageLPw(deletedPkg, tmpPkg); 20260 } 20261 final PackageParser.Package pkg; 20262 try (PackageFreezer freezer = 20263 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20264 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 20265 | PackageParser.PARSE_ENFORCE_CODE; 20266 pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 20267 0 /*currentTime*/, null /*user*/); 20268 prepareAppDataAfterInstallLIF(pkg); 20269 synchronized (mPackages) { 20270 try { 20271 updateSharedLibrariesLPr(pkg, null); 20272 } catch (PackageManagerException e) { 20273 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 20274 } 20275 mPermissionManager.updatePermissions( 20276 pkg.packageName, pkg, true, mPackages.values(), 20277 mPermissionCallback); 20278 mSettings.writeLPr(); 20279 } 20280 } catch (PackageManagerException e) { 20281 // Whoops! Something went wrong; try to roll back to the stub 20282 Slog.w(TAG, "Failed to install compressed system package:" 20283 + pkgSetting.name, e); 20284 // Remove the failed install 20285 removeCodePathLI(codePath); 20286 20287 // Install the system package 20288 try (PackageFreezer freezer = 20289 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20290 synchronized (mPackages) { 20291 // NOTE: The system package always needs to be enabled; even 20292 // if it's for a compressed stub. If we don't, installing the 20293 // system package fails during scan [scanning checks the disabled 20294 // packages]. We will reverse this later, after we've "installed" 20295 // the stub. 20296 // This leaves us in a fragile state; the stub should never be 20297 // enabled, so, cross your fingers and hope nothing goes wrong 20298 // until we can disable the package later. 20299 enableSystemPackageLPw(deletedPkg); 20300 } 20301 installPackageFromSystemLIF(deletedPkg.codePath, 20302 false /*isPrivileged*/, null /*allUserHandles*/, 20303 null /*origUserHandles*/, null /*origPermissionsState*/, 20304 true /*writeSettings*/); 20305 } catch (PackageManagerException pme) { 20306 Slog.w(TAG, "Failed to restore system package:" 20307 + deletedPkg.packageName, pme); 20308 } finally { 20309 synchronized (mPackages) { 20310 mSettings.disableSystemPackageLPw( 20311 deletedPkg.packageName, true /*replaced*/); 20312 mSettings.writeLPr(); 20313 } 20314 } 20315 return; 20316 } 20317 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE 20318 | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20319 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 20320 mDexManager.notifyPackageUpdated(pkg.packageName, 20321 pkg.baseCodePath, pkg.splitCodePaths); 20322 } 20323 } 20324 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20325 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20326 // Don't care about who enables an app. 20327 callingPackage = null; 20328 } 20329 synchronized (mPackages) { 20330 pkgSetting.setEnabled(newState, userId, callingPackage); 20331 } 20332 } else { 20333 synchronized (mPackages) { 20334 // We're dealing with a component level state change 20335 // First, verify that this is a valid class name. 20336 PackageParser.Package pkg = pkgSetting.pkg; 20337 if (pkg == null || !pkg.hasComponentClassName(className)) { 20338 if (pkg != null && 20339 pkg.applicationInfo.targetSdkVersion >= 20340 Build.VERSION_CODES.JELLY_BEAN) { 20341 throw new IllegalArgumentException("Component class " + className 20342 + " does not exist in " + packageName); 20343 } else { 20344 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20345 + className + " does not exist in " + packageName); 20346 } 20347 } 20348 switch (newState) { 20349 case COMPONENT_ENABLED_STATE_ENABLED: 20350 if (!pkgSetting.enableComponentLPw(className, userId)) { 20351 return; 20352 } 20353 break; 20354 case COMPONENT_ENABLED_STATE_DISABLED: 20355 if (!pkgSetting.disableComponentLPw(className, userId)) { 20356 return; 20357 } 20358 break; 20359 case COMPONENT_ENABLED_STATE_DEFAULT: 20360 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20361 return; 20362 } 20363 break; 20364 default: 20365 Slog.e(TAG, "Invalid new component state: " + newState); 20366 return; 20367 } 20368 } 20369 } 20370 synchronized (mPackages) { 20371 scheduleWritePackageRestrictionsLocked(userId); 20372 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 20373 final long callingId = Binder.clearCallingIdentity(); 20374 try { 20375 updateInstantAppInstallerLocked(packageName); 20376 } finally { 20377 Binder.restoreCallingIdentity(callingId); 20378 } 20379 components = mPendingBroadcasts.get(userId, packageName); 20380 final boolean newPackage = components == null; 20381 if (newPackage) { 20382 components = new ArrayList<String>(); 20383 } 20384 if (!components.contains(componentName)) { 20385 components.add(componentName); 20386 } 20387 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20388 sendNow = true; 20389 // Purge entry from pending broadcast list if another one exists already 20390 // since we are sending one right away. 20391 mPendingBroadcasts.remove(userId, packageName); 20392 } else { 20393 if (newPackage) { 20394 mPendingBroadcasts.put(userId, packageName, components); 20395 } 20396 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20397 // Schedule a message 20398 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20399 } 20400 } 20401 } 20402 20403 long callingId = Binder.clearCallingIdentity(); 20404 try { 20405 if (sendNow) { 20406 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20407 sendPackageChangedBroadcast(packageName, 20408 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20409 } 20410 } finally { 20411 Binder.restoreCallingIdentity(callingId); 20412 } 20413 } 20414 20415 @Override 20416 public void flushPackageRestrictionsAsUser(int userId) { 20417 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20418 return; 20419 } 20420 if (!sUserManager.exists(userId)) { 20421 return; 20422 } 20423 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20424 false /* checkShell */, "flushPackageRestrictions"); 20425 synchronized (mPackages) { 20426 mSettings.writePackageRestrictionsLPr(userId); 20427 mDirtyUsers.remove(userId); 20428 if (mDirtyUsers.isEmpty()) { 20429 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20430 } 20431 } 20432 } 20433 20434 private void sendPackageChangedBroadcast(String packageName, 20435 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20436 if (DEBUG_INSTALL) 20437 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20438 + componentNames); 20439 Bundle extras = new Bundle(4); 20440 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20441 String nameList[] = new String[componentNames.size()]; 20442 componentNames.toArray(nameList); 20443 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20444 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20445 extras.putInt(Intent.EXTRA_UID, packageUid); 20446 // If this is not reporting a change of the overall package, then only send it 20447 // to registered receivers. We don't want to launch a swath of apps for every 20448 // little component state change. 20449 final int flags = !componentNames.contains(packageName) 20450 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20451 final int userId = UserHandle.getUserId(packageUid); 20452 final boolean isInstantApp = isInstantApp(packageName, userId); 20453 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 20454 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 20455 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20456 userIds, instantUserIds); 20457 } 20458 20459 @Override 20460 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20461 if (!sUserManager.exists(userId)) return; 20462 final int callingUid = Binder.getCallingUid(); 20463 if (getInstantAppPackageName(callingUid) != null) { 20464 return; 20465 } 20466 final int permission = mContext.checkCallingOrSelfPermission( 20467 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20468 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20469 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20470 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20471 // writer 20472 synchronized (mPackages) { 20473 final PackageSetting ps = mSettings.mPackages.get(packageName); 20474 if (!filterAppAccessLPr(ps, callingUid, userId) 20475 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20476 allowedByPermission, callingUid, userId)) { 20477 scheduleWritePackageRestrictionsLocked(userId); 20478 } 20479 } 20480 } 20481 20482 @Override 20483 public String getInstallerPackageName(String packageName) { 20484 final int callingUid = Binder.getCallingUid(); 20485 if (getInstantAppPackageName(callingUid) != null) { 20486 return null; 20487 } 20488 // reader 20489 synchronized (mPackages) { 20490 final PackageSetting ps = mSettings.mPackages.get(packageName); 20491 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20492 return null; 20493 } 20494 return mSettings.getInstallerPackageNameLPr(packageName); 20495 } 20496 } 20497 20498 public boolean isOrphaned(String packageName) { 20499 // reader 20500 synchronized (mPackages) { 20501 return mSettings.isOrphaned(packageName); 20502 } 20503 } 20504 20505 @Override 20506 public int getApplicationEnabledSetting(String packageName, int userId) { 20507 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20508 int callingUid = Binder.getCallingUid(); 20509 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20510 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20511 // reader 20512 synchronized (mPackages) { 20513 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 20514 return COMPONENT_ENABLED_STATE_DISABLED; 20515 } 20516 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20517 } 20518 } 20519 20520 @Override 20521 public int getComponentEnabledSetting(ComponentName component, int userId) { 20522 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20523 int callingUid = Binder.getCallingUid(); 20524 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20525 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 20526 synchronized (mPackages) { 20527 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 20528 component, TYPE_UNKNOWN, userId)) { 20529 return COMPONENT_ENABLED_STATE_DISABLED; 20530 } 20531 return mSettings.getComponentEnabledSettingLPr(component, userId); 20532 } 20533 } 20534 20535 @Override 20536 public void enterSafeMode() { 20537 enforceSystemOrRoot("Only the system can request entering safe mode"); 20538 20539 if (!mSystemReady) { 20540 mSafeMode = true; 20541 } 20542 } 20543 20544 @Override 20545 public void systemReady() { 20546 enforceSystemOrRoot("Only the system can claim the system is ready"); 20547 20548 mSystemReady = true; 20549 final ContentResolver resolver = mContext.getContentResolver(); 20550 ContentObserver co = new ContentObserver(mHandler) { 20551 @Override 20552 public void onChange(boolean selfChange) { 20553 mEphemeralAppsDisabled = 20554 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20555 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20556 } 20557 }; 20558 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20559 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20560 false, co, UserHandle.USER_SYSTEM); 20561 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20562 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20563 co.onChange(true); 20564 20565 // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to 20566 // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once 20567 // it is done. 20568 ContentObserver privAppOobObserver = new ContentObserver(mHandler) { 20569 @Override 20570 public void onChange(boolean selfChange) { 20571 int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0); 20572 SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, 20573 oobEnabled == 1 ? "true" : "false"); 20574 } 20575 }; 20576 mContext.getContentResolver().registerContentObserver( 20577 Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver, 20578 UserHandle.USER_SYSTEM); 20579 // At boot, restore the value from the setting, which persists across reboot. 20580 privAppOobObserver.onChange(true); 20581 20582 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20583 // disabled after already being started. 20584 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20585 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20586 20587 // Read the compatibilty setting when the system is ready. 20588 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20589 mContext.getContentResolver(), 20590 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20591 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20592 if (DEBUG_SETTINGS) { 20593 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20594 } 20595 20596 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20597 20598 synchronized (mPackages) { 20599 // Verify that all of the preferred activity components actually 20600 // exist. It is possible for applications to be updated and at 20601 // that point remove a previously declared activity component that 20602 // had been set as a preferred activity. We try to clean this up 20603 // the next time we encounter that preferred activity, but it is 20604 // possible for the user flow to never be able to return to that 20605 // situation so here we do a sanity check to make sure we haven't 20606 // left any junk around. 20607 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20608 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20609 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20610 removed.clear(); 20611 for (PreferredActivity pa : pir.filterSet()) { 20612 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20613 removed.add(pa); 20614 } 20615 } 20616 if (removed.size() > 0) { 20617 for (int r=0; r<removed.size(); r++) { 20618 PreferredActivity pa = removed.get(r); 20619 Slog.w(TAG, "Removing dangling preferred activity: " 20620 + pa.mPref.mComponent); 20621 pir.removeFilter(pa); 20622 } 20623 mSettings.writePackageRestrictionsLPr( 20624 mSettings.mPreferredActivities.keyAt(i)); 20625 } 20626 } 20627 20628 for (int userId : UserManagerService.getInstance().getUserIds()) { 20629 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20630 grantPermissionsUserIds = ArrayUtils.appendInt( 20631 grantPermissionsUserIds, userId); 20632 } 20633 } 20634 } 20635 sUserManager.systemReady(); 20636 // If we upgraded grant all default permissions before kicking off. 20637 for (int userId : grantPermissionsUserIds) { 20638 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20639 } 20640 20641 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20642 // If we did not grant default permissions, we preload from this the 20643 // default permission exceptions lazily to ensure we don't hit the 20644 // disk on a new user creation. 20645 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20646 } 20647 20648 // Now that we've scanned all packages, and granted any default 20649 // permissions, ensure permissions are updated. Beware of dragons if you 20650 // try optimizing this. 20651 synchronized (mPackages) { 20652 mPermissionManager.updateAllPermissions( 20653 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 20654 mPermissionCallback); 20655 } 20656 20657 // Kick off any messages waiting for system ready 20658 if (mPostSystemReadyMessages != null) { 20659 for (Message msg : mPostSystemReadyMessages) { 20660 msg.sendToTarget(); 20661 } 20662 mPostSystemReadyMessages = null; 20663 } 20664 20665 // Watch for external volumes that come and go over time 20666 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20667 storage.registerListener(mStorageListener); 20668 20669 mInstallerService.systemReady(); 20670 mPackageDexOptimizer.systemReady(); 20671 20672 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20673 StorageManagerInternal.class); 20674 StorageManagerInternal.addExternalStoragePolicy( 20675 new StorageManagerInternal.ExternalStorageMountPolicy() { 20676 @Override 20677 public int getMountMode(int uid, String packageName) { 20678 if (Process.isIsolated(uid)) { 20679 return Zygote.MOUNT_EXTERNAL_NONE; 20680 } 20681 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20682 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20683 } 20684 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20685 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20686 } 20687 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20688 return Zygote.MOUNT_EXTERNAL_READ; 20689 } 20690 return Zygote.MOUNT_EXTERNAL_WRITE; 20691 } 20692 20693 @Override 20694 public boolean hasExternalStorage(int uid, String packageName) { 20695 return true; 20696 } 20697 }); 20698 20699 // Now that we're mostly running, clean up stale users and apps 20700 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20701 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20702 20703 mPermissionManager.systemReady(); 20704 } 20705 20706 public void waitForAppDataPrepared() { 20707 if (mPrepareAppDataFuture == null) { 20708 return; 20709 } 20710 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20711 mPrepareAppDataFuture = null; 20712 } 20713 20714 @Override 20715 public boolean isSafeMode() { 20716 // allow instant applications 20717 return mSafeMode; 20718 } 20719 20720 @Override 20721 public boolean hasSystemUidErrors() { 20722 // allow instant applications 20723 return mHasSystemUidErrors; 20724 } 20725 20726 static String arrayToString(int[] array) { 20727 StringBuffer buf = new StringBuffer(128); 20728 buf.append('['); 20729 if (array != null) { 20730 for (int i=0; i<array.length; i++) { 20731 if (i > 0) buf.append(", "); 20732 buf.append(array[i]); 20733 } 20734 } 20735 buf.append(']'); 20736 return buf.toString(); 20737 } 20738 20739 @Override 20740 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20741 FileDescriptor err, String[] args, ShellCallback callback, 20742 ResultReceiver resultReceiver) { 20743 (new PackageManagerShellCommand(this)).exec( 20744 this, in, out, err, args, callback, resultReceiver); 20745 } 20746 20747 @Override 20748 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20749 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20750 20751 DumpState dumpState = new DumpState(); 20752 boolean fullPreferred = false; 20753 boolean checkin = false; 20754 20755 String packageName = null; 20756 ArraySet<String> permissionNames = null; 20757 20758 int opti = 0; 20759 while (opti < args.length) { 20760 String opt = args[opti]; 20761 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20762 break; 20763 } 20764 opti++; 20765 20766 if ("-a".equals(opt)) { 20767 // Right now we only know how to print all. 20768 } else if ("-h".equals(opt)) { 20769 pw.println("Package manager dump options:"); 20770 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20771 pw.println(" --checkin: dump for a checkin"); 20772 pw.println(" -f: print details of intent filters"); 20773 pw.println(" -h: print this help"); 20774 pw.println(" cmd may be one of:"); 20775 pw.println(" l[ibraries]: list known shared libraries"); 20776 pw.println(" f[eatures]: list device features"); 20777 pw.println(" k[eysets]: print known keysets"); 20778 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20779 pw.println(" perm[issions]: dump permissions"); 20780 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20781 pw.println(" pref[erred]: print preferred package settings"); 20782 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20783 pw.println(" prov[iders]: dump content providers"); 20784 pw.println(" p[ackages]: dump installed packages"); 20785 pw.println(" s[hared-users]: dump shared user IDs"); 20786 pw.println(" m[essages]: print collected runtime messages"); 20787 pw.println(" v[erifiers]: print package verifier info"); 20788 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20789 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20790 pw.println(" version: print database version info"); 20791 pw.println(" write: write current settings now"); 20792 pw.println(" installs: details about install sessions"); 20793 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20794 pw.println(" dexopt: dump dexopt state"); 20795 pw.println(" compiler-stats: dump compiler statistics"); 20796 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20797 pw.println(" service-permissions: dump permissions required by services"); 20798 pw.println(" <package.name>: info about given package"); 20799 return; 20800 } else if ("--checkin".equals(opt)) { 20801 checkin = true; 20802 } else if ("-f".equals(opt)) { 20803 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20804 } else if ("--proto".equals(opt)) { 20805 dumpProto(fd); 20806 return; 20807 } else { 20808 pw.println("Unknown argument: " + opt + "; use -h for help"); 20809 } 20810 } 20811 20812 // Is the caller requesting to dump a particular piece of data? 20813 if (opti < args.length) { 20814 String cmd = args[opti]; 20815 opti++; 20816 // Is this a package name? 20817 if ("android".equals(cmd) || cmd.contains(".")) { 20818 packageName = cmd; 20819 // When dumping a single package, we always dump all of its 20820 // filter information since the amount of data will be reasonable. 20821 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20822 } else if ("check-permission".equals(cmd)) { 20823 if (opti >= args.length) { 20824 pw.println("Error: check-permission missing permission argument"); 20825 return; 20826 } 20827 String perm = args[opti]; 20828 opti++; 20829 if (opti >= args.length) { 20830 pw.println("Error: check-permission missing package argument"); 20831 return; 20832 } 20833 20834 String pkg = args[opti]; 20835 opti++; 20836 int user = UserHandle.getUserId(Binder.getCallingUid()); 20837 if (opti < args.length) { 20838 try { 20839 user = Integer.parseInt(args[opti]); 20840 } catch (NumberFormatException e) { 20841 pw.println("Error: check-permission user argument is not a number: " 20842 + args[opti]); 20843 return; 20844 } 20845 } 20846 20847 // Normalize package name to handle renamed packages and static libs 20848 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20849 20850 pw.println(checkPermission(perm, pkg, user)); 20851 return; 20852 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20853 dumpState.setDump(DumpState.DUMP_LIBS); 20854 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20855 dumpState.setDump(DumpState.DUMP_FEATURES); 20856 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20857 if (opti >= args.length) { 20858 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20859 | DumpState.DUMP_SERVICE_RESOLVERS 20860 | DumpState.DUMP_RECEIVER_RESOLVERS 20861 | DumpState.DUMP_CONTENT_RESOLVERS); 20862 } else { 20863 while (opti < args.length) { 20864 String name = args[opti]; 20865 if ("a".equals(name) || "activity".equals(name)) { 20866 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20867 } else if ("s".equals(name) || "service".equals(name)) { 20868 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20869 } else if ("r".equals(name) || "receiver".equals(name)) { 20870 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20871 } else if ("c".equals(name) || "content".equals(name)) { 20872 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20873 } else { 20874 pw.println("Error: unknown resolver table type: " + name); 20875 return; 20876 } 20877 opti++; 20878 } 20879 } 20880 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20881 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20882 } else if ("permission".equals(cmd)) { 20883 if (opti >= args.length) { 20884 pw.println("Error: permission requires permission name"); 20885 return; 20886 } 20887 permissionNames = new ArraySet<>(); 20888 while (opti < args.length) { 20889 permissionNames.add(args[opti]); 20890 opti++; 20891 } 20892 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20893 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20894 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20895 dumpState.setDump(DumpState.DUMP_PREFERRED); 20896 } else if ("preferred-xml".equals(cmd)) { 20897 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20898 if (opti < args.length && "--full".equals(args[opti])) { 20899 fullPreferred = true; 20900 opti++; 20901 } 20902 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20903 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20904 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20905 dumpState.setDump(DumpState.DUMP_PACKAGES); 20906 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20907 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20908 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20909 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20910 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20911 dumpState.setDump(DumpState.DUMP_MESSAGES); 20912 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20913 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20914 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20915 || "intent-filter-verifiers".equals(cmd)) { 20916 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20917 } else if ("version".equals(cmd)) { 20918 dumpState.setDump(DumpState.DUMP_VERSION); 20919 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20920 dumpState.setDump(DumpState.DUMP_KEYSETS); 20921 } else if ("installs".equals(cmd)) { 20922 dumpState.setDump(DumpState.DUMP_INSTALLS); 20923 } else if ("frozen".equals(cmd)) { 20924 dumpState.setDump(DumpState.DUMP_FROZEN); 20925 } else if ("volumes".equals(cmd)) { 20926 dumpState.setDump(DumpState.DUMP_VOLUMES); 20927 } else if ("dexopt".equals(cmd)) { 20928 dumpState.setDump(DumpState.DUMP_DEXOPT); 20929 } else if ("compiler-stats".equals(cmd)) { 20930 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20931 } else if ("changes".equals(cmd)) { 20932 dumpState.setDump(DumpState.DUMP_CHANGES); 20933 } else if ("service-permissions".equals(cmd)) { 20934 dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS); 20935 } else if ("write".equals(cmd)) { 20936 synchronized (mPackages) { 20937 mSettings.writeLPr(); 20938 pw.println("Settings written."); 20939 return; 20940 } 20941 } 20942 } 20943 20944 if (checkin) { 20945 pw.println("vers,1"); 20946 } 20947 20948 // reader 20949 synchronized (mPackages) { 20950 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20951 if (!checkin) { 20952 if (dumpState.onTitlePrinted()) 20953 pw.println(); 20954 pw.println("Database versions:"); 20955 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20956 } 20957 } 20958 20959 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20960 if (!checkin) { 20961 if (dumpState.onTitlePrinted()) 20962 pw.println(); 20963 pw.println("Verifiers:"); 20964 pw.print(" Required: "); 20965 pw.print(mRequiredVerifierPackage); 20966 pw.print(" (uid="); 20967 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20968 UserHandle.USER_SYSTEM)); 20969 pw.println(")"); 20970 } else if (mRequiredVerifierPackage != null) { 20971 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20972 pw.print(","); 20973 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20974 UserHandle.USER_SYSTEM)); 20975 } 20976 } 20977 20978 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20979 packageName == null) { 20980 if (mIntentFilterVerifierComponent != null) { 20981 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20982 if (!checkin) { 20983 if (dumpState.onTitlePrinted()) 20984 pw.println(); 20985 pw.println("Intent Filter Verifier:"); 20986 pw.print(" Using: "); 20987 pw.print(verifierPackageName); 20988 pw.print(" (uid="); 20989 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20990 UserHandle.USER_SYSTEM)); 20991 pw.println(")"); 20992 } else if (verifierPackageName != null) { 20993 pw.print("ifv,"); pw.print(verifierPackageName); 20994 pw.print(","); 20995 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20996 UserHandle.USER_SYSTEM)); 20997 } 20998 } else { 20999 pw.println(); 21000 pw.println("No Intent Filter Verifier available!"); 21001 } 21002 } 21003 21004 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 21005 boolean printedHeader = false; 21006 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 21007 while (it.hasNext()) { 21008 String libName = it.next(); 21009 LongSparseArray<SharedLibraryEntry> versionedLib 21010 = mSharedLibraries.get(libName); 21011 if (versionedLib == null) { 21012 continue; 21013 } 21014 final int versionCount = versionedLib.size(); 21015 for (int i = 0; i < versionCount; i++) { 21016 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 21017 if (!checkin) { 21018 if (!printedHeader) { 21019 if (dumpState.onTitlePrinted()) 21020 pw.println(); 21021 pw.println("Libraries:"); 21022 printedHeader = true; 21023 } 21024 pw.print(" "); 21025 } else { 21026 pw.print("lib,"); 21027 } 21028 pw.print(libEntry.info.getName()); 21029 if (libEntry.info.isStatic()) { 21030 pw.print(" version=" + libEntry.info.getLongVersion()); 21031 } 21032 if (!checkin) { 21033 pw.print(" -> "); 21034 } 21035 if (libEntry.path != null) { 21036 pw.print(" (jar) "); 21037 pw.print(libEntry.path); 21038 } else { 21039 pw.print(" (apk) "); 21040 pw.print(libEntry.apk); 21041 } 21042 pw.println(); 21043 } 21044 } 21045 } 21046 21047 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 21048 if (dumpState.onTitlePrinted()) 21049 pw.println(); 21050 if (!checkin) { 21051 pw.println("Features:"); 21052 } 21053 21054 synchronized (mAvailableFeatures) { 21055 for (FeatureInfo feat : mAvailableFeatures.values()) { 21056 if (checkin) { 21057 pw.print("feat,"); 21058 pw.print(feat.name); 21059 pw.print(","); 21060 pw.println(feat.version); 21061 } else { 21062 pw.print(" "); 21063 pw.print(feat.name); 21064 if (feat.version > 0) { 21065 pw.print(" version="); 21066 pw.print(feat.version); 21067 } 21068 pw.println(); 21069 } 21070 } 21071 } 21072 } 21073 21074 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 21075 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 21076 : "Activity Resolver Table:", " ", packageName, 21077 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21078 dumpState.setTitlePrinted(true); 21079 } 21080 } 21081 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 21082 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 21083 : "Receiver Resolver Table:", " ", packageName, 21084 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21085 dumpState.setTitlePrinted(true); 21086 } 21087 } 21088 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 21089 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 21090 : "Service Resolver Table:", " ", packageName, 21091 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21092 dumpState.setTitlePrinted(true); 21093 } 21094 } 21095 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 21096 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 21097 : "Provider Resolver Table:", " ", packageName, 21098 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21099 dumpState.setTitlePrinted(true); 21100 } 21101 } 21102 21103 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 21104 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21105 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21106 int user = mSettings.mPreferredActivities.keyAt(i); 21107 if (pir.dump(pw, 21108 dumpState.getTitlePrinted() 21109 ? "\nPreferred Activities User " + user + ":" 21110 : "Preferred Activities User " + user + ":", " ", 21111 packageName, true, false)) { 21112 dumpState.setTitlePrinted(true); 21113 } 21114 } 21115 } 21116 21117 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 21118 pw.flush(); 21119 FileOutputStream fout = new FileOutputStream(fd); 21120 BufferedOutputStream str = new BufferedOutputStream(fout); 21121 XmlSerializer serializer = new FastXmlSerializer(); 21122 try { 21123 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 21124 serializer.startDocument(null, true); 21125 serializer.setFeature( 21126 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 21127 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 21128 serializer.endDocument(); 21129 serializer.flush(); 21130 } catch (IllegalArgumentException e) { 21131 pw.println("Failed writing: " + e); 21132 } catch (IllegalStateException e) { 21133 pw.println("Failed writing: " + e); 21134 } catch (IOException e) { 21135 pw.println("Failed writing: " + e); 21136 } 21137 } 21138 21139 if (!checkin 21140 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 21141 && packageName == null) { 21142 pw.println(); 21143 int count = mSettings.mPackages.size(); 21144 if (count == 0) { 21145 pw.println("No applications!"); 21146 pw.println(); 21147 } else { 21148 final String prefix = " "; 21149 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 21150 if (allPackageSettings.size() == 0) { 21151 pw.println("No domain preferred apps!"); 21152 pw.println(); 21153 } else { 21154 pw.println("App verification status:"); 21155 pw.println(); 21156 count = 0; 21157 for (PackageSetting ps : allPackageSettings) { 21158 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 21159 if (ivi == null || ivi.getPackageName() == null) continue; 21160 pw.println(prefix + "Package: " + ivi.getPackageName()); 21161 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 21162 pw.println(prefix + "Status: " + ivi.getStatusString()); 21163 pw.println(); 21164 count++; 21165 } 21166 if (count == 0) { 21167 pw.println(prefix + "No app verification established."); 21168 pw.println(); 21169 } 21170 for (int userId : sUserManager.getUserIds()) { 21171 pw.println("App linkages for user " + userId + ":"); 21172 pw.println(); 21173 count = 0; 21174 for (PackageSetting ps : allPackageSettings) { 21175 final long status = ps.getDomainVerificationStatusForUser(userId); 21176 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 21177 && !DEBUG_DOMAIN_VERIFICATION) { 21178 continue; 21179 } 21180 pw.println(prefix + "Package: " + ps.name); 21181 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 21182 String statusStr = IntentFilterVerificationInfo. 21183 getStatusStringFromValue(status); 21184 pw.println(prefix + "Status: " + statusStr); 21185 pw.println(); 21186 count++; 21187 } 21188 if (count == 0) { 21189 pw.println(prefix + "No configured app linkages."); 21190 pw.println(); 21191 } 21192 } 21193 } 21194 } 21195 } 21196 21197 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 21198 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 21199 } 21200 21201 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 21202 boolean printedSomething = false; 21203 for (PackageParser.Provider p : mProviders.mProviders.values()) { 21204 if (packageName != null && !packageName.equals(p.info.packageName)) { 21205 continue; 21206 } 21207 if (!printedSomething) { 21208 if (dumpState.onTitlePrinted()) 21209 pw.println(); 21210 pw.println("Registered ContentProviders:"); 21211 printedSomething = true; 21212 } 21213 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 21214 pw.print(" "); pw.println(p.toString()); 21215 } 21216 printedSomething = false; 21217 for (Map.Entry<String, PackageParser.Provider> entry : 21218 mProvidersByAuthority.entrySet()) { 21219 PackageParser.Provider p = entry.getValue(); 21220 if (packageName != null && !packageName.equals(p.info.packageName)) { 21221 continue; 21222 } 21223 if (!printedSomething) { 21224 if (dumpState.onTitlePrinted()) 21225 pw.println(); 21226 pw.println("ContentProvider Authorities:"); 21227 printedSomething = true; 21228 } 21229 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 21230 pw.print(" "); pw.println(p.toString()); 21231 if (p.info != null && p.info.applicationInfo != null) { 21232 final String appInfo = p.info.applicationInfo.toString(); 21233 pw.print(" applicationInfo="); pw.println(appInfo); 21234 } 21235 } 21236 } 21237 21238 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 21239 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 21240 } 21241 21242 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 21243 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 21244 } 21245 21246 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 21247 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 21248 } 21249 21250 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 21251 if (dumpState.onTitlePrinted()) pw.println(); 21252 pw.println("Package Changes:"); 21253 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 21254 final int K = mChangedPackages.size(); 21255 for (int i = 0; i < K; i++) { 21256 final SparseArray<String> changes = mChangedPackages.valueAt(i); 21257 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 21258 final int N = changes.size(); 21259 if (N == 0) { 21260 pw.print(" "); pw.println("No packages changed"); 21261 } else { 21262 for (int j = 0; j < N; j++) { 21263 final String pkgName = changes.valueAt(j); 21264 final int sequenceNumber = changes.keyAt(j); 21265 pw.print(" "); 21266 pw.print("seq="); 21267 pw.print(sequenceNumber); 21268 pw.print(", package="); 21269 pw.println(pkgName); 21270 } 21271 } 21272 } 21273 } 21274 21275 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 21276 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 21277 } 21278 21279 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21280 // XXX should handle packageName != null by dumping only install data that 21281 // the given package is involved with. 21282 if (dumpState.onTitlePrinted()) pw.println(); 21283 21284 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21285 ipw.println(); 21286 ipw.println("Frozen packages:"); 21287 ipw.increaseIndent(); 21288 if (mFrozenPackages.size() == 0) { 21289 ipw.println("(none)"); 21290 } else { 21291 for (int i = 0; i < mFrozenPackages.size(); i++) { 21292 ipw.println(mFrozenPackages.valueAt(i)); 21293 } 21294 } 21295 ipw.decreaseIndent(); 21296 } 21297 21298 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 21299 if (dumpState.onTitlePrinted()) pw.println(); 21300 21301 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21302 ipw.println(); 21303 ipw.println("Loaded volumes:"); 21304 ipw.increaseIndent(); 21305 if (mLoadedVolumes.size() == 0) { 21306 ipw.println("(none)"); 21307 } else { 21308 for (int i = 0; i < mLoadedVolumes.size(); i++) { 21309 ipw.println(mLoadedVolumes.valueAt(i)); 21310 } 21311 } 21312 ipw.decreaseIndent(); 21313 } 21314 21315 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS) 21316 && packageName == null) { 21317 if (dumpState.onTitlePrinted()) pw.println(); 21318 pw.println("Service permissions:"); 21319 21320 final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator(); 21321 while (filterIterator.hasNext()) { 21322 final ServiceIntentInfo info = filterIterator.next(); 21323 final ServiceInfo serviceInfo = info.service.info; 21324 final String permission = serviceInfo.permission; 21325 if (permission != null) { 21326 pw.print(" "); 21327 pw.print(serviceInfo.getComponentName().flattenToShortString()); 21328 pw.print(": "); 21329 pw.println(permission); 21330 } 21331 } 21332 } 21333 21334 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21335 if (dumpState.onTitlePrinted()) pw.println(); 21336 dumpDexoptStateLPr(pw, packageName); 21337 } 21338 21339 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21340 if (dumpState.onTitlePrinted()) pw.println(); 21341 dumpCompilerStatsLPr(pw, packageName); 21342 } 21343 21344 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21345 if (dumpState.onTitlePrinted()) pw.println(); 21346 mSettings.dumpReadMessagesLPr(pw, dumpState); 21347 21348 pw.println(); 21349 pw.println("Package warning messages:"); 21350 dumpCriticalInfo(pw, null); 21351 } 21352 21353 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21354 dumpCriticalInfo(pw, "msg,"); 21355 } 21356 } 21357 21358 // PackageInstaller should be called outside of mPackages lock 21359 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21360 // XXX should handle packageName != null by dumping only install data that 21361 // the given package is involved with. 21362 if (dumpState.onTitlePrinted()) pw.println(); 21363 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21364 } 21365 } 21366 21367 private void dumpProto(FileDescriptor fd) { 21368 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21369 21370 synchronized (mPackages) { 21371 final long requiredVerifierPackageToken = 21372 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21373 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21374 proto.write( 21375 PackageServiceDumpProto.PackageShortProto.UID, 21376 getPackageUid( 21377 mRequiredVerifierPackage, 21378 MATCH_DEBUG_TRIAGED_MISSING, 21379 UserHandle.USER_SYSTEM)); 21380 proto.end(requiredVerifierPackageToken); 21381 21382 if (mIntentFilterVerifierComponent != null) { 21383 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21384 final long verifierPackageToken = 21385 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21386 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21387 proto.write( 21388 PackageServiceDumpProto.PackageShortProto.UID, 21389 getPackageUid( 21390 verifierPackageName, 21391 MATCH_DEBUG_TRIAGED_MISSING, 21392 UserHandle.USER_SYSTEM)); 21393 proto.end(verifierPackageToken); 21394 } 21395 21396 dumpSharedLibrariesProto(proto); 21397 dumpFeaturesProto(proto); 21398 mSettings.dumpPackagesProto(proto); 21399 mSettings.dumpSharedUsersProto(proto); 21400 dumpCriticalInfo(proto); 21401 } 21402 proto.flush(); 21403 } 21404 21405 private void dumpFeaturesProto(ProtoOutputStream proto) { 21406 synchronized (mAvailableFeatures) { 21407 final int count = mAvailableFeatures.size(); 21408 for (int i = 0; i < count; i++) { 21409 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES); 21410 } 21411 } 21412 } 21413 21414 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21415 final int count = mSharedLibraries.size(); 21416 for (int i = 0; i < count; i++) { 21417 final String libName = mSharedLibraries.keyAt(i); 21418 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21419 if (versionedLib == null) { 21420 continue; 21421 } 21422 final int versionCount = versionedLib.size(); 21423 for (int j = 0; j < versionCount; j++) { 21424 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21425 final long sharedLibraryToken = 21426 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21427 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21428 final boolean isJar = (libEntry.path != null); 21429 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21430 if (isJar) { 21431 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21432 } else { 21433 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21434 } 21435 proto.end(sharedLibraryToken); 21436 } 21437 } 21438 } 21439 21440 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21441 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21442 ipw.println(); 21443 ipw.println("Dexopt state:"); 21444 ipw.increaseIndent(); 21445 Collection<PackageParser.Package> packages = null; 21446 if (packageName != null) { 21447 PackageParser.Package targetPackage = mPackages.get(packageName); 21448 if (targetPackage != null) { 21449 packages = Collections.singletonList(targetPackage); 21450 } else { 21451 ipw.println("Unable to find package: " + packageName); 21452 return; 21453 } 21454 } else { 21455 packages = mPackages.values(); 21456 } 21457 21458 for (PackageParser.Package pkg : packages) { 21459 ipw.println("[" + pkg.packageName + "]"); 21460 ipw.increaseIndent(); 21461 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 21462 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 21463 ipw.decreaseIndent(); 21464 } 21465 } 21466 21467 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21468 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21469 ipw.println(); 21470 ipw.println("Compiler stats:"); 21471 ipw.increaseIndent(); 21472 Collection<PackageParser.Package> packages = null; 21473 if (packageName != null) { 21474 PackageParser.Package targetPackage = mPackages.get(packageName); 21475 if (targetPackage != null) { 21476 packages = Collections.singletonList(targetPackage); 21477 } else { 21478 ipw.println("Unable to find package: " + packageName); 21479 return; 21480 } 21481 } else { 21482 packages = mPackages.values(); 21483 } 21484 21485 for (PackageParser.Package pkg : packages) { 21486 ipw.println("[" + pkg.packageName + "]"); 21487 ipw.increaseIndent(); 21488 21489 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21490 if (stats == null) { 21491 ipw.println("(No recorded stats)"); 21492 } else { 21493 stats.dump(ipw); 21494 } 21495 ipw.decreaseIndent(); 21496 } 21497 } 21498 21499 private String dumpDomainString(String packageName) { 21500 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21501 .getList(); 21502 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21503 21504 ArraySet<String> result = new ArraySet<>(); 21505 if (iviList.size() > 0) { 21506 for (IntentFilterVerificationInfo ivi : iviList) { 21507 for (String host : ivi.getDomains()) { 21508 result.add(host); 21509 } 21510 } 21511 } 21512 if (filters != null && filters.size() > 0) { 21513 for (IntentFilter filter : filters) { 21514 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21515 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21516 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21517 result.addAll(filter.getHostsList()); 21518 } 21519 } 21520 } 21521 21522 StringBuilder sb = new StringBuilder(result.size() * 16); 21523 for (String domain : result) { 21524 if (sb.length() > 0) sb.append(" "); 21525 sb.append(domain); 21526 } 21527 return sb.toString(); 21528 } 21529 21530 // ------- apps on sdcard specific code ------- 21531 static final boolean DEBUG_SD_INSTALL = false; 21532 21533 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21534 21535 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21536 21537 private boolean mMediaMounted = false; 21538 21539 static String getEncryptKey() { 21540 try { 21541 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21542 SD_ENCRYPTION_KEYSTORE_NAME); 21543 if (sdEncKey == null) { 21544 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21545 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21546 if (sdEncKey == null) { 21547 Slog.e(TAG, "Failed to create encryption keys"); 21548 return null; 21549 } 21550 } 21551 return sdEncKey; 21552 } catch (NoSuchAlgorithmException nsae) { 21553 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21554 return null; 21555 } catch (IOException ioe) { 21556 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21557 return null; 21558 } 21559 } 21560 21561 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21562 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21563 final int size = infos.size(); 21564 final String[] packageNames = new String[size]; 21565 final int[] packageUids = new int[size]; 21566 for (int i = 0; i < size; i++) { 21567 final ApplicationInfo info = infos.get(i); 21568 packageNames[i] = info.packageName; 21569 packageUids[i] = info.uid; 21570 } 21571 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21572 finishedReceiver); 21573 } 21574 21575 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21576 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21577 sendResourcesChangedBroadcast(mediaStatus, replacing, 21578 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21579 } 21580 21581 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21582 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21583 int size = pkgList.length; 21584 if (size > 0) { 21585 // Send broadcasts here 21586 Bundle extras = new Bundle(); 21587 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21588 if (uidArr != null) { 21589 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21590 } 21591 if (replacing) { 21592 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21593 } 21594 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21595 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21596 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null); 21597 } 21598 } 21599 21600 private void loadPrivatePackages(final VolumeInfo vol) { 21601 mHandler.post(new Runnable() { 21602 @Override 21603 public void run() { 21604 loadPrivatePackagesInner(vol); 21605 } 21606 }); 21607 } 21608 21609 private void loadPrivatePackagesInner(VolumeInfo vol) { 21610 final String volumeUuid = vol.fsUuid; 21611 if (TextUtils.isEmpty(volumeUuid)) { 21612 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21613 return; 21614 } 21615 21616 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21617 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21618 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21619 21620 final VersionInfo ver; 21621 final List<PackageSetting> packages; 21622 synchronized (mPackages) { 21623 ver = mSettings.findOrCreateVersion(volumeUuid); 21624 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21625 } 21626 21627 for (PackageSetting ps : packages) { 21628 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21629 synchronized (mInstallLock) { 21630 final PackageParser.Package pkg; 21631 try { 21632 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21633 loaded.add(pkg.applicationInfo); 21634 21635 } catch (PackageManagerException e) { 21636 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21637 } 21638 21639 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21640 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21641 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21642 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21643 } 21644 } 21645 } 21646 21647 // Reconcile app data for all started/unlocked users 21648 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21649 final UserManager um = mContext.getSystemService(UserManager.class); 21650 UserManagerInternal umInternal = getUserManagerInternal(); 21651 for (UserInfo user : um.getUsers()) { 21652 final int flags; 21653 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21654 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21655 } else if (umInternal.isUserRunning(user.id)) { 21656 flags = StorageManager.FLAG_STORAGE_DE; 21657 } else { 21658 continue; 21659 } 21660 21661 try { 21662 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21663 synchronized (mInstallLock) { 21664 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21665 } 21666 } catch (IllegalStateException e) { 21667 // Device was probably ejected, and we'll process that event momentarily 21668 Slog.w(TAG, "Failed to prepare storage: " + e); 21669 } 21670 } 21671 21672 synchronized (mPackages) { 21673 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 21674 if (sdkUpdated) { 21675 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21676 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21677 } 21678 mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(), 21679 mPermissionCallback); 21680 21681 // Yay, everything is now upgraded 21682 ver.forceCurrent(); 21683 21684 mSettings.writeLPr(); 21685 } 21686 21687 for (PackageFreezer freezer : freezers) { 21688 freezer.close(); 21689 } 21690 21691 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21692 sendResourcesChangedBroadcast(true, false, loaded, null); 21693 mLoadedVolumes.add(vol.getId()); 21694 } 21695 21696 private void unloadPrivatePackages(final VolumeInfo vol) { 21697 mHandler.post(new Runnable() { 21698 @Override 21699 public void run() { 21700 unloadPrivatePackagesInner(vol); 21701 } 21702 }); 21703 } 21704 21705 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21706 final String volumeUuid = vol.fsUuid; 21707 if (TextUtils.isEmpty(volumeUuid)) { 21708 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21709 return; 21710 } 21711 21712 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21713 synchronized (mInstallLock) { 21714 synchronized (mPackages) { 21715 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21716 for (PackageSetting ps : packages) { 21717 if (ps.pkg == null) continue; 21718 21719 final ApplicationInfo info = ps.pkg.applicationInfo; 21720 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21721 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 21722 21723 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21724 "unloadPrivatePackagesInner")) { 21725 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21726 false, null)) { 21727 unloaded.add(info); 21728 } else { 21729 Slog.w(TAG, "Failed to unload " + ps.codePath); 21730 } 21731 } 21732 21733 // Try very hard to release any references to this package 21734 // so we don't risk the system server being killed due to 21735 // open FDs 21736 AttributeCache.instance().removePackage(ps.name); 21737 } 21738 21739 mSettings.writeLPr(); 21740 } 21741 } 21742 21743 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21744 sendResourcesChangedBroadcast(false, false, unloaded, null); 21745 mLoadedVolumes.remove(vol.getId()); 21746 21747 // Try very hard to release any references to this path so we don't risk 21748 // the system server being killed due to open FDs 21749 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21750 21751 for (int i = 0; i < 3; i++) { 21752 System.gc(); 21753 System.runFinalization(); 21754 } 21755 } 21756 21757 private void assertPackageKnown(String volumeUuid, String packageName) 21758 throws PackageManagerException { 21759 synchronized (mPackages) { 21760 // Normalize package name to handle renamed packages 21761 packageName = normalizePackageNameLPr(packageName); 21762 21763 final PackageSetting ps = mSettings.mPackages.get(packageName); 21764 if (ps == null) { 21765 throw new PackageManagerException("Package " + packageName + " is unknown"); 21766 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21767 throw new PackageManagerException( 21768 "Package " + packageName + " found on unknown volume " + volumeUuid 21769 + "; expected volume " + ps.volumeUuid); 21770 } 21771 } 21772 } 21773 21774 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21775 throws PackageManagerException { 21776 synchronized (mPackages) { 21777 // Normalize package name to handle renamed packages 21778 packageName = normalizePackageNameLPr(packageName); 21779 21780 final PackageSetting ps = mSettings.mPackages.get(packageName); 21781 if (ps == null) { 21782 throw new PackageManagerException("Package " + packageName + " is unknown"); 21783 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21784 throw new PackageManagerException( 21785 "Package " + packageName + " found on unknown volume " + volumeUuid 21786 + "; expected volume " + ps.volumeUuid); 21787 } else if (!ps.getInstalled(userId)) { 21788 throw new PackageManagerException( 21789 "Package " + packageName + " not installed for user " + userId); 21790 } 21791 } 21792 } 21793 21794 private List<String> collectAbsoluteCodePaths() { 21795 synchronized (mPackages) { 21796 List<String> codePaths = new ArrayList<>(); 21797 final int packageCount = mSettings.mPackages.size(); 21798 for (int i = 0; i < packageCount; i++) { 21799 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21800 codePaths.add(ps.codePath.getAbsolutePath()); 21801 } 21802 return codePaths; 21803 } 21804 } 21805 21806 /** 21807 * Examine all apps present on given mounted volume, and destroy apps that 21808 * aren't expected, either due to uninstallation or reinstallation on 21809 * another volume. 21810 */ 21811 private void reconcileApps(String volumeUuid) { 21812 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21813 List<File> filesToDelete = null; 21814 21815 final File[] files = FileUtils.listFilesOrEmpty( 21816 Environment.getDataAppDirectory(volumeUuid)); 21817 for (File file : files) { 21818 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21819 && !PackageInstallerService.isStageName(file.getName()); 21820 if (!isPackage) { 21821 // Ignore entries which are not packages 21822 continue; 21823 } 21824 21825 String absolutePath = file.getAbsolutePath(); 21826 21827 boolean pathValid = false; 21828 final int absoluteCodePathCount = absoluteCodePaths.size(); 21829 for (int i = 0; i < absoluteCodePathCount; i++) { 21830 String absoluteCodePath = absoluteCodePaths.get(i); 21831 if (absolutePath.startsWith(absoluteCodePath)) { 21832 pathValid = true; 21833 break; 21834 } 21835 } 21836 21837 if (!pathValid) { 21838 if (filesToDelete == null) { 21839 filesToDelete = new ArrayList<>(); 21840 } 21841 filesToDelete.add(file); 21842 } 21843 } 21844 21845 if (filesToDelete != null) { 21846 final int fileToDeleteCount = filesToDelete.size(); 21847 for (int i = 0; i < fileToDeleteCount; i++) { 21848 File fileToDelete = filesToDelete.get(i); 21849 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21850 synchronized (mInstallLock) { 21851 removeCodePathLI(fileToDelete); 21852 } 21853 } 21854 } 21855 } 21856 21857 /** 21858 * Reconcile all app data for the given user. 21859 * <p> 21860 * Verifies that directories exist and that ownership and labeling is 21861 * correct for all installed apps on all mounted volumes. 21862 */ 21863 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21864 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21865 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21866 final String volumeUuid = vol.getFsUuid(); 21867 synchronized (mInstallLock) { 21868 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21869 } 21870 } 21871 } 21872 21873 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21874 boolean migrateAppData) { 21875 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21876 } 21877 21878 /** 21879 * Reconcile all app data on given mounted volume. 21880 * <p> 21881 * Destroys app data that isn't expected, either due to uninstallation or 21882 * reinstallation on another volume. 21883 * <p> 21884 * Verifies that directories exist and that ownership and labeling is 21885 * correct for all installed apps. 21886 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21887 */ 21888 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21889 boolean migrateAppData, boolean onlyCoreApps) { 21890 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21891 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21892 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21893 21894 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21895 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21896 21897 // First look for stale data that doesn't belong, and check if things 21898 // have changed since we did our last restorecon 21899 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21900 if (StorageManager.isFileEncryptedNativeOrEmulated() 21901 && !StorageManager.isUserKeyUnlocked(userId)) { 21902 throw new RuntimeException( 21903 "Yikes, someone asked us to reconcile CE storage while " + userId 21904 + " was still locked; this would have caused massive data loss!"); 21905 } 21906 21907 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21908 for (File file : files) { 21909 final String packageName = file.getName(); 21910 try { 21911 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21912 } catch (PackageManagerException e) { 21913 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21914 try { 21915 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21916 StorageManager.FLAG_STORAGE_CE, 0); 21917 } catch (InstallerException e2) { 21918 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21919 } 21920 } 21921 } 21922 } 21923 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21924 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21925 for (File file : files) { 21926 final String packageName = file.getName(); 21927 try { 21928 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21929 } catch (PackageManagerException e) { 21930 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21931 try { 21932 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21933 StorageManager.FLAG_STORAGE_DE, 0); 21934 } catch (InstallerException e2) { 21935 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21936 } 21937 } 21938 } 21939 } 21940 21941 // Ensure that data directories are ready to roll for all packages 21942 // installed for this volume and user 21943 final List<PackageSetting> packages; 21944 synchronized (mPackages) { 21945 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21946 } 21947 int preparedCount = 0; 21948 for (PackageSetting ps : packages) { 21949 final String packageName = ps.name; 21950 if (ps.pkg == null) { 21951 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21952 // TODO: might be due to legacy ASEC apps; we should circle back 21953 // and reconcile again once they're scanned 21954 continue; 21955 } 21956 // Skip non-core apps if requested 21957 if (onlyCoreApps && !ps.pkg.coreApp) { 21958 result.add(packageName); 21959 continue; 21960 } 21961 21962 if (ps.getInstalled(userId)) { 21963 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21964 preparedCount++; 21965 } 21966 } 21967 21968 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21969 return result; 21970 } 21971 21972 /** 21973 * Prepare app data for the given app just after it was installed or 21974 * upgraded. This method carefully only touches users that it's installed 21975 * for, and it forces a restorecon to handle any seinfo changes. 21976 * <p> 21977 * Verifies that directories exist and that ownership and labeling is 21978 * correct for all installed apps. If there is an ownership mismatch, it 21979 * will try recovering system apps by wiping data; third-party app data is 21980 * left intact. 21981 * <p> 21982 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21983 */ 21984 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21985 final PackageSetting ps; 21986 synchronized (mPackages) { 21987 ps = mSettings.mPackages.get(pkg.packageName); 21988 mSettings.writeKernelMappingLPr(ps); 21989 } 21990 21991 final UserManager um = mContext.getSystemService(UserManager.class); 21992 UserManagerInternal umInternal = getUserManagerInternal(); 21993 for (UserInfo user : um.getUsers()) { 21994 final int flags; 21995 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21996 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21997 } else if (umInternal.isUserRunning(user.id)) { 21998 flags = StorageManager.FLAG_STORAGE_DE; 21999 } else { 22000 continue; 22001 } 22002 22003 if (ps.getInstalled(user.id)) { 22004 // TODO: when user data is locked, mark that we're still dirty 22005 prepareAppDataLIF(pkg, user.id, flags); 22006 } 22007 } 22008 } 22009 22010 /** 22011 * Prepare app data for the given app. 22012 * <p> 22013 * Verifies that directories exist and that ownership and labeling is 22014 * correct for all installed apps. If there is an ownership mismatch, this 22015 * will try recovering system apps by wiping data; third-party app data is 22016 * left intact. 22017 */ 22018 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 22019 if (pkg == null) { 22020 Slog.wtf(TAG, "Package was null!", new Throwable()); 22021 return; 22022 } 22023 prepareAppDataLeafLIF(pkg, userId, flags); 22024 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22025 for (int i = 0; i < childCount; i++) { 22026 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 22027 } 22028 } 22029 22030 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 22031 boolean maybeMigrateAppData) { 22032 prepareAppDataLIF(pkg, userId, flags); 22033 22034 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 22035 // We may have just shuffled around app data directories, so 22036 // prepare them one more time 22037 prepareAppDataLIF(pkg, userId, flags); 22038 } 22039 } 22040 22041 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22042 if (DEBUG_APP_DATA) { 22043 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 22044 + Integer.toHexString(flags)); 22045 } 22046 22047 final String volumeUuid = pkg.volumeUuid; 22048 final String packageName = pkg.packageName; 22049 final ApplicationInfo app = pkg.applicationInfo; 22050 final int appId = UserHandle.getAppId(app.uid); 22051 22052 Preconditions.checkNotNull(app.seInfo); 22053 22054 long ceDataInode = -1; 22055 try { 22056 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22057 appId, app.seInfo, app.targetSdkVersion); 22058 } catch (InstallerException e) { 22059 if (app.isSystemApp()) { 22060 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 22061 + ", but trying to recover: " + e); 22062 destroyAppDataLeafLIF(pkg, userId, flags); 22063 try { 22064 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22065 appId, app.seInfo, app.targetSdkVersion); 22066 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 22067 } catch (InstallerException e2) { 22068 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 22069 } 22070 } else { 22071 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22072 } 22073 } 22074 22075 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22076 // TODO: mark this structure as dirty so we persist it! 22077 synchronized (mPackages) { 22078 final PackageSetting ps = mSettings.mPackages.get(packageName); 22079 if (ps != null) { 22080 ps.setCeDataInode(ceDataInode, userId); 22081 } 22082 } 22083 } 22084 22085 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22086 } 22087 22088 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22089 if (pkg == null) { 22090 Slog.wtf(TAG, "Package was null!", new Throwable()); 22091 return; 22092 } 22093 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22094 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22095 for (int i = 0; i < childCount; i++) { 22096 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22097 } 22098 } 22099 22100 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22101 final String volumeUuid = pkg.volumeUuid; 22102 final String packageName = pkg.packageName; 22103 final ApplicationInfo app = pkg.applicationInfo; 22104 22105 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22106 // Create a native library symlink only if we have native libraries 22107 // and if the native libraries are 32 bit libraries. We do not provide 22108 // this symlink for 64 bit libraries. 22109 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22110 final String nativeLibPath = app.nativeLibraryDir; 22111 try { 22112 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22113 nativeLibPath, userId); 22114 } catch (InstallerException e) { 22115 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22116 } 22117 } 22118 } 22119 } 22120 22121 /** 22122 * For system apps on non-FBE devices, this method migrates any existing 22123 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22124 * requested by the app. 22125 */ 22126 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22127 if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated() 22128 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22129 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22130 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22131 try { 22132 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22133 storageTarget); 22134 } catch (InstallerException e) { 22135 logCriticalInfo(Log.WARN, 22136 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22137 } 22138 return true; 22139 } else { 22140 return false; 22141 } 22142 } 22143 22144 public PackageFreezer freezePackage(String packageName, String killReason) { 22145 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22146 } 22147 22148 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22149 return new PackageFreezer(packageName, userId, killReason); 22150 } 22151 22152 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22153 String killReason) { 22154 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22155 } 22156 22157 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22158 String killReason) { 22159 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22160 return new PackageFreezer(); 22161 } else { 22162 return freezePackage(packageName, userId, killReason); 22163 } 22164 } 22165 22166 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22167 String killReason) { 22168 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22169 } 22170 22171 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22172 String killReason) { 22173 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22174 return new PackageFreezer(); 22175 } else { 22176 return freezePackage(packageName, userId, killReason); 22177 } 22178 } 22179 22180 /** 22181 * Class that freezes and kills the given package upon creation, and 22182 * unfreezes it upon closing. This is typically used when doing surgery on 22183 * app code/data to prevent the app from running while you're working. 22184 */ 22185 private class PackageFreezer implements AutoCloseable { 22186 private final String mPackageName; 22187 private final PackageFreezer[] mChildren; 22188 22189 private final boolean mWeFroze; 22190 22191 private final AtomicBoolean mClosed = new AtomicBoolean(); 22192 private final CloseGuard mCloseGuard = CloseGuard.get(); 22193 22194 /** 22195 * Create and return a stub freezer that doesn't actually do anything, 22196 * typically used when someone requested 22197 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22198 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22199 */ 22200 public PackageFreezer() { 22201 mPackageName = null; 22202 mChildren = null; 22203 mWeFroze = false; 22204 mCloseGuard.open("close"); 22205 } 22206 22207 public PackageFreezer(String packageName, int userId, String killReason) { 22208 synchronized (mPackages) { 22209 mPackageName = packageName; 22210 mWeFroze = mFrozenPackages.add(mPackageName); 22211 22212 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22213 if (ps != null) { 22214 killApplication(ps.name, ps.appId, userId, killReason); 22215 } 22216 22217 final PackageParser.Package p = mPackages.get(packageName); 22218 if (p != null && p.childPackages != null) { 22219 final int N = p.childPackages.size(); 22220 mChildren = new PackageFreezer[N]; 22221 for (int i = 0; i < N; i++) { 22222 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22223 userId, killReason); 22224 } 22225 } else { 22226 mChildren = null; 22227 } 22228 } 22229 mCloseGuard.open("close"); 22230 } 22231 22232 @Override 22233 protected void finalize() throws Throwable { 22234 try { 22235 if (mCloseGuard != null) { 22236 mCloseGuard.warnIfOpen(); 22237 } 22238 22239 close(); 22240 } finally { 22241 super.finalize(); 22242 } 22243 } 22244 22245 @Override 22246 public void close() { 22247 mCloseGuard.close(); 22248 if (mClosed.compareAndSet(false, true)) { 22249 synchronized (mPackages) { 22250 if (mWeFroze) { 22251 mFrozenPackages.remove(mPackageName); 22252 } 22253 22254 if (mChildren != null) { 22255 for (PackageFreezer freezer : mChildren) { 22256 freezer.close(); 22257 } 22258 } 22259 } 22260 } 22261 } 22262 } 22263 22264 /** 22265 * Verify that given package is currently frozen. 22266 */ 22267 private void checkPackageFrozen(String packageName) { 22268 synchronized (mPackages) { 22269 if (!mFrozenPackages.contains(packageName)) { 22270 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22271 } 22272 } 22273 } 22274 22275 @Override 22276 public int movePackage(final String packageName, final String volumeUuid) { 22277 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22278 22279 final int callingUid = Binder.getCallingUid(); 22280 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 22281 final int moveId = mNextMoveId.getAndIncrement(); 22282 mHandler.post(new Runnable() { 22283 @Override 22284 public void run() { 22285 try { 22286 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 22287 } catch (PackageManagerException e) { 22288 Slog.w(TAG, "Failed to move " + packageName, e); 22289 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 22290 } 22291 } 22292 }); 22293 return moveId; 22294 } 22295 22296 private void movePackageInternal(final String packageName, final String volumeUuid, 22297 final int moveId, final int callingUid, UserHandle user) 22298 throws PackageManagerException { 22299 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22300 final PackageManager pm = mContext.getPackageManager(); 22301 22302 final boolean currentAsec; 22303 final String currentVolumeUuid; 22304 final File codeFile; 22305 final String installerPackageName; 22306 final String packageAbiOverride; 22307 final int appId; 22308 final String seinfo; 22309 final String label; 22310 final int targetSdkVersion; 22311 final PackageFreezer freezer; 22312 final int[] installedUserIds; 22313 22314 // reader 22315 synchronized (mPackages) { 22316 final PackageParser.Package pkg = mPackages.get(packageName); 22317 final PackageSetting ps = mSettings.mPackages.get(packageName); 22318 if (pkg == null 22319 || ps == null 22320 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 22321 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22322 } 22323 if (pkg.applicationInfo.isSystemApp()) { 22324 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22325 "Cannot move system application"); 22326 } 22327 22328 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22329 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22330 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22331 if (isInternalStorage && !allow3rdPartyOnInternal) { 22332 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22333 "3rd party apps are not allowed on internal storage"); 22334 } 22335 22336 if (pkg.applicationInfo.isExternalAsec()) { 22337 currentAsec = true; 22338 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22339 } else if (pkg.applicationInfo.isForwardLocked()) { 22340 currentAsec = true; 22341 currentVolumeUuid = "forward_locked"; 22342 } else { 22343 currentAsec = false; 22344 currentVolumeUuid = ps.volumeUuid; 22345 22346 final File probe = new File(pkg.codePath); 22347 final File probeOat = new File(probe, "oat"); 22348 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22349 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22350 "Move only supported for modern cluster style installs"); 22351 } 22352 } 22353 22354 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22355 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22356 "Package already moved to " + volumeUuid); 22357 } 22358 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22359 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22360 "Device admin cannot be moved"); 22361 } 22362 22363 if (mFrozenPackages.contains(packageName)) { 22364 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22365 "Failed to move already frozen package"); 22366 } 22367 22368 codeFile = new File(pkg.codePath); 22369 installerPackageName = ps.installerPackageName; 22370 packageAbiOverride = ps.cpuAbiOverrideString; 22371 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22372 seinfo = pkg.applicationInfo.seInfo; 22373 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22374 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22375 freezer = freezePackage(packageName, "movePackageInternal"); 22376 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22377 } 22378 22379 final Bundle extras = new Bundle(); 22380 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22381 extras.putString(Intent.EXTRA_TITLE, label); 22382 mMoveCallbacks.notifyCreated(moveId, extras); 22383 22384 int installFlags; 22385 final boolean moveCompleteApp; 22386 final File measurePath; 22387 22388 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22389 installFlags = INSTALL_INTERNAL; 22390 moveCompleteApp = !currentAsec; 22391 measurePath = Environment.getDataAppDirectory(volumeUuid); 22392 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22393 installFlags = INSTALL_EXTERNAL; 22394 moveCompleteApp = false; 22395 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22396 } else { 22397 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22398 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22399 || !volume.isMountedWritable()) { 22400 freezer.close(); 22401 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22402 "Move location not mounted private volume"); 22403 } 22404 22405 Preconditions.checkState(!currentAsec); 22406 22407 installFlags = INSTALL_INTERNAL; 22408 moveCompleteApp = true; 22409 measurePath = Environment.getDataAppDirectory(volumeUuid); 22410 } 22411 22412 // If we're moving app data around, we need all the users unlocked 22413 if (moveCompleteApp) { 22414 for (int userId : installedUserIds) { 22415 if (StorageManager.isFileEncryptedNativeOrEmulated() 22416 && !StorageManager.isUserKeyUnlocked(userId)) { 22417 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 22418 "User " + userId + " must be unlocked"); 22419 } 22420 } 22421 } 22422 22423 final PackageStats stats = new PackageStats(null, -1); 22424 synchronized (mInstaller) { 22425 for (int userId : installedUserIds) { 22426 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22427 freezer.close(); 22428 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22429 "Failed to measure package size"); 22430 } 22431 } 22432 } 22433 22434 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22435 + stats.dataSize); 22436 22437 final long startFreeBytes = measurePath.getUsableSpace(); 22438 final long sizeBytes; 22439 if (moveCompleteApp) { 22440 sizeBytes = stats.codeSize + stats.dataSize; 22441 } else { 22442 sizeBytes = stats.codeSize; 22443 } 22444 22445 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22446 freezer.close(); 22447 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22448 "Not enough free space to move"); 22449 } 22450 22451 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22452 22453 final CountDownLatch installedLatch = new CountDownLatch(1); 22454 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22455 @Override 22456 public void onUserActionRequired(Intent intent) throws RemoteException { 22457 throw new IllegalStateException(); 22458 } 22459 22460 @Override 22461 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22462 Bundle extras) throws RemoteException { 22463 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22464 + PackageManager.installStatusToString(returnCode, msg)); 22465 22466 installedLatch.countDown(); 22467 freezer.close(); 22468 22469 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22470 switch (status) { 22471 case PackageInstaller.STATUS_SUCCESS: 22472 mMoveCallbacks.notifyStatusChanged(moveId, 22473 PackageManager.MOVE_SUCCEEDED); 22474 break; 22475 case PackageInstaller.STATUS_FAILURE_STORAGE: 22476 mMoveCallbacks.notifyStatusChanged(moveId, 22477 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22478 break; 22479 default: 22480 mMoveCallbacks.notifyStatusChanged(moveId, 22481 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22482 break; 22483 } 22484 } 22485 }; 22486 22487 final MoveInfo move; 22488 if (moveCompleteApp) { 22489 // Kick off a thread to report progress estimates 22490 new Thread() { 22491 @Override 22492 public void run() { 22493 while (true) { 22494 try { 22495 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22496 break; 22497 } 22498 } catch (InterruptedException ignored) { 22499 } 22500 22501 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22502 final int progress = 10 + (int) MathUtils.constrain( 22503 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22504 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22505 } 22506 } 22507 }.start(); 22508 22509 final String dataAppName = codeFile.getName(); 22510 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22511 dataAppName, appId, seinfo, targetSdkVersion); 22512 } else { 22513 move = null; 22514 } 22515 22516 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22517 22518 final Message msg = mHandler.obtainMessage(INIT_COPY); 22519 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22520 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22521 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22522 packageAbiOverride, null /*grantedPermissions*/, 22523 PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN); 22524 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22525 msg.obj = params; 22526 22527 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22528 System.identityHashCode(msg.obj)); 22529 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22530 System.identityHashCode(msg.obj)); 22531 22532 mHandler.sendMessage(msg); 22533 } 22534 22535 @Override 22536 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22537 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22538 22539 final int realMoveId = mNextMoveId.getAndIncrement(); 22540 final Bundle extras = new Bundle(); 22541 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22542 mMoveCallbacks.notifyCreated(realMoveId, extras); 22543 22544 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22545 @Override 22546 public void onCreated(int moveId, Bundle extras) { 22547 // Ignored 22548 } 22549 22550 @Override 22551 public void onStatusChanged(int moveId, int status, long estMillis) { 22552 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22553 } 22554 }; 22555 22556 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22557 storage.setPrimaryStorageUuid(volumeUuid, callback); 22558 return realMoveId; 22559 } 22560 22561 @Override 22562 public int getMoveStatus(int moveId) { 22563 mContext.enforceCallingOrSelfPermission( 22564 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22565 return mMoveCallbacks.mLastStatus.get(moveId); 22566 } 22567 22568 @Override 22569 public void registerMoveCallback(IPackageMoveObserver callback) { 22570 mContext.enforceCallingOrSelfPermission( 22571 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22572 mMoveCallbacks.register(callback); 22573 } 22574 22575 @Override 22576 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22577 mContext.enforceCallingOrSelfPermission( 22578 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22579 mMoveCallbacks.unregister(callback); 22580 } 22581 22582 @Override 22583 public boolean setInstallLocation(int loc) { 22584 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22585 null); 22586 if (getInstallLocation() == loc) { 22587 return true; 22588 } 22589 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22590 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22591 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22592 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22593 return true; 22594 } 22595 return false; 22596 } 22597 22598 @Override 22599 public int getInstallLocation() { 22600 // allow instant app access 22601 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22602 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22603 PackageHelper.APP_INSTALL_AUTO); 22604 } 22605 22606 /** Called by UserManagerService */ 22607 void cleanUpUser(UserManagerService userManager, int userHandle) { 22608 synchronized (mPackages) { 22609 mDirtyUsers.remove(userHandle); 22610 mUserNeedsBadging.delete(userHandle); 22611 mSettings.removeUserLPw(userHandle); 22612 mPendingBroadcasts.remove(userHandle); 22613 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22614 removeUnusedPackagesLPw(userManager, userHandle); 22615 } 22616 } 22617 22618 /** 22619 * We're removing userHandle and would like to remove any downloaded packages 22620 * that are no longer in use by any other user. 22621 * @param userHandle the user being removed 22622 */ 22623 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22624 final boolean DEBUG_CLEAN_APKS = false; 22625 int [] users = userManager.getUserIds(); 22626 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22627 while (psit.hasNext()) { 22628 PackageSetting ps = psit.next(); 22629 if (ps.pkg == null) { 22630 continue; 22631 } 22632 final String packageName = ps.pkg.packageName; 22633 // Skip over if system app 22634 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22635 continue; 22636 } 22637 if (DEBUG_CLEAN_APKS) { 22638 Slog.i(TAG, "Checking package " + packageName); 22639 } 22640 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22641 if (keep) { 22642 if (DEBUG_CLEAN_APKS) { 22643 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22644 } 22645 } else { 22646 for (int i = 0; i < users.length; i++) { 22647 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22648 keep = true; 22649 if (DEBUG_CLEAN_APKS) { 22650 Slog.i(TAG, " Keeping package " + packageName + " for user " 22651 + users[i]); 22652 } 22653 break; 22654 } 22655 } 22656 } 22657 if (!keep) { 22658 if (DEBUG_CLEAN_APKS) { 22659 Slog.i(TAG, " Removing package " + packageName); 22660 } 22661 mHandler.post(new Runnable() { 22662 public void run() { 22663 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22664 userHandle, 0); 22665 } //end run 22666 }); 22667 } 22668 } 22669 } 22670 22671 /** Called by UserManagerService */ 22672 void createNewUser(int userId, String[] disallowedPackages) { 22673 synchronized (mInstallLock) { 22674 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22675 } 22676 synchronized (mPackages) { 22677 scheduleWritePackageRestrictionsLocked(userId); 22678 scheduleWritePackageListLocked(userId); 22679 applyFactoryDefaultBrowserLPw(userId); 22680 primeDomainVerificationsLPw(userId); 22681 } 22682 } 22683 22684 void onNewUserCreated(final int userId) { 22685 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22686 synchronized(mPackages) { 22687 // If permission review for legacy apps is required, we represent 22688 // dagerous permissions for such apps as always granted runtime 22689 // permissions to keep per user flag state whether review is needed. 22690 // Hence, if a new user is added we have to propagate dangerous 22691 // permission grants for these legacy apps. 22692 if (mSettings.mPermissions.mPermissionReviewRequired) { 22693// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG 22694 mPermissionManager.updateAllPermissions( 22695 StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(), 22696 mPermissionCallback); 22697 } 22698 } 22699 } 22700 22701 @Override 22702 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22703 mContext.enforceCallingOrSelfPermission( 22704 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22705 "Only package verification agents can read the verifier device identity"); 22706 22707 synchronized (mPackages) { 22708 return mSettings.getVerifierDeviceIdentityLPw(); 22709 } 22710 } 22711 22712 @Override 22713 public void setPermissionEnforced(String permission, boolean enforced) { 22714 // TODO: Now that we no longer change GID for storage, this should to away. 22715 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22716 "setPermissionEnforced"); 22717 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22718 synchronized (mPackages) { 22719 if (mSettings.mReadExternalStorageEnforced == null 22720 || mSettings.mReadExternalStorageEnforced != enforced) { 22721 mSettings.mReadExternalStorageEnforced = 22722 enforced ? Boolean.TRUE : Boolean.FALSE; 22723 mSettings.writeLPr(); 22724 } 22725 } 22726 // kill any non-foreground processes so we restart them and 22727 // grant/revoke the GID. 22728 final IActivityManager am = ActivityManager.getService(); 22729 if (am != null) { 22730 final long token = Binder.clearCallingIdentity(); 22731 try { 22732 am.killProcessesBelowForeground("setPermissionEnforcement"); 22733 } catch (RemoteException e) { 22734 } finally { 22735 Binder.restoreCallingIdentity(token); 22736 } 22737 } 22738 } else { 22739 throw new IllegalArgumentException("No selective enforcement for " + permission); 22740 } 22741 } 22742 22743 @Override 22744 @Deprecated 22745 public boolean isPermissionEnforced(String permission) { 22746 // allow instant applications 22747 return true; 22748 } 22749 22750 @Override 22751 public boolean isStorageLow() { 22752 // allow instant applications 22753 final long token = Binder.clearCallingIdentity(); 22754 try { 22755 final DeviceStorageMonitorInternal 22756 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22757 if (dsm != null) { 22758 return dsm.isMemoryLow(); 22759 } else { 22760 return false; 22761 } 22762 } finally { 22763 Binder.restoreCallingIdentity(token); 22764 } 22765 } 22766 22767 @Override 22768 public IPackageInstaller getPackageInstaller() { 22769 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 22770 return null; 22771 } 22772 return mInstallerService; 22773 } 22774 22775 @Override 22776 public IArtManager getArtManager() { 22777 return mArtManagerService; 22778 } 22779 22780 private boolean userNeedsBadging(int userId) { 22781 int index = mUserNeedsBadging.indexOfKey(userId); 22782 if (index < 0) { 22783 final UserInfo userInfo; 22784 final long token = Binder.clearCallingIdentity(); 22785 try { 22786 userInfo = sUserManager.getUserInfo(userId); 22787 } finally { 22788 Binder.restoreCallingIdentity(token); 22789 } 22790 final boolean b; 22791 if (userInfo != null && userInfo.isManagedProfile()) { 22792 b = true; 22793 } else { 22794 b = false; 22795 } 22796 mUserNeedsBadging.put(userId, b); 22797 return b; 22798 } 22799 return mUserNeedsBadging.valueAt(index); 22800 } 22801 22802 @Override 22803 public KeySet getKeySetByAlias(String packageName, String alias) { 22804 if (packageName == null || alias == null) { 22805 return null; 22806 } 22807 synchronized(mPackages) { 22808 final PackageParser.Package pkg = mPackages.get(packageName); 22809 if (pkg == null) { 22810 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22811 throw new IllegalArgumentException("Unknown package: " + packageName); 22812 } 22813 final PackageSetting ps = (PackageSetting) pkg.mExtras; 22814 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 22815 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 22816 throw new IllegalArgumentException("Unknown package: " + packageName); 22817 } 22818 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22819 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22820 } 22821 } 22822 22823 @Override 22824 public KeySet getSigningKeySet(String packageName) { 22825 if (packageName == null) { 22826 return null; 22827 } 22828 synchronized(mPackages) { 22829 final int callingUid = Binder.getCallingUid(); 22830 final int callingUserId = UserHandle.getUserId(callingUid); 22831 final PackageParser.Package pkg = mPackages.get(packageName); 22832 if (pkg == null) { 22833 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22834 throw new IllegalArgumentException("Unknown package: " + packageName); 22835 } 22836 final PackageSetting ps = (PackageSetting) pkg.mExtras; 22837 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 22838 // filter and pretend the package doesn't exist 22839 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 22840 + ", uid:" + callingUid); 22841 throw new IllegalArgumentException("Unknown package: " + packageName); 22842 } 22843 if (pkg.applicationInfo.uid != callingUid 22844 && Process.SYSTEM_UID != callingUid) { 22845 throw new SecurityException("May not access signing KeySet of other apps."); 22846 } 22847 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22848 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22849 } 22850 } 22851 22852 @Override 22853 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22854 final int callingUid = Binder.getCallingUid(); 22855 if (getInstantAppPackageName(callingUid) != null) { 22856 return false; 22857 } 22858 if (packageName == null || ks == null) { 22859 return false; 22860 } 22861 synchronized(mPackages) { 22862 final PackageParser.Package pkg = mPackages.get(packageName); 22863 if (pkg == null 22864 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 22865 UserHandle.getUserId(callingUid))) { 22866 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22867 throw new IllegalArgumentException("Unknown package: " + packageName); 22868 } 22869 IBinder ksh = ks.getToken(); 22870 if (ksh instanceof KeySetHandle) { 22871 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22872 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22873 } 22874 return false; 22875 } 22876 } 22877 22878 @Override 22879 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22880 final int callingUid = Binder.getCallingUid(); 22881 if (getInstantAppPackageName(callingUid) != null) { 22882 return false; 22883 } 22884 if (packageName == null || ks == null) { 22885 return false; 22886 } 22887 synchronized(mPackages) { 22888 final PackageParser.Package pkg = mPackages.get(packageName); 22889 if (pkg == null 22890 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 22891 UserHandle.getUserId(callingUid))) { 22892 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22893 throw new IllegalArgumentException("Unknown package: " + packageName); 22894 } 22895 IBinder ksh = ks.getToken(); 22896 if (ksh instanceof KeySetHandle) { 22897 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22898 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22899 } 22900 return false; 22901 } 22902 } 22903 22904 private void deletePackageIfUnusedLPr(final String packageName) { 22905 PackageSetting ps = mSettings.mPackages.get(packageName); 22906 if (ps == null) { 22907 return; 22908 } 22909 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22910 // TODO Implement atomic delete if package is unused 22911 // It is currently possible that the package will be deleted even if it is installed 22912 // after this method returns. 22913 mHandler.post(new Runnable() { 22914 public void run() { 22915 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22916 0, PackageManager.DELETE_ALL_USERS); 22917 } 22918 }); 22919 } 22920 } 22921 22922 /** 22923 * Check and throw if the given before/after packages would be considered a 22924 * downgrade. 22925 */ 22926 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22927 throws PackageManagerException { 22928 if (after.getLongVersionCode() < before.getLongVersionCode()) { 22929 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22930 "Update version code " + after.versionCode + " is older than current " 22931 + before.getLongVersionCode()); 22932 } else if (after.getLongVersionCode() == before.getLongVersionCode()) { 22933 if (after.baseRevisionCode < before.baseRevisionCode) { 22934 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22935 "Update base revision code " + after.baseRevisionCode 22936 + " is older than current " + before.baseRevisionCode); 22937 } 22938 22939 if (!ArrayUtils.isEmpty(after.splitNames)) { 22940 for (int i = 0; i < after.splitNames.length; i++) { 22941 final String splitName = after.splitNames[i]; 22942 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22943 if (j != -1) { 22944 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22945 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22946 "Update split " + splitName + " revision code " 22947 + after.splitRevisionCodes[i] + " is older than current " 22948 + before.splitRevisionCodes[j]); 22949 } 22950 } 22951 } 22952 } 22953 } 22954 } 22955 22956 private static class MoveCallbacks extends Handler { 22957 private static final int MSG_CREATED = 1; 22958 private static final int MSG_STATUS_CHANGED = 2; 22959 22960 private final RemoteCallbackList<IPackageMoveObserver> 22961 mCallbacks = new RemoteCallbackList<>(); 22962 22963 private final SparseIntArray mLastStatus = new SparseIntArray(); 22964 22965 public MoveCallbacks(Looper looper) { 22966 super(looper); 22967 } 22968 22969 public void register(IPackageMoveObserver callback) { 22970 mCallbacks.register(callback); 22971 } 22972 22973 public void unregister(IPackageMoveObserver callback) { 22974 mCallbacks.unregister(callback); 22975 } 22976 22977 @Override 22978 public void handleMessage(Message msg) { 22979 final SomeArgs args = (SomeArgs) msg.obj; 22980 final int n = mCallbacks.beginBroadcast(); 22981 for (int i = 0; i < n; i++) { 22982 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22983 try { 22984 invokeCallback(callback, msg.what, args); 22985 } catch (RemoteException ignored) { 22986 } 22987 } 22988 mCallbacks.finishBroadcast(); 22989 args.recycle(); 22990 } 22991 22992 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22993 throws RemoteException { 22994 switch (what) { 22995 case MSG_CREATED: { 22996 callback.onCreated(args.argi1, (Bundle) args.arg2); 22997 break; 22998 } 22999 case MSG_STATUS_CHANGED: { 23000 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 23001 break; 23002 } 23003 } 23004 } 23005 23006 private void notifyCreated(int moveId, Bundle extras) { 23007 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 23008 23009 final SomeArgs args = SomeArgs.obtain(); 23010 args.argi1 = moveId; 23011 args.arg2 = extras; 23012 obtainMessage(MSG_CREATED, args).sendToTarget(); 23013 } 23014 23015 private void notifyStatusChanged(int moveId, int status) { 23016 notifyStatusChanged(moveId, status, -1); 23017 } 23018 23019 private void notifyStatusChanged(int moveId, int status, long estMillis) { 23020 Slog.v(TAG, "Move " + moveId + " status " + status); 23021 23022 final SomeArgs args = SomeArgs.obtain(); 23023 args.argi1 = moveId; 23024 args.argi2 = status; 23025 args.arg3 = estMillis; 23026 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 23027 23028 synchronized (mLastStatus) { 23029 mLastStatus.put(moveId, status); 23030 } 23031 } 23032 } 23033 23034 private final static class OnPermissionChangeListeners extends Handler { 23035 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 23036 23037 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 23038 new RemoteCallbackList<>(); 23039 23040 public OnPermissionChangeListeners(Looper looper) { 23041 super(looper); 23042 } 23043 23044 @Override 23045 public void handleMessage(Message msg) { 23046 switch (msg.what) { 23047 case MSG_ON_PERMISSIONS_CHANGED: { 23048 final int uid = msg.arg1; 23049 handleOnPermissionsChanged(uid); 23050 } break; 23051 } 23052 } 23053 23054 public void addListenerLocked(IOnPermissionsChangeListener listener) { 23055 mPermissionListeners.register(listener); 23056 23057 } 23058 23059 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 23060 mPermissionListeners.unregister(listener); 23061 } 23062 23063 public void onPermissionsChanged(int uid) { 23064 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 23065 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 23066 } 23067 } 23068 23069 private void handleOnPermissionsChanged(int uid) { 23070 final int count = mPermissionListeners.beginBroadcast(); 23071 try { 23072 for (int i = 0; i < count; i++) { 23073 IOnPermissionsChangeListener callback = mPermissionListeners 23074 .getBroadcastItem(i); 23075 try { 23076 callback.onPermissionsChanged(uid); 23077 } catch (RemoteException e) { 23078 Log.e(TAG, "Permission listener is dead", e); 23079 } 23080 } 23081 } finally { 23082 mPermissionListeners.finishBroadcast(); 23083 } 23084 } 23085 } 23086 23087 private class PackageManagerNative extends IPackageManagerNative.Stub { 23088 @Override 23089 public String[] getNamesForUids(int[] uids) throws RemoteException { 23090 final String[] results = PackageManagerService.this.getNamesForUids(uids); 23091 // massage results so they can be parsed by the native binder 23092 for (int i = results.length - 1; i >= 0; --i) { 23093 if (results[i] == null) { 23094 results[i] = ""; 23095 } 23096 } 23097 return results; 23098 } 23099 23100 // NB: this differentiates between preloads and sideloads 23101 @Override 23102 public String getInstallerForPackage(String packageName) throws RemoteException { 23103 final String installerName = getInstallerPackageName(packageName); 23104 if (!TextUtils.isEmpty(installerName)) { 23105 return installerName; 23106 } 23107 // differentiate between preload and sideload 23108 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23109 ApplicationInfo appInfo = getApplicationInfo(packageName, 23110 /*flags*/ 0, 23111 /*userId*/ callingUser); 23112 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 23113 return "preload"; 23114 } 23115 return ""; 23116 } 23117 23118 @Override 23119 public long getVersionCodeForPackage(String packageName) throws RemoteException { 23120 try { 23121 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23122 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 23123 if (pInfo != null) { 23124 return pInfo.getLongVersionCode(); 23125 } 23126 } catch (Exception e) { 23127 } 23128 return 0; 23129 } 23130 } 23131 23132 private class PackageManagerInternalImpl extends PackageManagerInternal { 23133 @Override 23134 public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask, 23135 int flagValues, int userId) { 23136 PackageManagerService.this.updatePermissionFlags( 23137 permName, packageName, flagMask, flagValues, userId); 23138 } 23139 23140 @Override 23141 public int getPermissionFlagsTEMP(String permName, String packageName, int userId) { 23142 return PackageManagerService.this.getPermissionFlags(permName, packageName, userId); 23143 } 23144 23145 @Override 23146 public boolean isInstantApp(String packageName, int userId) { 23147 return PackageManagerService.this.isInstantApp(packageName, userId); 23148 } 23149 23150 @Override 23151 public String getInstantAppPackageName(int uid) { 23152 return PackageManagerService.this.getInstantAppPackageName(uid); 23153 } 23154 23155 @Override 23156 public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) { 23157 synchronized (mPackages) { 23158 return PackageManagerService.this.filterAppAccessLPr( 23159 (PackageSetting) pkg.mExtras, callingUid, userId); 23160 } 23161 } 23162 23163 @Override 23164 public PackageParser.Package getPackage(String packageName) { 23165 synchronized (mPackages) { 23166 packageName = resolveInternalPackageNameLPr( 23167 packageName, PackageManager.VERSION_CODE_HIGHEST); 23168 return mPackages.get(packageName); 23169 } 23170 } 23171 23172 @Override 23173 public PackageList getPackageList(PackageListObserver observer) { 23174 synchronized (mPackages) { 23175 final int N = mPackages.size(); 23176 final ArrayList<String> list = new ArrayList<>(N); 23177 for (int i = 0; i < N; i++) { 23178 list.add(mPackages.keyAt(i)); 23179 } 23180 final PackageList packageList = new PackageList(list, observer); 23181 if (observer != null) { 23182 mPackageListObservers.add(packageList); 23183 } 23184 return packageList; 23185 } 23186 } 23187 23188 @Override 23189 public void removePackageListObserver(PackageListObserver observer) { 23190 synchronized (mPackages) { 23191 mPackageListObservers.remove(observer); 23192 } 23193 } 23194 23195 @Override 23196 public PackageParser.Package getDisabledPackage(String packageName) { 23197 synchronized (mPackages) { 23198 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 23199 return (ps != null) ? ps.pkg : null; 23200 } 23201 } 23202 23203 @Override 23204 public String getKnownPackageName(int knownPackage, int userId) { 23205 switch(knownPackage) { 23206 case PackageManagerInternal.PACKAGE_BROWSER: 23207 return getDefaultBrowserPackageName(userId); 23208 case PackageManagerInternal.PACKAGE_INSTALLER: 23209 return mRequiredInstallerPackage; 23210 case PackageManagerInternal.PACKAGE_SETUP_WIZARD: 23211 return mSetupWizardPackage; 23212 case PackageManagerInternal.PACKAGE_SYSTEM: 23213 return "android"; 23214 case PackageManagerInternal.PACKAGE_VERIFIER: 23215 return mRequiredVerifierPackage; 23216 } 23217 return null; 23218 } 23219 23220 @Override 23221 public boolean isResolveActivityComponent(ComponentInfo component) { 23222 return mResolveActivity.packageName.equals(component.packageName) 23223 && mResolveActivity.name.equals(component.name); 23224 } 23225 23226 @Override 23227 public void setLocationPackagesProvider(PackagesProvider provider) { 23228 mDefaultPermissionPolicy.setLocationPackagesProvider(provider); 23229 } 23230 23231 @Override 23232 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23233 mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider); 23234 } 23235 23236 @Override 23237 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23238 mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider); 23239 } 23240 23241 @Override 23242 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23243 mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider); 23244 } 23245 23246 @Override 23247 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23248 mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider); 23249 } 23250 23251 @Override 23252 public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) { 23253 mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider); 23254 } 23255 23256 @Override 23257 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23258 mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider); 23259 } 23260 23261 @Override 23262 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23263 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId); 23264 } 23265 23266 @Override 23267 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23268 synchronized (mPackages) { 23269 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23270 } 23271 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId); 23272 } 23273 23274 @Override 23275 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23276 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager( 23277 packageName, userId); 23278 } 23279 23280 @Override 23281 public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) { 23282 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp( 23283 packageName, userId); 23284 } 23285 23286 @Override 23287 public void setKeepUninstalledPackages(final List<String> packageList) { 23288 Preconditions.checkNotNull(packageList); 23289 List<String> removedFromList = null; 23290 synchronized (mPackages) { 23291 if (mKeepUninstalledPackages != null) { 23292 final int packagesCount = mKeepUninstalledPackages.size(); 23293 for (int i = 0; i < packagesCount; i++) { 23294 String oldPackage = mKeepUninstalledPackages.get(i); 23295 if (packageList != null && packageList.contains(oldPackage)) { 23296 continue; 23297 } 23298 if (removedFromList == null) { 23299 removedFromList = new ArrayList<>(); 23300 } 23301 removedFromList.add(oldPackage); 23302 } 23303 } 23304 mKeepUninstalledPackages = new ArrayList<>(packageList); 23305 if (removedFromList != null) { 23306 final int removedCount = removedFromList.size(); 23307 for (int i = 0; i < removedCount; i++) { 23308 deletePackageIfUnusedLPr(removedFromList.get(i)); 23309 } 23310 } 23311 } 23312 } 23313 23314 @Override 23315 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23316 synchronized (mPackages) { 23317 return mPermissionManager.isPermissionsReviewRequired( 23318 mPackages.get(packageName), userId); 23319 } 23320 } 23321 23322 @Override 23323 public PackageInfo getPackageInfo( 23324 String packageName, int flags, int filterCallingUid, int userId) { 23325 return PackageManagerService.this 23326 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 23327 flags, filterCallingUid, userId); 23328 } 23329 23330 @Override 23331 public int getPackageUid(String packageName, int flags, int userId) { 23332 return PackageManagerService.this 23333 .getPackageUid(packageName, flags, userId); 23334 } 23335 23336 @Override 23337 public ApplicationInfo getApplicationInfo( 23338 String packageName, int flags, int filterCallingUid, int userId) { 23339 return PackageManagerService.this 23340 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 23341 } 23342 23343 @Override 23344 public ActivityInfo getActivityInfo( 23345 ComponentName component, int flags, int filterCallingUid, int userId) { 23346 return PackageManagerService.this 23347 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 23348 } 23349 23350 @Override 23351 public List<ResolveInfo> queryIntentActivities( 23352 Intent intent, int flags, int filterCallingUid, int userId) { 23353 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23354 return PackageManagerService.this 23355 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 23356 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 23357 } 23358 23359 @Override 23360 public List<ResolveInfo> queryIntentServices( 23361 Intent intent, int flags, int callingUid, int userId) { 23362 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23363 return PackageManagerService.this 23364 .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid, 23365 false); 23366 } 23367 23368 @Override 23369 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23370 int userId) { 23371 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23372 } 23373 23374 @Override 23375 public void setDeviceAndProfileOwnerPackages( 23376 int deviceOwnerUserId, String deviceOwnerPackage, 23377 SparseArray<String> profileOwnerPackages) { 23378 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23379 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23380 } 23381 23382 @Override 23383 public boolean isPackageDataProtected(int userId, String packageName) { 23384 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23385 } 23386 23387 @Override 23388 public boolean isPackageEphemeral(int userId, String packageName) { 23389 synchronized (mPackages) { 23390 final PackageSetting ps = mSettings.mPackages.get(packageName); 23391 return ps != null ? ps.getInstantApp(userId) : false; 23392 } 23393 } 23394 23395 @Override 23396 public boolean wasPackageEverLaunched(String packageName, int userId) { 23397 synchronized (mPackages) { 23398 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23399 } 23400 } 23401 23402 @Override 23403 public void grantRuntimePermission(String packageName, String permName, int userId, 23404 boolean overridePolicy) { 23405 PackageManagerService.this.mPermissionManager.grantRuntimePermission( 23406 permName, packageName, overridePolicy, getCallingUid(), userId, 23407 mPermissionCallback); 23408 } 23409 23410 @Override 23411 public void revokeRuntimePermission(String packageName, String permName, int userId, 23412 boolean overridePolicy) { 23413 mPermissionManager.revokeRuntimePermission( 23414 permName, packageName, overridePolicy, getCallingUid(), userId, 23415 mPermissionCallback); 23416 } 23417 23418 @Override 23419 public String getNameForUid(int uid) { 23420 return PackageManagerService.this.getNameForUid(uid); 23421 } 23422 23423 @Override 23424 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23425 Intent origIntent, String resolvedType, String callingPackage, 23426 Bundle verificationBundle, int userId) { 23427 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23428 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 23429 userId); 23430 } 23431 23432 @Override 23433 public void grantEphemeralAccess(int userId, Intent intent, 23434 int targetAppId, int ephemeralAppId) { 23435 synchronized (mPackages) { 23436 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23437 targetAppId, ephemeralAppId); 23438 } 23439 } 23440 23441 @Override 23442 public boolean isInstantAppInstallerComponent(ComponentName component) { 23443 synchronized (mPackages) { 23444 return mInstantAppInstallerActivity != null 23445 && mInstantAppInstallerActivity.getComponentName().equals(component); 23446 } 23447 } 23448 23449 @Override 23450 public void pruneInstantApps() { 23451 mInstantAppRegistry.pruneInstantApps(); 23452 } 23453 23454 @Override 23455 public String getSetupWizardPackageName() { 23456 return mSetupWizardPackage; 23457 } 23458 23459 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23460 if (policy != null) { 23461 mExternalSourcesPolicy = policy; 23462 } 23463 } 23464 23465 @Override 23466 public boolean isPackagePersistent(String packageName) { 23467 synchronized (mPackages) { 23468 PackageParser.Package pkg = mPackages.get(packageName); 23469 return pkg != null 23470 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23471 | ApplicationInfo.FLAG_PERSISTENT)) == 23472 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23473 : false; 23474 } 23475 } 23476 23477 @Override 23478 public boolean isLegacySystemApp(Package pkg) { 23479 synchronized (mPackages) { 23480 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23481 return mPromoteSystemApps 23482 && ps.isSystem() 23483 && mExistingSystemPackages.contains(ps.name); 23484 } 23485 } 23486 23487 @Override 23488 public List<PackageInfo> getOverlayPackages(int userId) { 23489 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23490 synchronized (mPackages) { 23491 for (PackageParser.Package p : mPackages.values()) { 23492 if (p.mOverlayTarget != null) { 23493 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23494 if (pkg != null) { 23495 overlayPackages.add(pkg); 23496 } 23497 } 23498 } 23499 } 23500 return overlayPackages; 23501 } 23502 23503 @Override 23504 public List<String> getTargetPackageNames(int userId) { 23505 List<String> targetPackages = new ArrayList<>(); 23506 synchronized (mPackages) { 23507 for (PackageParser.Package p : mPackages.values()) { 23508 if (p.mOverlayTarget == null) { 23509 targetPackages.add(p.packageName); 23510 } 23511 } 23512 } 23513 return targetPackages; 23514 } 23515 23516 @Override 23517 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23518 @Nullable List<String> overlayPackageNames) { 23519 synchronized (mPackages) { 23520 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23521 Slog.e(TAG, "failed to find package " + targetPackageName); 23522 return false; 23523 } 23524 ArrayList<String> overlayPaths = null; 23525 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 23526 final int N = overlayPackageNames.size(); 23527 overlayPaths = new ArrayList<>(N); 23528 for (int i = 0; i < N; i++) { 23529 final String packageName = overlayPackageNames.get(i); 23530 final PackageParser.Package pkg = mPackages.get(packageName); 23531 if (pkg == null) { 23532 Slog.e(TAG, "failed to find package " + packageName); 23533 return false; 23534 } 23535 overlayPaths.add(pkg.baseCodePath); 23536 } 23537 } 23538 23539 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 23540 ps.setOverlayPaths(overlayPaths, userId); 23541 return true; 23542 } 23543 } 23544 23545 @Override 23546 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23547 int flags, int userId, boolean resolveForStart) { 23548 return resolveIntentInternal( 23549 intent, resolvedType, flags, userId, resolveForStart); 23550 } 23551 23552 @Override 23553 public ResolveInfo resolveService(Intent intent, String resolvedType, 23554 int flags, int userId, int callingUid) { 23555 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 23556 } 23557 23558 @Override 23559 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 23560 return PackageManagerService.this.resolveContentProviderInternal( 23561 name, flags, userId); 23562 } 23563 23564 @Override 23565 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23566 synchronized (mPackages) { 23567 mIsolatedOwners.put(isolatedUid, ownerUid); 23568 } 23569 } 23570 23571 @Override 23572 public void removeIsolatedUid(int isolatedUid) { 23573 synchronized (mPackages) { 23574 mIsolatedOwners.delete(isolatedUid); 23575 } 23576 } 23577 23578 @Override 23579 public int getUidTargetSdkVersion(int uid) { 23580 synchronized (mPackages) { 23581 return getUidTargetSdkVersionLockedLPr(uid); 23582 } 23583 } 23584 23585 @Override 23586 public int getPackageTargetSdkVersion(String packageName) { 23587 synchronized (mPackages) { 23588 return getPackageTargetSdkVersionLockedLPr(packageName); 23589 } 23590 } 23591 23592 @Override 23593 public boolean canAccessInstantApps(int callingUid, int userId) { 23594 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 23595 } 23596 23597 @Override 23598 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 23599 synchronized (mPackages) { 23600 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 23601 } 23602 } 23603 23604 @Override 23605 public void notifyPackageUse(String packageName, int reason) { 23606 synchronized (mPackages) { 23607 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 23608 } 23609 } 23610 } 23611 23612 @Override 23613 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23614 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23615 synchronized (mPackages) { 23616 final long identity = Binder.clearCallingIdentity(); 23617 try { 23618 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps( 23619 packageNames, userId); 23620 } finally { 23621 Binder.restoreCallingIdentity(identity); 23622 } 23623 } 23624 } 23625 23626 @Override 23627 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23628 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23629 synchronized (mPackages) { 23630 final long identity = Binder.clearCallingIdentity(); 23631 try { 23632 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices( 23633 packageNames, userId); 23634 } finally { 23635 Binder.restoreCallingIdentity(identity); 23636 } 23637 } 23638 } 23639 23640 private static void enforceSystemOrPhoneCaller(String tag) { 23641 int callingUid = Binder.getCallingUid(); 23642 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23643 throw new SecurityException( 23644 "Cannot call " + tag + " from UID " + callingUid); 23645 } 23646 } 23647 23648 boolean isHistoricalPackageUsageAvailable() { 23649 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23650 } 23651 23652 /** 23653 * Return a <b>copy</b> of the collection of packages known to the package manager. 23654 * @return A copy of the values of mPackages. 23655 */ 23656 Collection<PackageParser.Package> getPackages() { 23657 synchronized (mPackages) { 23658 return new ArrayList<>(mPackages.values()); 23659 } 23660 } 23661 23662 /** 23663 * Logs process start information (including base APK hash) to the security log. 23664 * @hide 23665 */ 23666 @Override 23667 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23668 String apkFile, int pid) { 23669 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23670 return; 23671 } 23672 if (!SecurityLog.isLoggingEnabled()) { 23673 return; 23674 } 23675 Bundle data = new Bundle(); 23676 data.putLong("startTimestamp", System.currentTimeMillis()); 23677 data.putString("processName", processName); 23678 data.putInt("uid", uid); 23679 data.putString("seinfo", seinfo); 23680 data.putString("apkFile", apkFile); 23681 data.putInt("pid", pid); 23682 Message msg = mProcessLoggingHandler.obtainMessage( 23683 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23684 msg.setData(data); 23685 mProcessLoggingHandler.sendMessage(msg); 23686 } 23687 23688 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23689 return mCompilerStats.getPackageStats(pkgName); 23690 } 23691 23692 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23693 return getOrCreateCompilerPackageStats(pkg.packageName); 23694 } 23695 23696 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23697 return mCompilerStats.getOrCreatePackageStats(pkgName); 23698 } 23699 23700 public void deleteCompilerPackageStats(String pkgName) { 23701 mCompilerStats.deletePackageStats(pkgName); 23702 } 23703 23704 @Override 23705 public int getInstallReason(String packageName, int userId) { 23706 final int callingUid = Binder.getCallingUid(); 23707 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23708 true /* requireFullPermission */, false /* checkShell */, 23709 "get install reason"); 23710 synchronized (mPackages) { 23711 final PackageSetting ps = mSettings.mPackages.get(packageName); 23712 if (filterAppAccessLPr(ps, callingUid, userId)) { 23713 return PackageManager.INSTALL_REASON_UNKNOWN; 23714 } 23715 if (ps != null) { 23716 return ps.getInstallReason(userId); 23717 } 23718 } 23719 return PackageManager.INSTALL_REASON_UNKNOWN; 23720 } 23721 23722 @Override 23723 public boolean canRequestPackageInstalls(String packageName, int userId) { 23724 return canRequestPackageInstallsInternal(packageName, 0, userId, 23725 true /* throwIfPermNotDeclared*/); 23726 } 23727 23728 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 23729 boolean throwIfPermNotDeclared) { 23730 int callingUid = Binder.getCallingUid(); 23731 int uid = getPackageUid(packageName, 0, userId); 23732 if (callingUid != uid && callingUid != Process.ROOT_UID 23733 && callingUid != Process.SYSTEM_UID) { 23734 throw new SecurityException( 23735 "Caller uid " + callingUid + " does not own package " + packageName); 23736 } 23737 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 23738 if (info == null) { 23739 return false; 23740 } 23741 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23742 return false; 23743 } 23744 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23745 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23746 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23747 if (throwIfPermNotDeclared) { 23748 throw new SecurityException("Need to declare " + appOpPermission 23749 + " to call this api"); 23750 } else { 23751 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 23752 return false; 23753 } 23754 } 23755 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23756 return false; 23757 } 23758 if (mExternalSourcesPolicy != null) { 23759 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23760 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23761 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23762 } 23763 } 23764 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23765 } 23766 23767 @Override 23768 public ComponentName getInstantAppResolverSettingsComponent() { 23769 return mInstantAppResolverSettingsComponent; 23770 } 23771 23772 @Override 23773 public ComponentName getInstantAppInstallerComponent() { 23774 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23775 return null; 23776 } 23777 return mInstantAppInstallerActivity == null 23778 ? null : mInstantAppInstallerActivity.getComponentName(); 23779 } 23780 23781 @Override 23782 public String getInstantAppAndroidId(String packageName, int userId) { 23783 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 23784 "getInstantAppAndroidId"); 23785 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 23786 true /* requireFullPermission */, false /* checkShell */, 23787 "getInstantAppAndroidId"); 23788 // Make sure the target is an Instant App. 23789 if (!isInstantApp(packageName, userId)) { 23790 return null; 23791 } 23792 synchronized (mPackages) { 23793 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 23794 } 23795 } 23796 23797 boolean canHaveOatDir(String packageName) { 23798 synchronized (mPackages) { 23799 PackageParser.Package p = mPackages.get(packageName); 23800 if (p == null) { 23801 return false; 23802 } 23803 return p.canHaveOatDir(); 23804 } 23805 } 23806 23807 private String getOatDir(PackageParser.Package pkg) { 23808 if (!pkg.canHaveOatDir()) { 23809 return null; 23810 } 23811 File codePath = new File(pkg.codePath); 23812 if (codePath.isDirectory()) { 23813 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 23814 } 23815 return null; 23816 } 23817 23818 void deleteOatArtifactsOfPackage(String packageName) { 23819 final String[] instructionSets; 23820 final List<String> codePaths; 23821 final String oatDir; 23822 final PackageParser.Package pkg; 23823 synchronized (mPackages) { 23824 pkg = mPackages.get(packageName); 23825 } 23826 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 23827 codePaths = pkg.getAllCodePaths(); 23828 oatDir = getOatDir(pkg); 23829 23830 for (String codePath : codePaths) { 23831 for (String isa : instructionSets) { 23832 try { 23833 mInstaller.deleteOdex(codePath, isa, oatDir); 23834 } catch (InstallerException e) { 23835 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 23836 } 23837 } 23838 } 23839 } 23840 23841 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 23842 Set<String> unusedPackages = new HashSet<>(); 23843 long currentTimeInMillis = System.currentTimeMillis(); 23844 synchronized (mPackages) { 23845 for (PackageParser.Package pkg : mPackages.values()) { 23846 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 23847 if (ps == null) { 23848 continue; 23849 } 23850 PackageDexUsage.PackageUseInfo packageUseInfo = 23851 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 23852 if (PackageManagerServiceUtils 23853 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 23854 downgradeTimeThresholdMillis, packageUseInfo, 23855 pkg.getLatestPackageUseTimeInMills(), 23856 pkg.getLatestForegroundPackageUseTimeInMills())) { 23857 unusedPackages.add(pkg.packageName); 23858 } 23859 } 23860 } 23861 return unusedPackages; 23862 } 23863 23864 @Override 23865 public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning, 23866 int userId) { 23867 final int callingUid = Binder.getCallingUid(); 23868 final int callingAppId = UserHandle.getAppId(callingUid); 23869 23870 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23871 true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo"); 23872 23873 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 23874 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 23875 throw new SecurityException("Caller must have the " 23876 + SET_HARMFUL_APP_WARNINGS + " permission."); 23877 } 23878 23879 synchronized(mPackages) { 23880 mSettings.setHarmfulAppWarningLPw(packageName, warning, userId); 23881 scheduleWritePackageRestrictionsLocked(userId); 23882 } 23883 } 23884 23885 @Nullable 23886 @Override 23887 public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) { 23888 final int callingUid = Binder.getCallingUid(); 23889 final int callingAppId = UserHandle.getAppId(callingUid); 23890 23891 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23892 true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo"); 23893 23894 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 23895 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 23896 throw new SecurityException("Caller must have the " 23897 + SET_HARMFUL_APP_WARNINGS + " permission."); 23898 } 23899 23900 synchronized(mPackages) { 23901 return mSettings.getHarmfulAppWarningLPr(packageName, userId); 23902 } 23903 } 23904} 23905 23906interface PackageSender { 23907 /** 23908 * @param userIds User IDs where the action occurred on a full application 23909 * @param instantUserIds User IDs where the action occurred on an instant application 23910 */ 23911 void sendPackageBroadcast(final String action, final String pkg, 23912 final Bundle extras, final int flags, final String targetPkg, 23913 final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds); 23914 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 23915 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds); 23916 void notifyPackageAdded(String packageName); 23917 void notifyPackageRemoved(String packageName); 23918} 23919