PackageManagerService.java revision 96212bca06842f223a0e9e377e2c00a2008c96a2
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.DELETE_PACKAGES; 20import static android.Manifest.permission.INSTALL_PACKAGES; 21import static android.Manifest.permission.MANAGE_DEVICE_ADMINS; 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.SET_HARMFUL_APP_WARNINGS; 26import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 27import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509; 28import static android.content.pm.PackageManager.CERT_INPUT_SHA256; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 34import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 39import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 42import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 43import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 44import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 52import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 53import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 54import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 55import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 59import static android.content.pm.PackageManager.INSTALL_INTERNAL; 60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 66import static android.content.pm.PackageManager.MATCH_ALL; 67import static android.content.pm.PackageManager.MATCH_ANY_USER; 68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER; 81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 83import static android.content.pm.PackageManager.PERMISSION_DENIED; 84import static android.content.pm.PackageManager.PERMISSION_GRANTED; 85import static android.content.pm.PackageParser.isApkFile; 86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 87import static android.os.storage.StorageManager.FLAG_STORAGE_CE; 88import static android.os.storage.StorageManager.FLAG_STORAGE_DE; 89import static android.system.OsConstants.O_CREAT; 90import static android.system.OsConstants.O_RDWR; 91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 95import static com.android.internal.util.ArrayUtils.appendElement; 96import static com.android.internal.util.ArrayUtils.appendInt; 97import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 100import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 101import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures; 104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists; 105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile; 106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride; 107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo; 108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles; 109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime; 110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo; 111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures; 112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE; 113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS; 114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 115 116import android.Manifest; 117import android.annotation.IntDef; 118import android.annotation.NonNull; 119import android.annotation.Nullable; 120import android.annotation.UserIdInt; 121import android.app.ActivityManager; 122import android.app.ActivityManagerInternal; 123import android.app.AppOpsManager; 124import android.app.IActivityManager; 125import android.app.ResourcesManager; 126import android.app.admin.IDevicePolicyManager; 127import android.app.admin.SecurityLog; 128import android.app.backup.IBackupManager; 129import android.content.BroadcastReceiver; 130import android.content.ComponentName; 131import android.content.ContentResolver; 132import android.content.Context; 133import android.content.IIntentReceiver; 134import android.content.Intent; 135import android.content.IntentFilter; 136import android.content.IntentSender; 137import android.content.IntentSender.SendIntentException; 138import android.content.ServiceConnection; 139import android.content.pm.ActivityInfo; 140import android.content.pm.ApplicationInfo; 141import android.content.pm.AppsQueryHelper; 142import android.content.pm.AuxiliaryResolveInfo; 143import android.content.pm.ChangedPackages; 144import android.content.pm.ComponentInfo; 145import android.content.pm.FallbackCategoryProvider; 146import android.content.pm.FeatureInfo; 147import android.content.pm.IDexModuleRegisterCallback; 148import android.content.pm.IOnPermissionsChangeListener; 149import android.content.pm.IPackageDataObserver; 150import android.content.pm.IPackageDeleteObserver; 151import android.content.pm.IPackageDeleteObserver2; 152import android.content.pm.IPackageInstallObserver2; 153import android.content.pm.IPackageInstaller; 154import android.content.pm.IPackageManager; 155import android.content.pm.IPackageManagerNative; 156import android.content.pm.IPackageMoveObserver; 157import android.content.pm.IPackageStatsObserver; 158import android.content.pm.InstantAppInfo; 159import android.content.pm.InstantAppRequest; 160import android.content.pm.InstantAppResolveInfo; 161import android.content.pm.InstrumentationInfo; 162import android.content.pm.IntentFilterVerificationInfo; 163import android.content.pm.KeySet; 164import android.content.pm.PackageCleanItem; 165import android.content.pm.PackageInfo; 166import android.content.pm.PackageInfoLite; 167import android.content.pm.PackageInstaller; 168import android.content.pm.PackageList; 169import android.content.pm.PackageManager; 170import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 171import android.content.pm.PackageManagerInternal; 172import android.content.pm.PackageManagerInternal.PackageListObserver; 173import android.content.pm.PackageParser; 174import android.content.pm.PackageParser.ActivityIntentInfo; 175import android.content.pm.PackageParser.Package; 176import android.content.pm.PackageParser.PackageLite; 177import android.content.pm.PackageParser.PackageParserException; 178import android.content.pm.PackageParser.ParseFlags; 179import android.content.pm.PackageParser.ServiceIntentInfo; 180import android.content.pm.PackageParser.SigningDetails; 181import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion; 182import android.content.pm.PackageStats; 183import android.content.pm.PackageUserState; 184import android.content.pm.ParceledListSlice; 185import android.content.pm.PermissionGroupInfo; 186import android.content.pm.PermissionInfo; 187import android.content.pm.ProviderInfo; 188import android.content.pm.ResolveInfo; 189import android.content.pm.SELinuxUtil; 190import android.content.pm.ServiceInfo; 191import android.content.pm.SharedLibraryInfo; 192import android.content.pm.Signature; 193import android.content.pm.UserInfo; 194import android.content.pm.VerifierDeviceIdentity; 195import android.content.pm.VerifierInfo; 196import android.content.pm.VersionedPackage; 197import android.content.pm.dex.ArtManager; 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.PersistableBundle; 220import android.os.Process; 221import android.os.RemoteCallbackList; 222import android.os.RemoteException; 223import android.os.ResultReceiver; 224import android.os.SELinux; 225import android.os.ServiceManager; 226import android.os.ShellCallback; 227import android.os.SystemClock; 228import android.os.SystemProperties; 229import android.os.Trace; 230import android.os.UserHandle; 231import android.os.UserManager; 232import android.os.UserManagerInternal; 233import android.os.storage.IStorageManager; 234import android.os.storage.StorageEventListener; 235import android.os.storage.StorageManager; 236import android.os.storage.StorageManagerInternal; 237import android.os.storage.VolumeInfo; 238import android.os.storage.VolumeRecord; 239import android.provider.Settings.Global; 240import android.provider.Settings.Secure; 241import android.security.KeyStore; 242import android.security.SystemKeyStore; 243import android.service.pm.PackageServiceDumpProto; 244import android.system.ErrnoException; 245import android.system.Os; 246import android.text.TextUtils; 247import android.text.format.DateUtils; 248import android.util.ArrayMap; 249import android.util.ArraySet; 250import android.util.Base64; 251import android.util.ByteStringUtils; 252import android.util.DisplayMetrics; 253import android.util.EventLog; 254import android.util.ExceptionUtils; 255import android.util.Log; 256import android.util.LogPrinter; 257import android.util.LongSparseArray; 258import android.util.LongSparseLongArray; 259import android.util.MathUtils; 260import android.util.PackageUtils; 261import android.util.Pair; 262import android.util.PrintStreamPrinter; 263import android.util.Slog; 264import android.util.SparseArray; 265import android.util.SparseBooleanArray; 266import android.util.SparseIntArray; 267import android.util.TimingsTraceLog; 268import android.util.Xml; 269import android.util.jar.StrictJarFile; 270import android.util.proto.ProtoOutputStream; 271import android.view.Display; 272 273import com.android.internal.R; 274import com.android.internal.annotations.GuardedBy; 275import com.android.internal.app.IMediaContainerService; 276import com.android.internal.app.ResolverActivity; 277import com.android.internal.app.SuspendedAppActivity; 278import com.android.internal.content.NativeLibraryHelper; 279import com.android.internal.content.PackageHelper; 280import com.android.internal.logging.MetricsLogger; 281import com.android.internal.os.IParcelFileDescriptorFactory; 282import com.android.internal.os.SomeArgs; 283import com.android.internal.os.Zygote; 284import com.android.internal.telephony.CarrierAppUtils; 285import com.android.internal.util.ArrayUtils; 286import com.android.internal.util.ConcurrentUtils; 287import com.android.internal.util.DumpUtils; 288import com.android.internal.util.FastXmlSerializer; 289import com.android.internal.util.IndentingPrintWriter; 290import com.android.internal.util.Preconditions; 291import com.android.internal.util.XmlUtils; 292import com.android.server.AttributeCache; 293import com.android.server.DeviceIdleController; 294import com.android.server.EventLogTags; 295import com.android.server.FgThread; 296import com.android.server.IntentResolver; 297import com.android.server.LocalServices; 298import com.android.server.LockGuard; 299import com.android.server.ServiceThread; 300import com.android.server.SystemConfig; 301import com.android.server.SystemServerInitThreadPool; 302import com.android.server.Watchdog; 303import com.android.server.net.NetworkPolicyManagerInternal; 304import com.android.server.pm.Installer.InstallerException; 305import com.android.server.pm.Settings.DatabaseVersion; 306import com.android.server.pm.Settings.VersionInfo; 307import com.android.server.pm.dex.ArtManagerService; 308import com.android.server.pm.dex.DexLogger; 309import com.android.server.pm.dex.DexManager; 310import com.android.server.pm.dex.DexoptOptions; 311import com.android.server.pm.dex.PackageDexUsage; 312import com.android.server.pm.permission.BasePermission; 313import com.android.server.pm.permission.DefaultPermissionGrantPolicy; 314import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback; 315import com.android.server.pm.permission.PermissionManagerInternal; 316import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback; 317import com.android.server.pm.permission.PermissionManagerService; 318import com.android.server.pm.permission.PermissionsState; 319import com.android.server.pm.permission.PermissionsState.PermissionState; 320import com.android.server.security.VerityUtils; 321import com.android.server.storage.DeviceStorageMonitorInternal; 322 323import dalvik.system.CloseGuard; 324import dalvik.system.VMRuntime; 325 326import libcore.io.IoUtils; 327 328import org.xmlpull.v1.XmlPullParser; 329import org.xmlpull.v1.XmlPullParserException; 330import org.xmlpull.v1.XmlSerializer; 331 332import java.io.BufferedOutputStream; 333import java.io.ByteArrayInputStream; 334import java.io.ByteArrayOutputStream; 335import java.io.File; 336import java.io.FileDescriptor; 337import java.io.FileInputStream; 338import java.io.FileOutputStream; 339import java.io.FilenameFilter; 340import java.io.IOException; 341import java.io.PrintWriter; 342import java.lang.annotation.Retention; 343import java.lang.annotation.RetentionPolicy; 344import java.nio.charset.StandardCharsets; 345import java.security.DigestException; 346import java.security.DigestInputStream; 347import java.security.MessageDigest; 348import java.security.NoSuchAlgorithmException; 349import java.security.PublicKey; 350import java.security.SecureRandom; 351import java.security.cert.CertificateException; 352import java.util.ArrayList; 353import java.util.Arrays; 354import java.util.Collection; 355import java.util.Collections; 356import java.util.Comparator; 357import java.util.HashMap; 358import java.util.HashSet; 359import java.util.Iterator; 360import java.util.LinkedHashSet; 361import java.util.List; 362import java.util.Map; 363import java.util.Objects; 364import java.util.Set; 365import java.util.concurrent.CountDownLatch; 366import java.util.concurrent.Future; 367import java.util.concurrent.TimeUnit; 368import java.util.concurrent.atomic.AtomicBoolean; 369import java.util.concurrent.atomic.AtomicInteger; 370 371/** 372 * Keep track of all those APKs everywhere. 373 * <p> 374 * Internally there are two important locks: 375 * <ul> 376 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 377 * and other related state. It is a fine-grained lock that should only be held 378 * momentarily, as it's one of the most contended locks in the system. 379 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 380 * operations typically involve heavy lifting of application data on disk. Since 381 * {@code installd} is single-threaded, and it's operations can often be slow, 382 * this lock should never be acquired while already holding {@link #mPackages}. 383 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 384 * holding {@link #mInstallLock}. 385 * </ul> 386 * Many internal methods rely on the caller to hold the appropriate locks, and 387 * this contract is expressed through method name suffixes: 388 * <ul> 389 * <li>fooLI(): the caller must hold {@link #mInstallLock} 390 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 391 * being modified must be frozen 392 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 393 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 394 * </ul> 395 * <p> 396 * Because this class is very central to the platform's security; please run all 397 * CTS and unit tests whenever making modifications: 398 * 399 * <pre> 400 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 401 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 402 * </pre> 403 */ 404public class PackageManagerService extends IPackageManager.Stub 405 implements PackageSender { 406 static final String TAG = "PackageManager"; 407 public static final boolean DEBUG_SETTINGS = false; 408 static final boolean DEBUG_PREFERRED = false; 409 static final boolean DEBUG_UPGRADE = false; 410 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 411 private static final boolean DEBUG_BACKUP = false; 412 public static final boolean DEBUG_INSTALL = false; 413 public static final boolean DEBUG_REMOVE = true; 414 private static final boolean DEBUG_BROADCASTS = false; 415 private static final boolean DEBUG_SHOW_INFO = false; 416 private static final boolean DEBUG_PACKAGE_INFO = false; 417 private static final boolean DEBUG_INTENT_MATCHING = false; 418 public static final boolean DEBUG_PACKAGE_SCANNING = false; 419 private static final boolean DEBUG_VERIFY = false; 420 private static final boolean DEBUG_FILTERS = false; 421 public static final boolean DEBUG_PERMISSIONS = false; 422 private static final boolean DEBUG_SHARED_LIBRARIES = false; 423 public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE; 424 425 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 426 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 427 // user, but by default initialize to this. 428 public static final boolean DEBUG_DEXOPT = false; 429 430 private static final boolean DEBUG_ABI_SELECTION = false; 431 private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE; 432 private static final boolean DEBUG_TRIAGED_MISSING = false; 433 private static final boolean DEBUG_APP_DATA = false; 434 435 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 436 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 437 438 private static final boolean HIDE_EPHEMERAL_APIS = false; 439 440 private static final boolean ENABLE_FREE_CACHE_V2 = 441 SystemProperties.getBoolean("fw.free_cache_v2", true); 442 443 private static final int RADIO_UID = Process.PHONE_UID; 444 private static final int LOG_UID = Process.LOG_UID; 445 private static final int NFC_UID = Process.NFC_UID; 446 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 447 private static final int SHELL_UID = Process.SHELL_UID; 448 private static final int SE_UID = Process.SE_UID; 449 450 // Suffix used during package installation when copying/moving 451 // package apks to install directory. 452 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 453 454 static final int SCAN_NO_DEX = 1<<0; 455 static final int SCAN_UPDATE_SIGNATURE = 1<<1; 456 static final int SCAN_NEW_INSTALL = 1<<2; 457 static final int SCAN_UPDATE_TIME = 1<<3; 458 static final int SCAN_BOOTING = 1<<4; 459 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6; 460 static final int SCAN_REQUIRE_KNOWN = 1<<7; 461 static final int SCAN_MOVE = 1<<8; 462 static final int SCAN_INITIAL = 1<<9; 463 static final int SCAN_CHECK_ONLY = 1<<10; 464 static final int SCAN_DONT_KILL_APP = 1<<11; 465 static final int SCAN_IGNORE_FROZEN = 1<<12; 466 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13; 467 static final int SCAN_AS_INSTANT_APP = 1<<14; 468 static final int SCAN_AS_FULL_APP = 1<<15; 469 static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16; 470 static final int SCAN_AS_SYSTEM = 1<<17; 471 static final int SCAN_AS_PRIVILEGED = 1<<18; 472 static final int SCAN_AS_OEM = 1<<19; 473 static final int SCAN_AS_VENDOR = 1<<20; 474 static final int SCAN_AS_PRODUCT = 1<<21; 475 476 @IntDef(flag = true, prefix = { "SCAN_" }, value = { 477 SCAN_NO_DEX, 478 SCAN_UPDATE_SIGNATURE, 479 SCAN_NEW_INSTALL, 480 SCAN_UPDATE_TIME, 481 SCAN_BOOTING, 482 SCAN_DELETE_DATA_ON_FAILURES, 483 SCAN_REQUIRE_KNOWN, 484 SCAN_MOVE, 485 SCAN_INITIAL, 486 SCAN_CHECK_ONLY, 487 SCAN_DONT_KILL_APP, 488 SCAN_IGNORE_FROZEN, 489 SCAN_FIRST_BOOT_OR_UPGRADE, 490 SCAN_AS_INSTANT_APP, 491 SCAN_AS_FULL_APP, 492 SCAN_AS_VIRTUAL_PRELOAD, 493 }) 494 @Retention(RetentionPolicy.SOURCE) 495 public @interface ScanFlags {} 496 497 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 498 /** Extension of the compressed packages */ 499 public final static String COMPRESSED_EXTENSION = ".gz"; 500 /** Suffix of stub packages on the system partition */ 501 public final static String STUB_SUFFIX = "-Stub"; 502 503 private static final int[] EMPTY_INT_ARRAY = new int[0]; 504 505 private static final int TYPE_UNKNOWN = 0; 506 private static final int TYPE_ACTIVITY = 1; 507 private static final int TYPE_RECEIVER = 2; 508 private static final int TYPE_SERVICE = 3; 509 private static final int TYPE_PROVIDER = 4; 510 @IntDef(prefix = { "TYPE_" }, value = { 511 TYPE_UNKNOWN, 512 TYPE_ACTIVITY, 513 TYPE_RECEIVER, 514 TYPE_SERVICE, 515 TYPE_PROVIDER, 516 }) 517 @Retention(RetentionPolicy.SOURCE) 518 public @interface ComponentType {} 519 520 /** 521 * Timeout (in milliseconds) after which the watchdog should declare that 522 * our handler thread is wedged. The usual default for such things is one 523 * minute but we sometimes do very lengthy I/O operations on this thread, 524 * such as installing multi-gigabyte applications, so ours needs to be longer. 525 */ 526 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 527 528 /** 529 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 530 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 531 * settings entry if available, otherwise we use the hardcoded default. If it's been 532 * more than this long since the last fstrim, we force one during the boot sequence. 533 * 534 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 535 * one gets run at the next available charging+idle time. This final mandatory 536 * no-fstrim check kicks in only of the other scheduling criteria is never met. 537 */ 538 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 539 540 /** 541 * Whether verification is enabled by default. 542 */ 543 private static final boolean DEFAULT_VERIFY_ENABLE = true; 544 545 /** 546 * The default maximum time to wait for the verification agent to return in 547 * milliseconds. 548 */ 549 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 550 551 /** 552 * The default response for package verification timeout. 553 * 554 * This can be either PackageManager.VERIFICATION_ALLOW or 555 * PackageManager.VERIFICATION_REJECT. 556 */ 557 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 558 559 public static final String PLATFORM_PACKAGE_NAME = "android"; 560 561 public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 562 563 public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 564 DEFAULT_CONTAINER_PACKAGE, 565 "com.android.defcontainer.DefaultContainerService"); 566 567 private static final String KILL_APP_REASON_GIDS_CHANGED = 568 "permission grant or revoke changed gids"; 569 570 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 571 "permissions revoked"; 572 573 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 574 575 private static final String PACKAGE_SCHEME = "package"; 576 577 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 578 579 private static final String PRODUCT_OVERLAY_DIR = "/product/overlay"; 580 581 private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob"; 582 583 /** Canonical intent used to identify what counts as a "web browser" app */ 584 private static final Intent sBrowserIntent; 585 static { 586 sBrowserIntent = new Intent(); 587 sBrowserIntent.setAction(Intent.ACTION_VIEW); 588 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 589 sBrowserIntent.setData(Uri.parse("http:")); 590 sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL); 591 } 592 593 /** 594 * The set of all protected actions [i.e. those actions for which a high priority 595 * intent filter is disallowed]. 596 */ 597 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 598 static { 599 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 600 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 601 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 602 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 603 } 604 605 // Compilation reasons. 606 public static final int REASON_UNKNOWN = -1; 607 public static final int REASON_FIRST_BOOT = 0; 608 public static final int REASON_BOOT = 1; 609 public static final int REASON_INSTALL = 2; 610 public static final int REASON_BACKGROUND_DEXOPT = 3; 611 public static final int REASON_AB_OTA = 4; 612 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5; 613 public static final int REASON_SHARED = 6; 614 615 public static final int REASON_LAST = REASON_SHARED; 616 617 /** 618 * Version number for the package parser cache. Increment this whenever the format or 619 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 620 */ 621 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 622 623 /** 624 * Whether the package parser cache is enabled. 625 */ 626 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 627 628 /** 629 * Permissions required in order to receive instant application lifecycle broadcasts. 630 */ 631 private static final String[] INSTANT_APP_BROADCAST_PERMISSION = 632 new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS }; 633 634 final ServiceThread mHandlerThread; 635 636 final PackageHandler mHandler; 637 638 private final ProcessLoggingHandler mProcessLoggingHandler; 639 640 /** 641 * Messages for {@link #mHandler} that need to wait for system ready before 642 * being dispatched. 643 */ 644 private ArrayList<Message> mPostSystemReadyMessages; 645 646 final int mSdkVersion = Build.VERSION.SDK_INT; 647 648 final Context mContext; 649 final boolean mFactoryTest; 650 final boolean mOnlyCore; 651 final DisplayMetrics mMetrics; 652 final int mDefParseFlags; 653 final String[] mSeparateProcesses; 654 final boolean mIsUpgrade; 655 final boolean mIsPreNUpgrade; 656 final boolean mIsPreNMR1Upgrade; 657 658 // Have we told the Activity Manager to whitelist the default container service by uid yet? 659 @GuardedBy("mPackages") 660 boolean mDefaultContainerWhitelisted = false; 661 662 @GuardedBy("mPackages") 663 private boolean mDexOptDialogShown; 664 665 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 666 // LOCK HELD. Can be called with mInstallLock held. 667 @GuardedBy("mInstallLock") 668 final Installer mInstaller; 669 670 /** Directory where installed applications are stored */ 671 private static final File sAppInstallDir = 672 new File(Environment.getDataDirectory(), "app"); 673 /** Directory where installed application's 32-bit native libraries are copied. */ 674 private static final File sAppLib32InstallDir = 675 new File(Environment.getDataDirectory(), "app-lib"); 676 /** Directory where code and non-resource assets of forward-locked applications are stored */ 677 private static final File sDrmAppPrivateInstallDir = 678 new File(Environment.getDataDirectory(), "app-private"); 679 680 // ---------------------------------------------------------------- 681 682 // Lock for state used when installing and doing other long running 683 // operations. Methods that must be called with this lock held have 684 // the suffix "LI". 685 final Object mInstallLock = new Object(); 686 687 // ---------------------------------------------------------------- 688 689 // Keys are String (package name), values are Package. This also serves 690 // as the lock for the global state. Methods that must be called with 691 // this lock held have the prefix "LP". 692 @GuardedBy("mPackages") 693 final ArrayMap<String, PackageParser.Package> mPackages = 694 new ArrayMap<String, PackageParser.Package>(); 695 696 final ArrayMap<String, Set<String>> mKnownCodebase = 697 new ArrayMap<String, Set<String>>(); 698 699 // Keys are isolated uids and values are the uid of the application 700 // that created the isolated proccess. 701 @GuardedBy("mPackages") 702 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 703 704 /** 705 * Tracks new system packages [received in an OTA] that we expect to 706 * find updated user-installed versions. Keys are package name, values 707 * are package location. 708 */ 709 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 710 /** 711 * Tracks high priority intent filters for protected actions. During boot, certain 712 * filter actions are protected and should never be allowed to have a high priority 713 * intent filter for them. However, there is one, and only one exception -- the 714 * setup wizard. It must be able to define a high priority intent filter for these 715 * actions to ensure there are no escapes from the wizard. We need to delay processing 716 * of these during boot as we need to look at all of the system packages in order 717 * to know which component is the setup wizard. 718 */ 719 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 720 /** 721 * Whether or not processing protected filters should be deferred. 722 */ 723 private boolean mDeferProtectedFilters = true; 724 725 /** 726 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 727 */ 728 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 729 /** 730 * Whether or not system app permissions should be promoted from install to runtime. 731 */ 732 boolean mPromoteSystemApps; 733 734 @GuardedBy("mPackages") 735 final Settings mSettings; 736 737 /** 738 * Set of package names that are currently "frozen", which means active 739 * surgery is being done on the code/data for that package. The platform 740 * will refuse to launch frozen packages to avoid race conditions. 741 * 742 * @see PackageFreezer 743 */ 744 @GuardedBy("mPackages") 745 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 746 747 final ProtectedPackages mProtectedPackages; 748 749 @GuardedBy("mLoadedVolumes") 750 final ArraySet<String> mLoadedVolumes = new ArraySet<>(); 751 752 boolean mFirstBoot; 753 754 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 755 756 @GuardedBy("mAvailableFeatures") 757 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 758 759 private final InstantAppRegistry mInstantAppRegistry; 760 761 @GuardedBy("mPackages") 762 int mChangedPackagesSequenceNumber; 763 /** 764 * List of changed [installed, removed or updated] packages. 765 * mapping from user id -> sequence number -> package name 766 */ 767 @GuardedBy("mPackages") 768 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 769 /** 770 * The sequence number of the last change to a package. 771 * mapping from user id -> package name -> sequence number 772 */ 773 @GuardedBy("mPackages") 774 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 775 776 @GuardedBy("mPackages") 777 final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>(); 778 779 class PackageParserCallback implements PackageParser.Callback { 780 @Override public final boolean hasFeature(String feature) { 781 return PackageManagerService.this.hasSystemFeature(feature, 0); 782 } 783 784 final List<PackageParser.Package> getStaticOverlayPackages( 785 Collection<PackageParser.Package> allPackages, String targetPackageName) { 786 if ("android".equals(targetPackageName)) { 787 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 788 // native AssetManager. 789 return null; 790 } 791 792 List<PackageParser.Package> overlayPackages = null; 793 for (PackageParser.Package p : allPackages) { 794 if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) { 795 if (overlayPackages == null) { 796 overlayPackages = new ArrayList<PackageParser.Package>(); 797 } 798 overlayPackages.add(p); 799 } 800 } 801 if (overlayPackages != null) { 802 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 803 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 804 return p1.mOverlayPriority - p2.mOverlayPriority; 805 } 806 }; 807 Collections.sort(overlayPackages, cmp); 808 } 809 return overlayPackages; 810 } 811 812 final String[] getStaticOverlayPaths(List<PackageParser.Package> overlayPackages, 813 String targetPath) { 814 if (overlayPackages == null || overlayPackages.isEmpty()) { 815 return null; 816 } 817 List<String> overlayPathList = null; 818 for (PackageParser.Package overlayPackage : overlayPackages) { 819 if (targetPath == null) { 820 if (overlayPathList == null) { 821 overlayPathList = new ArrayList<String>(); 822 } 823 overlayPathList.add(overlayPackage.baseCodePath); 824 continue; 825 } 826 827 try { 828 // Creates idmaps for system to parse correctly the Android manifest of the 829 // target package. 830 // 831 // OverlayManagerService will update each of them with a correct gid from its 832 // target package app id. 833 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 834 UserHandle.getSharedAppGid( 835 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 836 if (overlayPathList == null) { 837 overlayPathList = new ArrayList<String>(); 838 } 839 overlayPathList.add(overlayPackage.baseCodePath); 840 } catch (InstallerException e) { 841 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 842 overlayPackage.baseCodePath); 843 } 844 } 845 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 846 } 847 848 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 849 List<PackageParser.Package> overlayPackages; 850 synchronized (mInstallLock) { 851 synchronized (mPackages) { 852 overlayPackages = getStaticOverlayPackages( 853 mPackages.values(), targetPackageName); 854 } 855 // It is safe to keep overlayPackages without holding mPackages because static overlay 856 // packages can't be uninstalled or disabled. 857 return getStaticOverlayPaths(overlayPackages, targetPath); 858 } 859 } 860 861 @Override public final String[] getOverlayApks(String targetPackageName) { 862 return getStaticOverlayPaths(targetPackageName, null); 863 } 864 865 @Override public final String[] getOverlayPaths(String targetPackageName, 866 String targetPath) { 867 return getStaticOverlayPaths(targetPackageName, targetPath); 868 } 869 } 870 871 class ParallelPackageParserCallback extends PackageParserCallback { 872 List<PackageParser.Package> mOverlayPackages = null; 873 874 void findStaticOverlayPackages() { 875 synchronized (mPackages) { 876 for (PackageParser.Package p : mPackages.values()) { 877 if (p.mOverlayIsStatic) { 878 if (mOverlayPackages == null) { 879 mOverlayPackages = new ArrayList<PackageParser.Package>(); 880 } 881 mOverlayPackages.add(p); 882 } 883 } 884 } 885 } 886 887 @Override 888 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 889 // We can trust mOverlayPackages without holding mPackages because package uninstall 890 // can't happen while running parallel parsing. 891 // And we can call mInstaller inside getStaticOverlayPaths without holding mInstallLock 892 // because mInstallLock is held before running parallel parsing. 893 // Moreover holding mPackages or mInstallLock on each parsing thread causes dead-lock. 894 return mOverlayPackages == null ? null : 895 getStaticOverlayPaths( 896 getStaticOverlayPackages(mOverlayPackages, targetPackageName), 897 targetPath); 898 } 899 } 900 901 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 902 final ParallelPackageParserCallback mParallelPackageParserCallback = 903 new ParallelPackageParserCallback(); 904 905 public static final class SharedLibraryEntry { 906 public final @Nullable String path; 907 public final @Nullable String apk; 908 public final @NonNull SharedLibraryInfo info; 909 910 SharedLibraryEntry(String _path, String _apk, String name, long version, int type, 911 String declaringPackageName, long declaringPackageVersionCode) { 912 path = _path; 913 apk = _apk; 914 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 915 declaringPackageName, declaringPackageVersionCode), null); 916 } 917 } 918 919 // Currently known shared libraries. 920 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 921 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 922 new ArrayMap<>(); 923 924 // All available activities, for your resolving pleasure. 925 final ActivityIntentResolver mActivities = 926 new ActivityIntentResolver(); 927 928 // All available receivers, for your resolving pleasure. 929 final ActivityIntentResolver mReceivers = 930 new ActivityIntentResolver(); 931 932 // All available services, for your resolving pleasure. 933 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 934 935 // All available providers, for your resolving pleasure. 936 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 937 938 // Mapping from provider base names (first directory in content URI codePath) 939 // to the provider information. 940 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 941 new ArrayMap<String, PackageParser.Provider>(); 942 943 // Mapping from instrumentation class names to info about them. 944 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 945 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 946 947 // Packages whose data we have transfered into another package, thus 948 // should no longer exist. 949 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 950 951 // Broadcast actions that are only available to the system. 952 @GuardedBy("mProtectedBroadcasts") 953 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>(); 954 955 /** List of packages waiting for verification. */ 956 final SparseArray<PackageVerificationState> mPendingVerification 957 = new SparseArray<PackageVerificationState>(); 958 959 final PackageInstallerService mInstallerService; 960 961 final ArtManagerService mArtManagerService; 962 963 private final PackageDexOptimizer mPackageDexOptimizer; 964 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 965 // is used by other apps). 966 private final DexManager mDexManager; 967 968 private AtomicInteger mNextMoveId = new AtomicInteger(); 969 private final MoveCallbacks mMoveCallbacks; 970 971 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 972 973 // Cache of users who need badging. 974 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 975 976 /** Token for keys in mPendingVerification. */ 977 private int mPendingVerificationToken = 0; 978 979 volatile boolean mSystemReady; 980 volatile boolean mSafeMode; 981 volatile boolean mHasSystemUidErrors; 982 private volatile boolean mWebInstantAppsDisabled; 983 984 ApplicationInfo mAndroidApplication; 985 final ActivityInfo mResolveActivity = new ActivityInfo(); 986 final ResolveInfo mResolveInfo = new ResolveInfo(); 987 ComponentName mResolveComponentName; 988 PackageParser.Package mPlatformPackage; 989 ComponentName mCustomResolverComponentName; 990 991 boolean mResolverReplaced = false; 992 993 private final @Nullable ComponentName mIntentFilterVerifierComponent; 994 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 995 996 private int mIntentFilterVerificationToken = 0; 997 998 /** The service connection to the ephemeral resolver */ 999 final InstantAppResolverConnection mInstantAppResolverConnection; 1000 /** Component used to show resolver settings for Instant Apps */ 1001 final ComponentName mInstantAppResolverSettingsComponent; 1002 1003 /** Activity used to install instant applications */ 1004 ActivityInfo mInstantAppInstallerActivity; 1005 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 1006 1007 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 1008 = new SparseArray<IntentFilterVerificationState>(); 1009 1010 // TODO remove this and go through mPermissonManager directly 1011 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 1012 private final PermissionManagerInternal mPermissionManager; 1013 1014 // List of packages names to keep cached, even if they are uninstalled for all users 1015 private List<String> mKeepUninstalledPackages; 1016 1017 private UserManagerInternal mUserManagerInternal; 1018 private ActivityManagerInternal mActivityManagerInternal; 1019 1020 private DeviceIdleController.LocalService mDeviceIdleController; 1021 1022 private File mCacheDir; 1023 1024 private Future<?> mPrepareAppDataFuture; 1025 1026 private static class IFVerificationParams { 1027 PackageParser.Package pkg; 1028 boolean replacing; 1029 int userId; 1030 int verifierUid; 1031 1032 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1033 int _userId, int _verifierUid) { 1034 pkg = _pkg; 1035 replacing = _replacing; 1036 userId = _userId; 1037 replacing = _replacing; 1038 verifierUid = _verifierUid; 1039 } 1040 } 1041 1042 private interface IntentFilterVerifier<T extends IntentFilter> { 1043 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1044 T filter, String packageName); 1045 void startVerifications(int userId); 1046 void receiveVerificationResponse(int verificationId); 1047 } 1048 1049 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1050 private Context mContext; 1051 private ComponentName mIntentFilterVerifierComponent; 1052 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1053 1054 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1055 mContext = context; 1056 mIntentFilterVerifierComponent = verifierComponent; 1057 } 1058 1059 private String getDefaultScheme() { 1060 return IntentFilter.SCHEME_HTTPS; 1061 } 1062 1063 @Override 1064 public void startVerifications(int userId) { 1065 // Launch verifications requests 1066 int count = mCurrentIntentFilterVerifications.size(); 1067 for (int n=0; n<count; n++) { 1068 int verificationId = mCurrentIntentFilterVerifications.get(n); 1069 final IntentFilterVerificationState ivs = 1070 mIntentFilterVerificationStates.get(verificationId); 1071 1072 String packageName = ivs.getPackageName(); 1073 1074 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1075 final int filterCount = filters.size(); 1076 ArraySet<String> domainsSet = new ArraySet<>(); 1077 for (int m=0; m<filterCount; m++) { 1078 PackageParser.ActivityIntentInfo filter = filters.get(m); 1079 domainsSet.addAll(filter.getHostsList()); 1080 } 1081 synchronized (mPackages) { 1082 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1083 packageName, domainsSet) != null) { 1084 scheduleWriteSettingsLocked(); 1085 } 1086 } 1087 sendVerificationRequest(verificationId, ivs); 1088 } 1089 mCurrentIntentFilterVerifications.clear(); 1090 } 1091 1092 private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) { 1093 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1094 verificationIntent.putExtra( 1095 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1096 verificationId); 1097 verificationIntent.putExtra( 1098 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1099 getDefaultScheme()); 1100 verificationIntent.putExtra( 1101 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1102 ivs.getHostsString()); 1103 verificationIntent.putExtra( 1104 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1105 ivs.getPackageName()); 1106 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1107 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1108 1109 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1110 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1111 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1112 UserHandle.USER_SYSTEM, true, "intent filter verifier"); 1113 1114 mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM); 1115 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1116 "Sending IntentFilter verification broadcast"); 1117 } 1118 1119 public void receiveVerificationResponse(int verificationId) { 1120 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1121 1122 final boolean verified = ivs.isVerified(); 1123 1124 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1125 final int count = filters.size(); 1126 if (DEBUG_DOMAIN_VERIFICATION) { 1127 Slog.i(TAG, "Received verification response " + verificationId 1128 + " for " + count + " filters, verified=" + verified); 1129 } 1130 for (int n=0; n<count; n++) { 1131 PackageParser.ActivityIntentInfo filter = filters.get(n); 1132 filter.setVerified(verified); 1133 1134 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1135 + " verified with result:" + verified + " and hosts:" 1136 + ivs.getHostsString()); 1137 } 1138 1139 mIntentFilterVerificationStates.remove(verificationId); 1140 1141 final String packageName = ivs.getPackageName(); 1142 IntentFilterVerificationInfo ivi = null; 1143 1144 synchronized (mPackages) { 1145 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1146 } 1147 if (ivi == null) { 1148 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1149 + verificationId + " packageName:" + packageName); 1150 return; 1151 } 1152 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1153 "Updating IntentFilterVerificationInfo for package " + packageName 1154 +" verificationId:" + verificationId); 1155 1156 synchronized (mPackages) { 1157 if (verified) { 1158 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1159 } else { 1160 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1161 } 1162 scheduleWriteSettingsLocked(); 1163 1164 final int userId = ivs.getUserId(); 1165 if (userId != UserHandle.USER_ALL) { 1166 final int userStatus = 1167 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1168 1169 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1170 boolean needUpdate = false; 1171 1172 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1173 // already been set by the User thru the Disambiguation dialog 1174 switch (userStatus) { 1175 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1176 if (verified) { 1177 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1178 } else { 1179 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1180 } 1181 needUpdate = true; 1182 break; 1183 1184 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1185 if (verified) { 1186 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1187 needUpdate = true; 1188 } 1189 break; 1190 1191 default: 1192 // Nothing to do 1193 } 1194 1195 if (needUpdate) { 1196 mSettings.updateIntentFilterVerificationStatusLPw( 1197 packageName, updatedStatus, userId); 1198 scheduleWritePackageRestrictionsLocked(userId); 1199 } 1200 } 1201 } 1202 } 1203 1204 @Override 1205 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1206 ActivityIntentInfo filter, String packageName) { 1207 if (!hasValidDomains(filter)) { 1208 return false; 1209 } 1210 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1211 if (ivs == null) { 1212 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1213 packageName); 1214 } 1215 if (DEBUG_DOMAIN_VERIFICATION) { 1216 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1217 } 1218 ivs.addFilter(filter); 1219 return true; 1220 } 1221 1222 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1223 int userId, int verificationId, String packageName) { 1224 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1225 verifierUid, userId, packageName); 1226 ivs.setPendingState(); 1227 synchronized (mPackages) { 1228 mIntentFilterVerificationStates.append(verificationId, ivs); 1229 mCurrentIntentFilterVerifications.add(verificationId); 1230 } 1231 return ivs; 1232 } 1233 } 1234 1235 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1236 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1237 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1238 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1239 } 1240 1241 // Set of pending broadcasts for aggregating enable/disable of components. 1242 static class PendingPackageBroadcasts { 1243 // for each user id, a map of <package name -> components within that package> 1244 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1245 1246 public PendingPackageBroadcasts() { 1247 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1248 } 1249 1250 public ArrayList<String> get(int userId, String packageName) { 1251 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1252 return packages.get(packageName); 1253 } 1254 1255 public void put(int userId, String packageName, ArrayList<String> components) { 1256 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1257 packages.put(packageName, components); 1258 } 1259 1260 public void remove(int userId, String packageName) { 1261 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1262 if (packages != null) { 1263 packages.remove(packageName); 1264 } 1265 } 1266 1267 public void remove(int userId) { 1268 mUidMap.remove(userId); 1269 } 1270 1271 public int userIdCount() { 1272 return mUidMap.size(); 1273 } 1274 1275 public int userIdAt(int n) { 1276 return mUidMap.keyAt(n); 1277 } 1278 1279 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1280 return mUidMap.get(userId); 1281 } 1282 1283 public int size() { 1284 // total number of pending broadcast entries across all userIds 1285 int num = 0; 1286 for (int i = 0; i< mUidMap.size(); i++) { 1287 num += mUidMap.valueAt(i).size(); 1288 } 1289 return num; 1290 } 1291 1292 public void clear() { 1293 mUidMap.clear(); 1294 } 1295 1296 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1297 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1298 if (map == null) { 1299 map = new ArrayMap<String, ArrayList<String>>(); 1300 mUidMap.put(userId, map); 1301 } 1302 return map; 1303 } 1304 } 1305 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1306 1307 // Service Connection to remote media container service to copy 1308 // package uri's from external media onto secure containers 1309 // or internal storage. 1310 private IMediaContainerService mContainerService = null; 1311 1312 static final int SEND_PENDING_BROADCAST = 1; 1313 static final int MCS_BOUND = 3; 1314 static final int END_COPY = 4; 1315 static final int INIT_COPY = 5; 1316 static final int MCS_UNBIND = 6; 1317 static final int START_CLEANING_PACKAGE = 7; 1318 static final int FIND_INSTALL_LOC = 8; 1319 static final int POST_INSTALL = 9; 1320 static final int MCS_RECONNECT = 10; 1321 static final int MCS_GIVE_UP = 11; 1322 static final int WRITE_SETTINGS = 13; 1323 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1324 static final int PACKAGE_VERIFIED = 15; 1325 static final int CHECK_PENDING_VERIFICATION = 16; 1326 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1327 static final int INTENT_FILTER_VERIFIED = 18; 1328 static final int WRITE_PACKAGE_LIST = 19; 1329 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1330 static final int DEF_CONTAINER_BIND = 21; 1331 1332 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1333 1334 // Delay time in millisecs 1335 static final int BROADCAST_DELAY = 10 * 1000; 1336 1337 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1338 2 * 60 * 60 * 1000L; /* two hours */ 1339 1340 static UserManagerService sUserManager; 1341 1342 // Stores a list of users whose package restrictions file needs to be updated 1343 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1344 1345 final private DefaultContainerConnection mDefContainerConn = 1346 new DefaultContainerConnection(); 1347 class DefaultContainerConnection implements ServiceConnection { 1348 public void onServiceConnected(ComponentName name, IBinder service) { 1349 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1350 final IMediaContainerService imcs = IMediaContainerService.Stub 1351 .asInterface(Binder.allowBlocking(service)); 1352 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1353 } 1354 1355 public void onServiceDisconnected(ComponentName name) { 1356 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1357 } 1358 } 1359 1360 // Recordkeeping of restore-after-install operations that are currently in flight 1361 // between the Package Manager and the Backup Manager 1362 static class PostInstallData { 1363 public InstallArgs args; 1364 public PackageInstalledInfo res; 1365 1366 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1367 args = _a; 1368 res = _r; 1369 } 1370 } 1371 1372 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1373 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1374 1375 // XML tags for backup/restore of various bits of state 1376 private static final String TAG_PREFERRED_BACKUP = "pa"; 1377 private static final String TAG_DEFAULT_APPS = "da"; 1378 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1379 1380 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1381 private static final String TAG_ALL_GRANTS = "rt-grants"; 1382 private static final String TAG_GRANT = "grant"; 1383 private static final String ATTR_PACKAGE_NAME = "pkg"; 1384 1385 private static final String TAG_PERMISSION = "perm"; 1386 private static final String ATTR_PERMISSION_NAME = "name"; 1387 private static final String ATTR_IS_GRANTED = "g"; 1388 private static final String ATTR_USER_SET = "set"; 1389 private static final String ATTR_USER_FIXED = "fixed"; 1390 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1391 1392 // System/policy permission grants are not backed up 1393 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1394 FLAG_PERMISSION_POLICY_FIXED 1395 | FLAG_PERMISSION_SYSTEM_FIXED 1396 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1397 1398 // And we back up these user-adjusted states 1399 private static final int USER_RUNTIME_GRANT_MASK = 1400 FLAG_PERMISSION_USER_SET 1401 | FLAG_PERMISSION_USER_FIXED 1402 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1403 1404 final @Nullable String mRequiredVerifierPackage; 1405 final @NonNull String mRequiredInstallerPackage; 1406 final @NonNull String mRequiredUninstallerPackage; 1407 final @Nullable String mSetupWizardPackage; 1408 final @Nullable String mStorageManagerPackage; 1409 final @Nullable String mSystemTextClassifierPackage; 1410 final @NonNull String mServicesSystemSharedLibraryPackageName; 1411 final @NonNull String mSharedSystemSharedLibraryPackageName; 1412 1413 private final PackageUsage mPackageUsage = new PackageUsage(); 1414 private final CompilerStats mCompilerStats = new CompilerStats(); 1415 1416 class PackageHandler extends Handler { 1417 private boolean mBound = false; 1418 final ArrayList<HandlerParams> mPendingInstalls = 1419 new ArrayList<HandlerParams>(); 1420 1421 private boolean connectToService() { 1422 if (DEBUG_INSTALL) Log.i(TAG, "Trying to bind to DefaultContainerService"); 1423 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1424 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1425 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1426 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1427 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1428 mBound = true; 1429 return true; 1430 } 1431 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1432 return false; 1433 } 1434 1435 private void disconnectService() { 1436 mContainerService = null; 1437 mBound = false; 1438 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1439 mContext.unbindService(mDefContainerConn); 1440 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1441 } 1442 1443 PackageHandler(Looper looper) { 1444 super(looper); 1445 } 1446 1447 public void handleMessage(Message msg) { 1448 try { 1449 doHandleMessage(msg); 1450 } finally { 1451 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1452 } 1453 } 1454 1455 void doHandleMessage(Message msg) { 1456 switch (msg.what) { 1457 case DEF_CONTAINER_BIND: 1458 if (!mBound) { 1459 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS", 1460 System.identityHashCode(mHandler)); 1461 if (!connectToService()) { 1462 Slog.e(TAG, "Failed to bind to media container service"); 1463 } 1464 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS", 1465 System.identityHashCode(mHandler)); 1466 } 1467 break; 1468 case INIT_COPY: { 1469 HandlerParams params = (HandlerParams) msg.obj; 1470 int idx = mPendingInstalls.size(); 1471 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1472 // If a bind was already initiated we dont really 1473 // need to do anything. The pending install 1474 // will be processed later on. 1475 if (!mBound) { 1476 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1477 System.identityHashCode(mHandler)); 1478 // If this is the only one pending we might 1479 // have to bind to the service again. 1480 if (!connectToService()) { 1481 Slog.e(TAG, "Failed to bind to media container service"); 1482 params.serviceError(); 1483 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1484 System.identityHashCode(mHandler)); 1485 if (params.traceMethod != null) { 1486 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1487 params.traceCookie); 1488 } 1489 return; 1490 } else { 1491 // Once we bind to the service, the first 1492 // pending request will be processed. 1493 mPendingInstalls.add(idx, params); 1494 } 1495 } else { 1496 mPendingInstalls.add(idx, params); 1497 // Already bound to the service. Just make 1498 // sure we trigger off processing the first request. 1499 if (idx == 0) { 1500 mHandler.sendEmptyMessage(MCS_BOUND); 1501 } 1502 } 1503 break; 1504 } 1505 case MCS_BOUND: { 1506 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1507 if (msg.obj != null) { 1508 mContainerService = (IMediaContainerService) msg.obj; 1509 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1510 System.identityHashCode(mHandler)); 1511 } 1512 if (mContainerService == null) { 1513 if (!mBound) { 1514 // Something seriously wrong since we are not bound and we are not 1515 // waiting for connection. Bail out. 1516 Slog.e(TAG, "Cannot bind to media container service"); 1517 for (HandlerParams params : mPendingInstalls) { 1518 // Indicate service bind error 1519 params.serviceError(); 1520 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1521 System.identityHashCode(params)); 1522 if (params.traceMethod != null) { 1523 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1524 params.traceMethod, params.traceCookie); 1525 } 1526 } 1527 mPendingInstalls.clear(); 1528 } else { 1529 Slog.w(TAG, "Waiting to connect to media container service"); 1530 } 1531 } else if (mPendingInstalls.size() > 0) { 1532 HandlerParams params = mPendingInstalls.get(0); 1533 if (params != null) { 1534 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1535 System.identityHashCode(params)); 1536 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1537 if (params.startCopy()) { 1538 // We are done... look for more work or to 1539 // go idle. 1540 if (DEBUG_SD_INSTALL) Log.i(TAG, 1541 "Checking for more work or unbind..."); 1542 // Delete pending install 1543 if (mPendingInstalls.size() > 0) { 1544 mPendingInstalls.remove(0); 1545 } 1546 if (mPendingInstalls.size() == 0) { 1547 if (mBound) { 1548 if (DEBUG_SD_INSTALL) Log.i(TAG, 1549 "Posting delayed MCS_UNBIND"); 1550 removeMessages(MCS_UNBIND); 1551 Message ubmsg = obtainMessage(MCS_UNBIND); 1552 // Unbind after a little delay, to avoid 1553 // continual thrashing. 1554 sendMessageDelayed(ubmsg, 10000); 1555 } 1556 } else { 1557 // There are more pending requests in queue. 1558 // Just post MCS_BOUND message to trigger processing 1559 // of next pending install. 1560 if (DEBUG_SD_INSTALL) Log.i(TAG, 1561 "Posting MCS_BOUND for next work"); 1562 mHandler.sendEmptyMessage(MCS_BOUND); 1563 } 1564 } 1565 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1566 } 1567 } else { 1568 // Should never happen ideally. 1569 Slog.w(TAG, "Empty queue"); 1570 } 1571 break; 1572 } 1573 case MCS_RECONNECT: { 1574 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1575 if (mPendingInstalls.size() > 0) { 1576 if (mBound) { 1577 disconnectService(); 1578 } 1579 if (!connectToService()) { 1580 Slog.e(TAG, "Failed to bind to media container service"); 1581 for (HandlerParams params : mPendingInstalls) { 1582 // Indicate service bind error 1583 params.serviceError(); 1584 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1585 System.identityHashCode(params)); 1586 } 1587 mPendingInstalls.clear(); 1588 } 1589 } 1590 break; 1591 } 1592 case MCS_UNBIND: { 1593 // If there is no actual work left, then time to unbind. 1594 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1595 1596 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1597 if (mBound) { 1598 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1599 1600 disconnectService(); 1601 } 1602 } else if (mPendingInstalls.size() > 0) { 1603 // There are more pending requests in queue. 1604 // Just post MCS_BOUND message to trigger processing 1605 // of next pending install. 1606 mHandler.sendEmptyMessage(MCS_BOUND); 1607 } 1608 1609 break; 1610 } 1611 case MCS_GIVE_UP: { 1612 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1613 HandlerParams params = mPendingInstalls.remove(0); 1614 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1615 System.identityHashCode(params)); 1616 break; 1617 } 1618 case SEND_PENDING_BROADCAST: { 1619 String packages[]; 1620 ArrayList<String> components[]; 1621 int size = 0; 1622 int uids[]; 1623 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1624 synchronized (mPackages) { 1625 if (mPendingBroadcasts == null) { 1626 return; 1627 } 1628 size = mPendingBroadcasts.size(); 1629 if (size <= 0) { 1630 // Nothing to be done. Just return 1631 return; 1632 } 1633 packages = new String[size]; 1634 components = new ArrayList[size]; 1635 uids = new int[size]; 1636 int i = 0; // filling out the above arrays 1637 1638 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1639 int packageUserId = mPendingBroadcasts.userIdAt(n); 1640 Iterator<Map.Entry<String, ArrayList<String>>> it 1641 = mPendingBroadcasts.packagesForUserId(packageUserId) 1642 .entrySet().iterator(); 1643 while (it.hasNext() && i < size) { 1644 Map.Entry<String, ArrayList<String>> ent = it.next(); 1645 packages[i] = ent.getKey(); 1646 components[i] = ent.getValue(); 1647 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1648 uids[i] = (ps != null) 1649 ? UserHandle.getUid(packageUserId, ps.appId) 1650 : -1; 1651 i++; 1652 } 1653 } 1654 size = i; 1655 mPendingBroadcasts.clear(); 1656 } 1657 // Send broadcasts 1658 for (int i = 0; i < size; i++) { 1659 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1660 } 1661 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1662 break; 1663 } 1664 case START_CLEANING_PACKAGE: { 1665 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1666 final String packageName = (String)msg.obj; 1667 final int userId = msg.arg1; 1668 final boolean andCode = msg.arg2 != 0; 1669 synchronized (mPackages) { 1670 if (userId == UserHandle.USER_ALL) { 1671 int[] users = sUserManager.getUserIds(); 1672 for (int user : users) { 1673 mSettings.addPackageToCleanLPw( 1674 new PackageCleanItem(user, packageName, andCode)); 1675 } 1676 } else { 1677 mSettings.addPackageToCleanLPw( 1678 new PackageCleanItem(userId, packageName, andCode)); 1679 } 1680 } 1681 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1682 startCleaningPackages(); 1683 } break; 1684 case POST_INSTALL: { 1685 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1686 1687 PostInstallData data = mRunningInstalls.get(msg.arg1); 1688 final boolean didRestore = (msg.arg2 != 0); 1689 mRunningInstalls.delete(msg.arg1); 1690 1691 if (data != null) { 1692 InstallArgs args = data.args; 1693 PackageInstalledInfo parentRes = data.res; 1694 1695 final boolean grantPermissions = (args.installFlags 1696 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1697 final boolean killApp = (args.installFlags 1698 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1699 final boolean virtualPreload = ((args.installFlags 1700 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 1701 final String[] grantedPermissions = args.installGrantPermissions; 1702 1703 // Handle the parent package 1704 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1705 virtualPreload, grantedPermissions, didRestore, 1706 args.installerPackageName, args.observer); 1707 1708 // Handle the child packages 1709 final int childCount = (parentRes.addedChildPackages != null) 1710 ? parentRes.addedChildPackages.size() : 0; 1711 for (int i = 0; i < childCount; i++) { 1712 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1713 handlePackagePostInstall(childRes, grantPermissions, killApp, 1714 virtualPreload, grantedPermissions, false /*didRestore*/, 1715 args.installerPackageName, args.observer); 1716 } 1717 1718 // Log tracing if needed 1719 if (args.traceMethod != null) { 1720 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1721 args.traceCookie); 1722 } 1723 } else { 1724 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1725 } 1726 1727 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1728 } break; 1729 case WRITE_SETTINGS: { 1730 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1731 synchronized (mPackages) { 1732 removeMessages(WRITE_SETTINGS); 1733 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1734 mSettings.writeLPr(); 1735 mDirtyUsers.clear(); 1736 } 1737 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1738 } break; 1739 case WRITE_PACKAGE_RESTRICTIONS: { 1740 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1741 synchronized (mPackages) { 1742 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1743 for (int userId : mDirtyUsers) { 1744 mSettings.writePackageRestrictionsLPr(userId); 1745 } 1746 mDirtyUsers.clear(); 1747 } 1748 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1749 } break; 1750 case WRITE_PACKAGE_LIST: { 1751 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1752 synchronized (mPackages) { 1753 removeMessages(WRITE_PACKAGE_LIST); 1754 mSettings.writePackageListLPr(msg.arg1); 1755 } 1756 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1757 } break; 1758 case CHECK_PENDING_VERIFICATION: { 1759 final int verificationId = msg.arg1; 1760 final PackageVerificationState state = mPendingVerification.get(verificationId); 1761 1762 if ((state != null) && !state.timeoutExtended()) { 1763 final InstallArgs args = state.getInstallArgs(); 1764 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1765 1766 Slog.i(TAG, "Verification timed out for " + originUri); 1767 mPendingVerification.remove(verificationId); 1768 1769 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1770 1771 final UserHandle user = args.getUser(); 1772 if (getDefaultVerificationResponse(user) 1773 == PackageManager.VERIFICATION_ALLOW) { 1774 Slog.i(TAG, "Continuing with installation of " + originUri); 1775 state.setVerifierResponse(Binder.getCallingUid(), 1776 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1777 broadcastPackageVerified(verificationId, originUri, 1778 PackageManager.VERIFICATION_ALLOW, user); 1779 try { 1780 ret = args.copyApk(mContainerService, true); 1781 } catch (RemoteException e) { 1782 Slog.e(TAG, "Could not contact the ContainerService"); 1783 } 1784 } else { 1785 broadcastPackageVerified(verificationId, originUri, 1786 PackageManager.VERIFICATION_REJECT, user); 1787 } 1788 1789 Trace.asyncTraceEnd( 1790 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1791 1792 processPendingInstall(args, ret); 1793 mHandler.sendEmptyMessage(MCS_UNBIND); 1794 } 1795 break; 1796 } 1797 case PACKAGE_VERIFIED: { 1798 final int verificationId = msg.arg1; 1799 1800 final PackageVerificationState state = mPendingVerification.get(verificationId); 1801 if (state == null) { 1802 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1803 break; 1804 } 1805 1806 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1807 1808 state.setVerifierResponse(response.callerUid, response.code); 1809 1810 if (state.isVerificationComplete()) { 1811 mPendingVerification.remove(verificationId); 1812 1813 final InstallArgs args = state.getInstallArgs(); 1814 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1815 1816 int ret; 1817 if (state.isInstallAllowed()) { 1818 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1819 broadcastPackageVerified(verificationId, originUri, 1820 response.code, state.getInstallArgs().getUser()); 1821 try { 1822 ret = args.copyApk(mContainerService, true); 1823 } catch (RemoteException e) { 1824 Slog.e(TAG, "Could not contact the ContainerService"); 1825 } 1826 } else { 1827 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1828 } 1829 1830 Trace.asyncTraceEnd( 1831 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1832 1833 processPendingInstall(args, ret); 1834 mHandler.sendEmptyMessage(MCS_UNBIND); 1835 } 1836 1837 break; 1838 } 1839 case START_INTENT_FILTER_VERIFICATIONS: { 1840 IFVerificationParams params = (IFVerificationParams) msg.obj; 1841 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1842 params.replacing, params.pkg); 1843 break; 1844 } 1845 case INTENT_FILTER_VERIFIED: { 1846 final int verificationId = msg.arg1; 1847 1848 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1849 verificationId); 1850 if (state == null) { 1851 Slog.w(TAG, "Invalid IntentFilter verification token " 1852 + verificationId + " received"); 1853 break; 1854 } 1855 1856 final int userId = state.getUserId(); 1857 1858 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1859 "Processing IntentFilter verification with token:" 1860 + verificationId + " and userId:" + userId); 1861 1862 final IntentFilterVerificationResponse response = 1863 (IntentFilterVerificationResponse) msg.obj; 1864 1865 state.setVerifierResponse(response.callerUid, response.code); 1866 1867 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1868 "IntentFilter verification with token:" + verificationId 1869 + " and userId:" + userId 1870 + " is settings verifier response with response code:" 1871 + response.code); 1872 1873 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1874 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1875 + response.getFailedDomainsString()); 1876 } 1877 1878 if (state.isVerificationComplete()) { 1879 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1880 } else { 1881 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1882 "IntentFilter verification with token:" + verificationId 1883 + " was not said to be complete"); 1884 } 1885 1886 break; 1887 } 1888 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1889 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1890 mInstantAppResolverConnection, 1891 (InstantAppRequest) msg.obj, 1892 mInstantAppInstallerActivity, 1893 mHandler); 1894 } 1895 } 1896 } 1897 } 1898 1899 private PermissionCallback mPermissionCallback = new PermissionCallback() { 1900 @Override 1901 public void onGidsChanged(int appId, int userId) { 1902 mHandler.post(new Runnable() { 1903 @Override 1904 public void run() { 1905 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 1906 } 1907 }); 1908 } 1909 @Override 1910 public void onPermissionGranted(int uid, int userId) { 1911 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1912 1913 // Not critical; if this is lost, the application has to request again. 1914 synchronized (mPackages) { 1915 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 1916 } 1917 } 1918 @Override 1919 public void onInstallPermissionGranted() { 1920 synchronized (mPackages) { 1921 scheduleWriteSettingsLocked(); 1922 } 1923 } 1924 @Override 1925 public void onPermissionRevoked(int uid, int userId) { 1926 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1927 1928 synchronized (mPackages) { 1929 // Critical; after this call the application should never have the permission 1930 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 1931 } 1932 1933 final int appId = UserHandle.getAppId(uid); 1934 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 1935 } 1936 @Override 1937 public void onInstallPermissionRevoked() { 1938 synchronized (mPackages) { 1939 scheduleWriteSettingsLocked(); 1940 } 1941 } 1942 @Override 1943 public void onPermissionUpdated(int[] updatedUserIds, boolean sync) { 1944 synchronized (mPackages) { 1945 for (int userId : updatedUserIds) { 1946 mSettings.writeRuntimePermissionsForUserLPr(userId, sync); 1947 } 1948 } 1949 } 1950 @Override 1951 public void onInstallPermissionUpdated() { 1952 synchronized (mPackages) { 1953 scheduleWriteSettingsLocked(); 1954 } 1955 } 1956 @Override 1957 public void onPermissionRemoved() { 1958 synchronized (mPackages) { 1959 mSettings.writeLPr(); 1960 } 1961 } 1962 }; 1963 1964 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1965 boolean killApp, boolean virtualPreload, String[] grantedPermissions, 1966 boolean launchedForRestore, String installerPackage, 1967 IPackageInstallObserver2 installObserver) { 1968 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1969 // Send the removed broadcasts 1970 if (res.removedInfo != null) { 1971 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1972 } 1973 1974 // Now that we successfully installed the package, grant runtime 1975 // permissions if requested before broadcasting the install. Also 1976 // for legacy apps in permission review mode we clear the permission 1977 // review flag which is used to emulate runtime permissions for 1978 // legacy apps. 1979 if (grantPermissions) { 1980 final int callingUid = Binder.getCallingUid(); 1981 mPermissionManager.grantRequestedRuntimePermissions( 1982 res.pkg, res.newUsers, grantedPermissions, callingUid, 1983 mPermissionCallback); 1984 } 1985 1986 final boolean update = res.removedInfo != null 1987 && res.removedInfo.removedPackage != null; 1988 final String installerPackageName = 1989 res.installerPackageName != null 1990 ? res.installerPackageName 1991 : res.removedInfo != null 1992 ? res.removedInfo.installerPackageName 1993 : null; 1994 1995 // If this is the first time we have child packages for a disabled privileged 1996 // app that had no children, we grant requested runtime permissions to the new 1997 // children if the parent on the system image had them already granted. 1998 if (res.pkg.parentPackage != null) { 1999 final int callingUid = Binder.getCallingUid(); 2000 mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage( 2001 res.pkg, callingUid, mPermissionCallback); 2002 } 2003 2004 synchronized (mPackages) { 2005 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 2006 } 2007 2008 final String packageName = res.pkg.applicationInfo.packageName; 2009 2010 // Determine the set of users who are adding this package for 2011 // the first time vs. those who are seeing an update. 2012 int[] firstUserIds = EMPTY_INT_ARRAY; 2013 int[] firstInstantUserIds = EMPTY_INT_ARRAY; 2014 int[] updateUserIds = EMPTY_INT_ARRAY; 2015 int[] instantUserIds = EMPTY_INT_ARRAY; 2016 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 2017 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 2018 for (int newUser : res.newUsers) { 2019 final boolean isInstantApp = ps.getInstantApp(newUser); 2020 if (allNewUsers) { 2021 if (isInstantApp) { 2022 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 2023 } else { 2024 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 2025 } 2026 continue; 2027 } 2028 boolean isNew = true; 2029 for (int origUser : res.origUsers) { 2030 if (origUser == newUser) { 2031 isNew = false; 2032 break; 2033 } 2034 } 2035 if (isNew) { 2036 if (isInstantApp) { 2037 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 2038 } else { 2039 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 2040 } 2041 } else { 2042 if (isInstantApp) { 2043 instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser); 2044 } else { 2045 updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser); 2046 } 2047 } 2048 } 2049 2050 // Send installed broadcasts if the package is not a static shared lib. 2051 if (res.pkg.staticSharedLibName == null) { 2052 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 2053 2054 // Send added for users that see the package for the first time 2055 // sendPackageAddedForNewUsers also deals with system apps 2056 int appId = UserHandle.getAppId(res.uid); 2057 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 2058 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload, 2059 virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds); 2060 2061 // Send added for users that don't see the package for the first time 2062 Bundle extras = new Bundle(1); 2063 extras.putInt(Intent.EXTRA_UID, res.uid); 2064 if (update) { 2065 extras.putBoolean(Intent.EXTRA_REPLACING, true); 2066 } 2067 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2068 extras, 0 /*flags*/, 2069 null /*targetPackage*/, null /*finishedReceiver*/, 2070 updateUserIds, instantUserIds); 2071 if (installerPackageName != null) { 2072 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2073 extras, 0 /*flags*/, 2074 installerPackageName, null /*finishedReceiver*/, 2075 updateUserIds, instantUserIds); 2076 } 2077 2078 // Send replaced for users that don't see the package for the first time 2079 if (update) { 2080 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 2081 packageName, extras, 0 /*flags*/, 2082 null /*targetPackage*/, null /*finishedReceiver*/, 2083 updateUserIds, instantUserIds); 2084 if (installerPackageName != null) { 2085 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 2086 extras, 0 /*flags*/, 2087 installerPackageName, null /*finishedReceiver*/, 2088 updateUserIds, instantUserIds); 2089 } 2090 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 2091 null /*package*/, null /*extras*/, 0 /*flags*/, 2092 packageName /*targetPackage*/, 2093 null /*finishedReceiver*/, updateUserIds, instantUserIds); 2094 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 2095 // First-install and we did a restore, so we're responsible for the 2096 // first-launch broadcast. 2097 if (DEBUG_BACKUP) { 2098 Slog.i(TAG, "Post-restore of " + packageName 2099 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds)); 2100 } 2101 sendFirstLaunchBroadcast(packageName, installerPackage, 2102 firstUserIds, firstInstantUserIds); 2103 } 2104 2105 // Send broadcast package appeared if forward locked/external for all users 2106 // treat asec-hosted packages like removable media on upgrade 2107 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 2108 if (DEBUG_INSTALL) { 2109 Slog.i(TAG, "upgrading pkg " + res.pkg 2110 + " is ASEC-hosted -> AVAILABLE"); 2111 } 2112 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2113 ArrayList<String> pkgList = new ArrayList<>(1); 2114 pkgList.add(packageName); 2115 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2116 } 2117 } 2118 2119 // Work that needs to happen on first install within each user 2120 if (firstUserIds != null && firstUserIds.length > 0) { 2121 synchronized (mPackages) { 2122 for (int userId : firstUserIds) { 2123 // If this app is a browser and it's newly-installed for some 2124 // users, clear any default-browser state in those users. The 2125 // app's nature doesn't depend on the user, so we can just check 2126 // its browser nature in any user and generalize. 2127 if (packageIsBrowser(packageName, userId)) { 2128 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2129 } 2130 2131 // We may also need to apply pending (restored) runtime 2132 // permission grants within these users. 2133 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2134 } 2135 } 2136 } 2137 2138 if (allNewUsers && !update) { 2139 notifyPackageAdded(packageName); 2140 } 2141 2142 // Log current value of "unknown sources" setting 2143 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2144 getUnknownSourcesSettings()); 2145 2146 // Remove the replaced package's older resources safely now 2147 // We delete after a gc for applications on sdcard. 2148 if (res.removedInfo != null && res.removedInfo.args != null) { 2149 Runtime.getRuntime().gc(); 2150 synchronized (mInstallLock) { 2151 res.removedInfo.args.doPostDeleteLI(true); 2152 } 2153 } else { 2154 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2155 // and not block here. 2156 VMRuntime.getRuntime().requestConcurrentGC(); 2157 } 2158 2159 // Notify DexManager that the package was installed for new users. 2160 // The updated users should already be indexed and the package code paths 2161 // should not change. 2162 // Don't notify the manager for ephemeral apps as they are not expected to 2163 // survive long enough to benefit of background optimizations. 2164 for (int userId : firstUserIds) { 2165 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2166 // There's a race currently where some install events may interleave with an uninstall. 2167 // This can lead to package info being null (b/36642664). 2168 if (info != null) { 2169 mDexManager.notifyPackageInstalled(info, userId); 2170 } 2171 } 2172 } 2173 2174 // If someone is watching installs - notify them 2175 if (installObserver != null) { 2176 try { 2177 Bundle extras = extrasForInstallResult(res); 2178 installObserver.onPackageInstalled(res.name, res.returnCode, 2179 res.returnMsg, extras); 2180 } catch (RemoteException e) { 2181 Slog.i(TAG, "Observer no longer exists."); 2182 } 2183 } 2184 } 2185 2186 private StorageEventListener mStorageListener = new StorageEventListener() { 2187 @Override 2188 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2189 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2190 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2191 final String volumeUuid = vol.getFsUuid(); 2192 2193 // Clean up any users or apps that were removed or recreated 2194 // while this volume was missing 2195 sUserManager.reconcileUsers(volumeUuid); 2196 reconcileApps(volumeUuid); 2197 2198 // Clean up any install sessions that expired or were 2199 // cancelled while this volume was missing 2200 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2201 2202 loadPrivatePackages(vol); 2203 2204 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2205 unloadPrivatePackages(vol); 2206 } 2207 } 2208 } 2209 2210 @Override 2211 public void onVolumeForgotten(String fsUuid) { 2212 if (TextUtils.isEmpty(fsUuid)) { 2213 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2214 return; 2215 } 2216 2217 // Remove any apps installed on the forgotten volume 2218 synchronized (mPackages) { 2219 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2220 for (PackageSetting ps : packages) { 2221 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2222 deletePackageVersioned(new VersionedPackage(ps.name, 2223 PackageManager.VERSION_CODE_HIGHEST), 2224 new LegacyPackageDeleteObserver(null).getBinder(), 2225 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2226 // Try very hard to release any references to this package 2227 // so we don't risk the system server being killed due to 2228 // open FDs 2229 AttributeCache.instance().removePackage(ps.name); 2230 } 2231 2232 mSettings.onVolumeForgotten(fsUuid); 2233 mSettings.writeLPr(); 2234 } 2235 } 2236 }; 2237 2238 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2239 Bundle extras = null; 2240 switch (res.returnCode) { 2241 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2242 extras = new Bundle(); 2243 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2244 res.origPermission); 2245 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2246 res.origPackage); 2247 break; 2248 } 2249 case PackageManager.INSTALL_SUCCEEDED: { 2250 extras = new Bundle(); 2251 extras.putBoolean(Intent.EXTRA_REPLACING, 2252 res.removedInfo != null && res.removedInfo.removedPackage != null); 2253 break; 2254 } 2255 } 2256 return extras; 2257 } 2258 2259 void scheduleWriteSettingsLocked() { 2260 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2261 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2262 } 2263 } 2264 2265 void scheduleWritePackageListLocked(int userId) { 2266 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2267 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2268 msg.arg1 = userId; 2269 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2270 } 2271 } 2272 2273 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2274 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2275 scheduleWritePackageRestrictionsLocked(userId); 2276 } 2277 2278 void scheduleWritePackageRestrictionsLocked(int userId) { 2279 final int[] userIds = (userId == UserHandle.USER_ALL) 2280 ? sUserManager.getUserIds() : new int[]{userId}; 2281 for (int nextUserId : userIds) { 2282 if (!sUserManager.exists(nextUserId)) return; 2283 mDirtyUsers.add(nextUserId); 2284 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2285 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2286 } 2287 } 2288 } 2289 2290 public static PackageManagerService main(Context context, Installer installer, 2291 boolean factoryTest, boolean onlyCore) { 2292 // Self-check for initial settings. 2293 PackageManagerServiceCompilerMapping.checkProperties(); 2294 2295 PackageManagerService m = new PackageManagerService(context, installer, 2296 factoryTest, onlyCore); 2297 m.enableSystemUserPackages(); 2298 ServiceManager.addService("package", m); 2299 final PackageManagerNative pmn = m.new PackageManagerNative(); 2300 ServiceManager.addService("package_native", pmn); 2301 return m; 2302 } 2303 2304 private void enableSystemUserPackages() { 2305 if (!UserManager.isSplitSystemUser()) { 2306 return; 2307 } 2308 // For system user, enable apps based on the following conditions: 2309 // - app is whitelisted or belong to one of these groups: 2310 // -- system app which has no launcher icons 2311 // -- system app which has INTERACT_ACROSS_USERS permission 2312 // -- system IME app 2313 // - app is not in the blacklist 2314 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2315 Set<String> enableApps = new ArraySet<>(); 2316 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2317 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2318 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2319 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2320 enableApps.addAll(wlApps); 2321 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2322 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2323 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2324 enableApps.removeAll(blApps); 2325 Log.i(TAG, "Applications installed for system user: " + enableApps); 2326 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2327 UserHandle.SYSTEM); 2328 final int allAppsSize = allAps.size(); 2329 synchronized (mPackages) { 2330 for (int i = 0; i < allAppsSize; i++) { 2331 String pName = allAps.get(i); 2332 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2333 // Should not happen, but we shouldn't be failing if it does 2334 if (pkgSetting == null) { 2335 continue; 2336 } 2337 boolean install = enableApps.contains(pName); 2338 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2339 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2340 + " for system user"); 2341 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2342 } 2343 } 2344 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2345 } 2346 } 2347 2348 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2349 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2350 Context.DISPLAY_SERVICE); 2351 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2352 } 2353 2354 /** 2355 * Requests that files preopted on a secondary system partition be copied to the data partition 2356 * if possible. Note that the actual copying of the files is accomplished by init for security 2357 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2358 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2359 */ 2360 private static void requestCopyPreoptedFiles() { 2361 final int WAIT_TIME_MS = 100; 2362 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2363 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2364 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2365 // We will wait for up to 100 seconds. 2366 final long timeStart = SystemClock.uptimeMillis(); 2367 final long timeEnd = timeStart + 100 * 1000; 2368 long timeNow = timeStart; 2369 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2370 try { 2371 Thread.sleep(WAIT_TIME_MS); 2372 } catch (InterruptedException e) { 2373 // Do nothing 2374 } 2375 timeNow = SystemClock.uptimeMillis(); 2376 if (timeNow > timeEnd) { 2377 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2378 Slog.wtf(TAG, "cppreopt did not finish!"); 2379 break; 2380 } 2381 } 2382 2383 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2384 } 2385 } 2386 2387 public PackageManagerService(Context context, Installer installer, 2388 boolean factoryTest, boolean onlyCore) { 2389 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2390 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2391 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2392 SystemClock.uptimeMillis()); 2393 2394 if (mSdkVersion <= 0) { 2395 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2396 } 2397 2398 mContext = context; 2399 2400 mFactoryTest = factoryTest; 2401 mOnlyCore = onlyCore; 2402 mMetrics = new DisplayMetrics(); 2403 mInstaller = installer; 2404 2405 // Create sub-components that provide services / data. Order here is important. 2406 synchronized (mInstallLock) { 2407 synchronized (mPackages) { 2408 // Expose private service for system components to use. 2409 LocalServices.addService( 2410 PackageManagerInternal.class, new PackageManagerInternalImpl()); 2411 sUserManager = new UserManagerService(context, this, 2412 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2413 mPermissionManager = PermissionManagerService.create(context, 2414 new DefaultPermissionGrantedCallback() { 2415 @Override 2416 public void onDefaultRuntimePermissionsGranted(int userId) { 2417 synchronized(mPackages) { 2418 mSettings.onDefaultRuntimePermissionsGrantedLPr(userId); 2419 } 2420 } 2421 }, mPackages /*externalLock*/); 2422 mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy(); 2423 mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages); 2424 } 2425 } 2426 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2427 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2428 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2429 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2430 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2431 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2432 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2433 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2434 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2435 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2436 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2437 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2438 mSettings.addSharedUserLPw("android.uid.se", SE_UID, 2439 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2440 2441 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2442 if (separateProcesses != null && separateProcesses.length() > 0) { 2443 if ("*".equals(separateProcesses)) { 2444 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2445 mSeparateProcesses = null; 2446 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2447 } else { 2448 mDefParseFlags = 0; 2449 mSeparateProcesses = separateProcesses.split(","); 2450 Slog.w(TAG, "Running with debug.separate_processes: " 2451 + separateProcesses); 2452 } 2453 } else { 2454 mDefParseFlags = 0; 2455 mSeparateProcesses = null; 2456 } 2457 2458 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2459 "*dexopt*"); 2460 DexManager.Listener dexManagerListener = DexLogger.getListener(this, 2461 installer, mInstallLock); 2462 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock, 2463 dexManagerListener); 2464 mArtManagerService = new ArtManagerService(this, installer, mInstallLock); 2465 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2466 2467 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2468 FgThread.get().getLooper()); 2469 2470 getDefaultDisplayMetrics(context, mMetrics); 2471 2472 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2473 SystemConfig systemConfig = SystemConfig.getInstance(); 2474 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2475 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2476 2477 mProtectedPackages = new ProtectedPackages(mContext); 2478 2479 synchronized (mInstallLock) { 2480 // writer 2481 synchronized (mPackages) { 2482 mHandlerThread = new ServiceThread(TAG, 2483 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2484 mHandlerThread.start(); 2485 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2486 mProcessLoggingHandler = new ProcessLoggingHandler(); 2487 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2488 mInstantAppRegistry = new InstantAppRegistry(this); 2489 2490 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2491 final int builtInLibCount = libConfig.size(); 2492 for (int i = 0; i < builtInLibCount; i++) { 2493 String name = libConfig.keyAt(i); 2494 String path = libConfig.valueAt(i); 2495 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2496 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2497 } 2498 2499 SELinuxMMAC.readInstallPolicy(); 2500 2501 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2502 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2503 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2504 2505 // Clean up orphaned packages for which the code path doesn't exist 2506 // and they are an update to a system app - caused by bug/32321269 2507 final int packageSettingCount = mSettings.mPackages.size(); 2508 for (int i = packageSettingCount - 1; i >= 0; i--) { 2509 PackageSetting ps = mSettings.mPackages.valueAt(i); 2510 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2511 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2512 mSettings.mPackages.removeAt(i); 2513 mSettings.enableSystemPackageLPw(ps.name); 2514 } 2515 } 2516 2517 if (mFirstBoot) { 2518 requestCopyPreoptedFiles(); 2519 } 2520 2521 String customResolverActivity = Resources.getSystem().getString( 2522 R.string.config_customResolverActivity); 2523 if (TextUtils.isEmpty(customResolverActivity)) { 2524 customResolverActivity = null; 2525 } else { 2526 mCustomResolverComponentName = ComponentName.unflattenFromString( 2527 customResolverActivity); 2528 } 2529 2530 long startTime = SystemClock.uptimeMillis(); 2531 2532 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2533 startTime); 2534 2535 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2536 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2537 2538 if (bootClassPath == null) { 2539 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2540 } 2541 2542 if (systemServerClassPath == null) { 2543 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2544 } 2545 2546 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2547 2548 final VersionInfo ver = mSettings.getInternalVersion(); 2549 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2550 if (mIsUpgrade) { 2551 logCriticalInfo(Log.INFO, 2552 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2553 } 2554 2555 // when upgrading from pre-M, promote system app permissions from install to runtime 2556 mPromoteSystemApps = 2557 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2558 2559 // When upgrading from pre-N, we need to handle package extraction like first boot, 2560 // as there is no profiling data available. 2561 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2562 2563 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2564 2565 // save off the names of pre-existing system packages prior to scanning; we don't 2566 // want to automatically grant runtime permissions for new system apps 2567 if (mPromoteSystemApps) { 2568 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2569 while (pkgSettingIter.hasNext()) { 2570 PackageSetting ps = pkgSettingIter.next(); 2571 if (isSystemApp(ps)) { 2572 mExistingSystemPackages.add(ps.name); 2573 } 2574 } 2575 } 2576 2577 mCacheDir = preparePackageParserCache(mIsUpgrade); 2578 2579 // Set flag to monitor and not change apk file paths when 2580 // scanning install directories. 2581 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2582 2583 if (mIsUpgrade || mFirstBoot) { 2584 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2585 } 2586 2587 // Collect vendor/product overlay packages. (Do this before scanning any apps.) 2588 // For security and version matching reason, only consider 2589 // overlay packages if they reside in the right directory. 2590 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), 2591 mDefParseFlags 2592 | PackageParser.PARSE_IS_SYSTEM_DIR, 2593 scanFlags 2594 | SCAN_AS_SYSTEM 2595 | SCAN_AS_VENDOR, 2596 0); 2597 scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR), 2598 mDefParseFlags 2599 | PackageParser.PARSE_IS_SYSTEM_DIR, 2600 scanFlags 2601 | SCAN_AS_SYSTEM 2602 | SCAN_AS_PRODUCT, 2603 0); 2604 2605 mParallelPackageParserCallback.findStaticOverlayPackages(); 2606 2607 // Find base frameworks (resource packages without code). 2608 scanDirTracedLI(frameworkDir, 2609 mDefParseFlags 2610 | PackageParser.PARSE_IS_SYSTEM_DIR, 2611 scanFlags 2612 | SCAN_NO_DEX 2613 | SCAN_AS_SYSTEM 2614 | SCAN_AS_PRIVILEGED, 2615 0); 2616 2617 // Collect privileged system packages. 2618 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2619 scanDirTracedLI(privilegedAppDir, 2620 mDefParseFlags 2621 | PackageParser.PARSE_IS_SYSTEM_DIR, 2622 scanFlags 2623 | SCAN_AS_SYSTEM 2624 | SCAN_AS_PRIVILEGED, 2625 0); 2626 2627 // Collect ordinary system packages. 2628 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2629 scanDirTracedLI(systemAppDir, 2630 mDefParseFlags 2631 | PackageParser.PARSE_IS_SYSTEM_DIR, 2632 scanFlags 2633 | SCAN_AS_SYSTEM, 2634 0); 2635 2636 // Collect privileged vendor packages. 2637 File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 2638 try { 2639 privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile(); 2640 } catch (IOException e) { 2641 // failed to look up canonical path, continue with original one 2642 } 2643 scanDirTracedLI(privilegedVendorAppDir, 2644 mDefParseFlags 2645 | PackageParser.PARSE_IS_SYSTEM_DIR, 2646 scanFlags 2647 | SCAN_AS_SYSTEM 2648 | SCAN_AS_VENDOR 2649 | SCAN_AS_PRIVILEGED, 2650 0); 2651 2652 // Collect ordinary vendor packages. 2653 File vendorAppDir = new File(Environment.getVendorDirectory(), "app"); 2654 try { 2655 vendorAppDir = vendorAppDir.getCanonicalFile(); 2656 } catch (IOException e) { 2657 // failed to look up canonical path, continue with original one 2658 } 2659 scanDirTracedLI(vendorAppDir, 2660 mDefParseFlags 2661 | PackageParser.PARSE_IS_SYSTEM_DIR, 2662 scanFlags 2663 | SCAN_AS_SYSTEM 2664 | SCAN_AS_VENDOR, 2665 0); 2666 2667 // Collect privileged odm packages. /odm is another vendor partition 2668 // other than /vendor. 2669 File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), 2670 "priv-app"); 2671 try { 2672 privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile(); 2673 } catch (IOException e) { 2674 // failed to look up canonical path, continue with original one 2675 } 2676 scanDirTracedLI(privilegedOdmAppDir, 2677 mDefParseFlags 2678 | PackageParser.PARSE_IS_SYSTEM_DIR, 2679 scanFlags 2680 | SCAN_AS_SYSTEM 2681 | SCAN_AS_VENDOR 2682 | SCAN_AS_PRIVILEGED, 2683 0); 2684 2685 // Collect ordinary odm packages. /odm is another vendor partition 2686 // other than /vendor. 2687 File odmAppDir = new File(Environment.getOdmDirectory(), "app"); 2688 try { 2689 odmAppDir = odmAppDir.getCanonicalFile(); 2690 } catch (IOException e) { 2691 // failed to look up canonical path, continue with original one 2692 } 2693 scanDirTracedLI(odmAppDir, 2694 mDefParseFlags 2695 | PackageParser.PARSE_IS_SYSTEM_DIR, 2696 scanFlags 2697 | SCAN_AS_SYSTEM 2698 | SCAN_AS_VENDOR, 2699 0); 2700 2701 // Collect all OEM packages. 2702 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2703 scanDirTracedLI(oemAppDir, 2704 mDefParseFlags 2705 | PackageParser.PARSE_IS_SYSTEM_DIR, 2706 scanFlags 2707 | SCAN_AS_SYSTEM 2708 | SCAN_AS_OEM, 2709 0); 2710 2711 // Collected privileged product packages. 2712 File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 2713 try { 2714 privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile(); 2715 } catch (IOException e) { 2716 // failed to look up canonical path, continue with original one 2717 } 2718 scanDirTracedLI(privilegedProductAppDir, 2719 mDefParseFlags 2720 | PackageParser.PARSE_IS_SYSTEM_DIR, 2721 scanFlags 2722 | SCAN_AS_SYSTEM 2723 | SCAN_AS_PRODUCT 2724 | SCAN_AS_PRIVILEGED, 2725 0); 2726 2727 // Collect ordinary product packages. 2728 File productAppDir = new File(Environment.getProductDirectory(), "app"); 2729 try { 2730 productAppDir = productAppDir.getCanonicalFile(); 2731 } catch (IOException e) { 2732 // failed to look up canonical path, continue with original one 2733 } 2734 scanDirTracedLI(productAppDir, 2735 mDefParseFlags 2736 | PackageParser.PARSE_IS_SYSTEM_DIR, 2737 scanFlags 2738 | SCAN_AS_SYSTEM 2739 | SCAN_AS_PRODUCT, 2740 0); 2741 2742 // Prune any system packages that no longer exist. 2743 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>(); 2744 // Stub packages must either be replaced with full versions in the /data 2745 // partition or be disabled. 2746 final List<String> stubSystemApps = new ArrayList<>(); 2747 if (!mOnlyCore) { 2748 // do this first before mucking with mPackages for the "expecting better" case 2749 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator(); 2750 while (pkgIterator.hasNext()) { 2751 final PackageParser.Package pkg = pkgIterator.next(); 2752 if (pkg.isStub) { 2753 stubSystemApps.add(pkg.packageName); 2754 } 2755 } 2756 2757 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2758 while (psit.hasNext()) { 2759 PackageSetting ps = psit.next(); 2760 2761 /* 2762 * If this is not a system app, it can't be a 2763 * disable system app. 2764 */ 2765 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2766 continue; 2767 } 2768 2769 /* 2770 * If the package is scanned, it's not erased. 2771 */ 2772 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2773 if (scannedPkg != null) { 2774 /* 2775 * If the system app is both scanned and in the 2776 * disabled packages list, then it must have been 2777 * added via OTA. Remove it from the currently 2778 * scanned package so the previously user-installed 2779 * application can be scanned. 2780 */ 2781 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2782 logCriticalInfo(Log.WARN, 2783 "Expecting better updated system app for " + ps.name 2784 + "; removing system app. Last known" 2785 + " codePath=" + ps.codePathString 2786 + ", versionCode=" + ps.versionCode 2787 + "; scanned versionCode=" + scannedPkg.getLongVersionCode()); 2788 removePackageLI(scannedPkg, true); 2789 mExpectingBetter.put(ps.name, ps.codePath); 2790 } 2791 2792 continue; 2793 } 2794 2795 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2796 psit.remove(); 2797 logCriticalInfo(Log.WARN, "System package " + ps.name 2798 + " no longer exists; it's data will be wiped"); 2799 // Actual deletion of code and data will be handled by later 2800 // reconciliation step 2801 } else { 2802 // we still have a disabled system package, but, it still might have 2803 // been removed. check the code path still exists and check there's 2804 // still a package. the latter can happen if an OTA keeps the same 2805 // code path, but, changes the package name. 2806 final PackageSetting disabledPs = 2807 mSettings.getDisabledSystemPkgLPr(ps.name); 2808 if (disabledPs.codePath == null || !disabledPs.codePath.exists() 2809 || disabledPs.pkg == null) { 2810 possiblyDeletedUpdatedSystemApps.add(ps.name); 2811 } 2812 } 2813 } 2814 } 2815 2816 //delete tmp files 2817 deleteTempPackageFiles(); 2818 2819 final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get(); 2820 2821 // Remove any shared userIDs that have no associated packages 2822 mSettings.pruneSharedUsersLPw(); 2823 final long systemScanTime = SystemClock.uptimeMillis() - startTime; 2824 final int systemPackagesCount = mPackages.size(); 2825 Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime 2826 + " ms, packageCount: " + systemPackagesCount 2827 + " , timePerPackage: " 2828 + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount) 2829 + " , cached: " + cachedSystemApps); 2830 if (mIsUpgrade && systemPackagesCount > 0) { 2831 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time", 2832 ((int) systemScanTime) / systemPackagesCount); 2833 } 2834 if (!mOnlyCore) { 2835 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2836 SystemClock.uptimeMillis()); 2837 scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2838 2839 scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags 2840 | PackageParser.PARSE_FORWARD_LOCK, 2841 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2842 2843 // Remove disable package settings for updated system apps that were 2844 // removed via an OTA. If the update is no longer present, remove the 2845 // app completely. Otherwise, revoke their system privileges. 2846 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2847 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2848 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2849 final String msg; 2850 if (deletedPkg == null) { 2851 // should have found an update, but, we didn't; remove everything 2852 msg = "Updated system package " + deletedAppName 2853 + " no longer exists; removing its data"; 2854 // Actual deletion of code and data will be handled by later 2855 // reconciliation step 2856 } else { 2857 // found an update; revoke system privileges 2858 msg = "Updated system package + " + deletedAppName 2859 + " no longer exists; revoking system privileges"; 2860 2861 // Don't do anything if a stub is removed from the system image. If 2862 // we were to remove the uncompressed version from the /data partition, 2863 // this is where it'd be done. 2864 2865 final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2866 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2867 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2868 } 2869 logCriticalInfo(Log.WARN, msg); 2870 } 2871 2872 /* 2873 * Make sure all system apps that we expected to appear on 2874 * the userdata partition actually showed up. If they never 2875 * appeared, crawl back and revive the system version. 2876 */ 2877 for (int i = 0; i < mExpectingBetter.size(); i++) { 2878 final String packageName = mExpectingBetter.keyAt(i); 2879 if (!mPackages.containsKey(packageName)) { 2880 final File scanFile = mExpectingBetter.valueAt(i); 2881 2882 logCriticalInfo(Log.WARN, "Expected better " + packageName 2883 + " but never showed up; reverting to system"); 2884 2885 final @ParseFlags int reparseFlags; 2886 final @ScanFlags int rescanFlags; 2887 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2888 reparseFlags = 2889 mDefParseFlags | 2890 PackageParser.PARSE_IS_SYSTEM_DIR; 2891 rescanFlags = 2892 scanFlags 2893 | SCAN_AS_SYSTEM 2894 | SCAN_AS_PRIVILEGED; 2895 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2896 reparseFlags = 2897 mDefParseFlags | 2898 PackageParser.PARSE_IS_SYSTEM_DIR; 2899 rescanFlags = 2900 scanFlags 2901 | SCAN_AS_SYSTEM; 2902 } else if (FileUtils.contains(privilegedVendorAppDir, scanFile) 2903 || FileUtils.contains(privilegedOdmAppDir, scanFile)) { 2904 reparseFlags = 2905 mDefParseFlags | 2906 PackageParser.PARSE_IS_SYSTEM_DIR; 2907 rescanFlags = 2908 scanFlags 2909 | SCAN_AS_SYSTEM 2910 | SCAN_AS_VENDOR 2911 | SCAN_AS_PRIVILEGED; 2912 } else if (FileUtils.contains(vendorAppDir, scanFile) 2913 || FileUtils.contains(odmAppDir, scanFile)) { 2914 reparseFlags = 2915 mDefParseFlags | 2916 PackageParser.PARSE_IS_SYSTEM_DIR; 2917 rescanFlags = 2918 scanFlags 2919 | SCAN_AS_SYSTEM 2920 | SCAN_AS_VENDOR; 2921 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2922 reparseFlags = 2923 mDefParseFlags | 2924 PackageParser.PARSE_IS_SYSTEM_DIR; 2925 rescanFlags = 2926 scanFlags 2927 | SCAN_AS_SYSTEM 2928 | SCAN_AS_OEM; 2929 } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) { 2930 reparseFlags = 2931 mDefParseFlags | 2932 PackageParser.PARSE_IS_SYSTEM_DIR; 2933 rescanFlags = 2934 scanFlags 2935 | SCAN_AS_SYSTEM 2936 | SCAN_AS_PRODUCT 2937 | SCAN_AS_PRIVILEGED; 2938 } else if (FileUtils.contains(productAppDir, scanFile)) { 2939 reparseFlags = 2940 mDefParseFlags | 2941 PackageParser.PARSE_IS_SYSTEM_DIR; 2942 rescanFlags = 2943 scanFlags 2944 | SCAN_AS_SYSTEM 2945 | SCAN_AS_PRODUCT; 2946 } else { 2947 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2948 continue; 2949 } 2950 2951 mSettings.enableSystemPackageLPw(packageName); 2952 2953 try { 2954 scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null); 2955 } catch (PackageManagerException e) { 2956 Slog.e(TAG, "Failed to parse original system package: " 2957 + e.getMessage()); 2958 } 2959 } 2960 } 2961 2962 // Uncompress and install any stubbed system applications. 2963 // This must be done last to ensure all stubs are replaced or disabled. 2964 decompressSystemApplications(stubSystemApps, scanFlags); 2965 2966 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get() 2967 - cachedSystemApps; 2968 2969 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime; 2970 final int dataPackagesCount = mPackages.size() - systemPackagesCount; 2971 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime 2972 + " ms, packageCount: " + dataPackagesCount 2973 + " , timePerPackage: " 2974 + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) 2975 + " , cached: " + cachedNonSystemApps); 2976 if (mIsUpgrade && dataPackagesCount > 0) { 2977 MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time", 2978 ((int) dataScanTime) / dataPackagesCount); 2979 } 2980 } 2981 mExpectingBetter.clear(); 2982 2983 // Resolve the storage manager. 2984 mStorageManagerPackage = getStorageManagerPackageName(); 2985 2986 // Resolve protected action filters. Only the setup wizard is allowed to 2987 // have a high priority filter for these actions. 2988 mSetupWizardPackage = getSetupWizardPackageName(); 2989 if (mProtectedFilters.size() > 0) { 2990 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2991 Slog.i(TAG, "No setup wizard;" 2992 + " All protected intents capped to priority 0"); 2993 } 2994 for (ActivityIntentInfo filter : mProtectedFilters) { 2995 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2996 if (DEBUG_FILTERS) { 2997 Slog.i(TAG, "Found setup wizard;" 2998 + " allow priority " + filter.getPriority() + ";" 2999 + " package: " + filter.activity.info.packageName 3000 + " activity: " + filter.activity.className 3001 + " priority: " + filter.getPriority()); 3002 } 3003 // skip setup wizard; allow it to keep the high priority filter 3004 continue; 3005 } 3006 if (DEBUG_FILTERS) { 3007 Slog.i(TAG, "Protected action; cap priority to 0;" 3008 + " package: " + filter.activity.info.packageName 3009 + " activity: " + filter.activity.className 3010 + " origPrio: " + filter.getPriority()); 3011 } 3012 filter.setPriority(0); 3013 } 3014 } 3015 3016 mSystemTextClassifierPackage = getSystemTextClassifierPackageName(); 3017 3018 mDeferProtectedFilters = false; 3019 mProtectedFilters.clear(); 3020 3021 // Now that we know all of the shared libraries, update all clients to have 3022 // the correct library paths. 3023 updateAllSharedLibrariesLPw(null); 3024 3025 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 3026 // NOTE: We ignore potential failures here during a system scan (like 3027 // the rest of the commands above) because there's precious little we 3028 // can do about it. A settings error is reported, though. 3029 final List<String> changedAbiCodePath = 3030 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 3031 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 3032 for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) { 3033 final String codePathString = changedAbiCodePath.get(i); 3034 try { 3035 mInstaller.rmdex(codePathString, 3036 getDexCodeInstructionSet(getPreferredInstructionSet())); 3037 } catch (InstallerException ignored) { 3038 } 3039 } 3040 } 3041 // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same 3042 // SELinux domain. 3043 setting.fixSeInfoLocked(); 3044 } 3045 3046 // Now that we know all the packages we are keeping, 3047 // read and update their last usage times. 3048 mPackageUsage.read(mPackages); 3049 mCompilerStats.read(); 3050 3051 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 3052 SystemClock.uptimeMillis()); 3053 Slog.i(TAG, "Time to scan packages: " 3054 + ((SystemClock.uptimeMillis()-startTime)/1000f) 3055 + " seconds"); 3056 3057 // If the platform SDK has changed since the last time we booted, 3058 // we need to re-grant app permission to catch any new ones that 3059 // appear. This is really a hack, and means that apps can in some 3060 // cases get permissions that the user didn't initially explicitly 3061 // allow... it would be nice to have some better way to handle 3062 // this situation. 3063 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 3064 if (sdkUpdated) { 3065 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 3066 + mSdkVersion + "; regranting permissions for internal storage"); 3067 } 3068 mPermissionManager.updateAllPermissions( 3069 StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(), 3070 mPermissionCallback); 3071 ver.sdkVersion = mSdkVersion; 3072 3073 // If this is the first boot or an update from pre-M, and it is a normal 3074 // boot, then we need to initialize the default preferred apps across 3075 // all defined users. 3076 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 3077 for (UserInfo user : sUserManager.getUsers(true)) { 3078 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 3079 applyFactoryDefaultBrowserLPw(user.id); 3080 primeDomainVerificationsLPw(user.id); 3081 } 3082 } 3083 3084 // Prepare storage for system user really early during boot, 3085 // since core system apps like SettingsProvider and SystemUI 3086 // can't wait for user to start 3087 final int storageFlags; 3088 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3089 storageFlags = StorageManager.FLAG_STORAGE_DE; 3090 } else { 3091 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 3092 } 3093 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 3094 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 3095 true /* onlyCoreApps */); 3096 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 3097 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync", 3098 Trace.TRACE_TAG_PACKAGE_MANAGER); 3099 traceLog.traceBegin("AppDataFixup"); 3100 try { 3101 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 3102 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 3103 } catch (InstallerException e) { 3104 Slog.w(TAG, "Trouble fixing GIDs", e); 3105 } 3106 traceLog.traceEnd(); 3107 3108 traceLog.traceBegin("AppDataPrepare"); 3109 if (deferPackages == null || deferPackages.isEmpty()) { 3110 return; 3111 } 3112 int count = 0; 3113 for (String pkgName : deferPackages) { 3114 PackageParser.Package pkg = null; 3115 synchronized (mPackages) { 3116 PackageSetting ps = mSettings.getPackageLPr(pkgName); 3117 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 3118 pkg = ps.pkg; 3119 } 3120 } 3121 if (pkg != null) { 3122 synchronized (mInstallLock) { 3123 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 3124 true /* maybeMigrateAppData */); 3125 } 3126 count++; 3127 } 3128 } 3129 traceLog.traceEnd(); 3130 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 3131 }, "prepareAppData"); 3132 3133 // If this is first boot after an OTA, and a normal boot, then 3134 // we need to clear code cache directories. 3135 // Note that we do *not* clear the application profiles. These remain valid 3136 // across OTAs and are used to drive profile verification (post OTA) and 3137 // profile compilation (without waiting to collect a fresh set of profiles). 3138 if (mIsUpgrade && !onlyCore) { 3139 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 3140 for (int i = 0; i < mSettings.mPackages.size(); i++) { 3141 final PackageSetting ps = mSettings.mPackages.valueAt(i); 3142 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 3143 // No apps are running this early, so no need to freeze 3144 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 3145 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 3146 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 3147 } 3148 } 3149 ver.fingerprint = Build.FINGERPRINT; 3150 } 3151 3152 checkDefaultBrowser(); 3153 3154 // clear only after permissions and other defaults have been updated 3155 mExistingSystemPackages.clear(); 3156 mPromoteSystemApps = false; 3157 3158 // All the changes are done during package scanning. 3159 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 3160 3161 // can downgrade to reader 3162 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 3163 mSettings.writeLPr(); 3164 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3165 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 3166 SystemClock.uptimeMillis()); 3167 3168 if (!mOnlyCore) { 3169 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 3170 mRequiredInstallerPackage = getRequiredInstallerLPr(); 3171 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 3172 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 3173 if (mIntentFilterVerifierComponent != null) { 3174 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 3175 mIntentFilterVerifierComponent); 3176 } else { 3177 mIntentFilterVerifier = null; 3178 } 3179 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3180 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 3181 SharedLibraryInfo.VERSION_UNDEFINED); 3182 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3183 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 3184 SharedLibraryInfo.VERSION_UNDEFINED); 3185 } else { 3186 mRequiredVerifierPackage = null; 3187 mRequiredInstallerPackage = null; 3188 mRequiredUninstallerPackage = null; 3189 mIntentFilterVerifierComponent = null; 3190 mIntentFilterVerifier = null; 3191 mServicesSystemSharedLibraryPackageName = null; 3192 mSharedSystemSharedLibraryPackageName = null; 3193 } 3194 3195 mInstallerService = new PackageInstallerService(context, this); 3196 final Pair<ComponentName, String> instantAppResolverComponent = 3197 getInstantAppResolverLPr(); 3198 if (instantAppResolverComponent != null) { 3199 if (DEBUG_INSTANT) { 3200 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 3201 } 3202 mInstantAppResolverConnection = new InstantAppResolverConnection( 3203 mContext, instantAppResolverComponent.first, 3204 instantAppResolverComponent.second); 3205 mInstantAppResolverSettingsComponent = 3206 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 3207 } else { 3208 mInstantAppResolverConnection = null; 3209 mInstantAppResolverSettingsComponent = null; 3210 } 3211 updateInstantAppInstallerLocked(null); 3212 3213 // Read and update the usage of dex files. 3214 // Do this at the end of PM init so that all the packages have their 3215 // data directory reconciled. 3216 // At this point we know the code paths of the packages, so we can validate 3217 // the disk file and build the internal cache. 3218 // The usage file is expected to be small so loading and verifying it 3219 // should take a fairly small time compare to the other activities (e.g. package 3220 // scanning). 3221 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3222 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 3223 for (int userId : currentUserIds) { 3224 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3225 } 3226 mDexManager.load(userPackages); 3227 if (mIsUpgrade) { 3228 MetricsLogger.histogram(null, "ota_package_manager_init_time", 3229 (int) (SystemClock.uptimeMillis() - startTime)); 3230 } 3231 } // synchronized (mPackages) 3232 } // synchronized (mInstallLock) 3233 3234 // Now after opening every single application zip, make sure they 3235 // are all flushed. Not really needed, but keeps things nice and 3236 // tidy. 3237 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3238 Runtime.getRuntime().gc(); 3239 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3240 3241 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 3242 FallbackCategoryProvider.loadFallbacks(); 3243 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3244 3245 // The initial scanning above does many calls into installd while 3246 // holding the mPackages lock, but we're mostly interested in yelling 3247 // once we have a booted system. 3248 mInstaller.setWarnIfHeld(mPackages); 3249 3250 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3251 } 3252 3253 /** 3254 * Uncompress and install stub applications. 3255 * <p>In order to save space on the system partition, some applications are shipped in a 3256 * compressed form. In addition the compressed bits for the full application, the 3257 * system image contains a tiny stub comprised of only the Android manifest. 3258 * <p>During the first boot, attempt to uncompress and install the full application. If 3259 * the application can't be installed for any reason, disable the stub and prevent 3260 * uncompressing the full application during future boots. 3261 * <p>In order to forcefully attempt an installation of a full application, go to app 3262 * settings and enable the application. 3263 */ 3264 private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) { 3265 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3266 final String pkgName = stubSystemApps.get(i); 3267 // skip if the system package is already disabled 3268 if (mSettings.isDisabledSystemPackageLPr(pkgName)) { 3269 stubSystemApps.remove(i); 3270 continue; 3271 } 3272 // skip if the package isn't installed (?!); this should never happen 3273 final PackageParser.Package pkg = mPackages.get(pkgName); 3274 if (pkg == null) { 3275 stubSystemApps.remove(i); 3276 continue; 3277 } 3278 // skip if the package has been disabled by the user 3279 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3280 if (ps != null) { 3281 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM); 3282 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) { 3283 stubSystemApps.remove(i); 3284 continue; 3285 } 3286 } 3287 3288 if (DEBUG_COMPRESSION) { 3289 Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName); 3290 } 3291 3292 // uncompress the binary to its eventual destination on /data 3293 final File scanFile = decompressPackage(pkg); 3294 if (scanFile == null) { 3295 continue; 3296 } 3297 3298 // install the package to replace the stub on /system 3299 try { 3300 mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/); 3301 removePackageLI(pkg, true /*chatty*/); 3302 scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null); 3303 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 3304 UserHandle.USER_SYSTEM, "android"); 3305 stubSystemApps.remove(i); 3306 continue; 3307 } catch (PackageManagerException e) { 3308 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage()); 3309 } 3310 3311 // any failed attempt to install the package will be cleaned up later 3312 } 3313 3314 // disable any stub still left; these failed to install the full application 3315 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3316 final String pkgName = stubSystemApps.get(i); 3317 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3318 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 3319 UserHandle.USER_SYSTEM, "android"); 3320 logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName); 3321 } 3322 } 3323 3324 /** 3325 * Decompresses the given package on the system image onto 3326 * the /data partition. 3327 * @return The directory the package was decompressed into. Otherwise, {@code null}. 3328 */ 3329 private File decompressPackage(PackageParser.Package pkg) { 3330 final File[] compressedFiles = getCompressedFiles(pkg.codePath); 3331 if (compressedFiles == null || compressedFiles.length == 0) { 3332 if (DEBUG_COMPRESSION) { 3333 Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath); 3334 } 3335 return null; 3336 } 3337 final File dstCodePath = 3338 getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName); 3339 int ret = PackageManager.INSTALL_SUCCEEDED; 3340 try { 3341 Os.mkdir(dstCodePath.getAbsolutePath(), 0755); 3342 Os.chmod(dstCodePath.getAbsolutePath(), 0755); 3343 for (File srcFile : compressedFiles) { 3344 final String srcFileName = srcFile.getName(); 3345 final String dstFileName = srcFileName.substring( 3346 0, srcFileName.length() - COMPRESSED_EXTENSION.length()); 3347 final File dstFile = new File(dstCodePath, dstFileName); 3348 ret = decompressFile(srcFile, dstFile); 3349 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3350 logCriticalInfo(Log.ERROR, "Failed to decompress" 3351 + "; pkg: " + pkg.packageName 3352 + ", file: " + dstFileName); 3353 break; 3354 } 3355 } 3356 } catch (ErrnoException e) { 3357 logCriticalInfo(Log.ERROR, "Failed to decompress" 3358 + "; pkg: " + pkg.packageName 3359 + ", err: " + e.errno); 3360 } 3361 if (ret == PackageManager.INSTALL_SUCCEEDED) { 3362 final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME); 3363 NativeLibraryHelper.Handle handle = null; 3364 try { 3365 handle = NativeLibraryHelper.Handle.create(dstCodePath); 3366 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 3367 null /*abiOverride*/); 3368 } catch (IOException e) { 3369 logCriticalInfo(Log.ERROR, "Failed to extract native libraries" 3370 + "; pkg: " + pkg.packageName); 3371 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3372 } finally { 3373 IoUtils.closeQuietly(handle); 3374 } 3375 } 3376 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3377 if (dstCodePath == null || !dstCodePath.exists()) { 3378 return null; 3379 } 3380 removeCodePathLI(dstCodePath); 3381 return null; 3382 } 3383 3384 return dstCodePath; 3385 } 3386 3387 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3388 // we're only interested in updating the installer appliction when 1) it's not 3389 // already set or 2) the modified package is the installer 3390 if (mInstantAppInstallerActivity != null 3391 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3392 .equals(modifiedPackage)) { 3393 return; 3394 } 3395 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3396 } 3397 3398 private static File preparePackageParserCache(boolean isUpgrade) { 3399 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3400 return null; 3401 } 3402 3403 // Disable package parsing on eng builds to allow for faster incremental development. 3404 if (Build.IS_ENG) { 3405 return null; 3406 } 3407 3408 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3409 Slog.i(TAG, "Disabling package parser cache due to system property."); 3410 return null; 3411 } 3412 3413 // The base directory for the package parser cache lives under /data/system/. 3414 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3415 "package_cache"); 3416 if (cacheBaseDir == null) { 3417 return null; 3418 } 3419 3420 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3421 // This also serves to "GC" unused entries when the package cache version changes (which 3422 // can only happen during upgrades). 3423 if (isUpgrade) { 3424 FileUtils.deleteContents(cacheBaseDir); 3425 } 3426 3427 3428 // Return the versioned package cache directory. This is something like 3429 // "/data/system/package_cache/1" 3430 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3431 3432 if (cacheDir == null) { 3433 // Something went wrong. Attempt to delete everything and return. 3434 Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir); 3435 FileUtils.deleteContentsAndDir(cacheBaseDir); 3436 return null; 3437 } 3438 3439 // The following is a workaround to aid development on non-numbered userdebug 3440 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3441 // the system partition is newer. 3442 // 3443 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3444 // that starts with "eng." to signify that this is an engineering build and not 3445 // destined for release. 3446 if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3447 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3448 3449 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3450 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3451 // in general and should not be used for production changes. In this specific case, 3452 // we know that they will work. 3453 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3454 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3455 FileUtils.deleteContents(cacheBaseDir); 3456 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3457 } 3458 } 3459 3460 return cacheDir; 3461 } 3462 3463 @Override 3464 public boolean isFirstBoot() { 3465 // allow instant applications 3466 return mFirstBoot; 3467 } 3468 3469 @Override 3470 public boolean isOnlyCoreApps() { 3471 // allow instant applications 3472 return mOnlyCore; 3473 } 3474 3475 @Override 3476 public boolean isUpgrade() { 3477 // allow instant applications 3478 // The system property allows testing ota flow when upgraded to the same image. 3479 return mIsUpgrade || SystemProperties.getBoolean( 3480 "persist.pm.mock-upgrade", false /* default */); 3481 } 3482 3483 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3484 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3485 3486 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3487 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3488 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3489 if (matches.size() == 1) { 3490 return matches.get(0).getComponentInfo().packageName; 3491 } else if (matches.size() == 0) { 3492 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3493 return null; 3494 } 3495 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3496 } 3497 3498 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3499 synchronized (mPackages) { 3500 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3501 if (libraryEntry == null) { 3502 throw new IllegalStateException("Missing required shared library:" + name); 3503 } 3504 return libraryEntry.apk; 3505 } 3506 } 3507 3508 private @NonNull String getRequiredInstallerLPr() { 3509 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3510 intent.addCategory(Intent.CATEGORY_DEFAULT); 3511 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3512 3513 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3514 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3515 UserHandle.USER_SYSTEM); 3516 if (matches.size() == 1) { 3517 ResolveInfo resolveInfo = matches.get(0); 3518 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3519 throw new RuntimeException("The installer must be a privileged app"); 3520 } 3521 return matches.get(0).getComponentInfo().packageName; 3522 } else { 3523 throw new RuntimeException("There must be exactly one installer; found " + matches); 3524 } 3525 } 3526 3527 private @NonNull String getRequiredUninstallerLPr() { 3528 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3529 intent.addCategory(Intent.CATEGORY_DEFAULT); 3530 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3531 3532 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3533 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3534 UserHandle.USER_SYSTEM); 3535 if (resolveInfo == null || 3536 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3537 throw new RuntimeException("There must be exactly one uninstaller; found " 3538 + resolveInfo); 3539 } 3540 return resolveInfo.getComponentInfo().packageName; 3541 } 3542 3543 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3544 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3545 3546 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3547 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3548 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3549 ResolveInfo best = null; 3550 final int N = matches.size(); 3551 for (int i = 0; i < N; i++) { 3552 final ResolveInfo cur = matches.get(i); 3553 final String packageName = cur.getComponentInfo().packageName; 3554 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3555 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3556 continue; 3557 } 3558 3559 if (best == null || cur.priority > best.priority) { 3560 best = cur; 3561 } 3562 } 3563 3564 if (best != null) { 3565 return best.getComponentInfo().getComponentName(); 3566 } 3567 Slog.w(TAG, "Intent filter verifier not found"); 3568 return null; 3569 } 3570 3571 @Override 3572 public @Nullable ComponentName getInstantAppResolverComponent() { 3573 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3574 return null; 3575 } 3576 synchronized (mPackages) { 3577 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3578 if (instantAppResolver == null) { 3579 return null; 3580 } 3581 return instantAppResolver.first; 3582 } 3583 } 3584 3585 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3586 final String[] packageArray = 3587 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3588 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3589 if (DEBUG_INSTANT) { 3590 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3591 } 3592 return null; 3593 } 3594 3595 final int callingUid = Binder.getCallingUid(); 3596 final int resolveFlags = 3597 MATCH_DIRECT_BOOT_AWARE 3598 | MATCH_DIRECT_BOOT_UNAWARE 3599 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3600 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3601 final Intent resolverIntent = new Intent(actionName); 3602 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3603 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3604 final int N = resolvers.size(); 3605 if (N == 0) { 3606 if (DEBUG_INSTANT) { 3607 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3608 } 3609 return null; 3610 } 3611 3612 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3613 for (int i = 0; i < N; i++) { 3614 final ResolveInfo info = resolvers.get(i); 3615 3616 if (info.serviceInfo == null) { 3617 continue; 3618 } 3619 3620 final String packageName = info.serviceInfo.packageName; 3621 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3622 if (DEBUG_INSTANT) { 3623 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3624 + " pkg: " + packageName + ", info:" + info); 3625 } 3626 continue; 3627 } 3628 3629 if (DEBUG_INSTANT) { 3630 Slog.v(TAG, "Ephemeral resolver found;" 3631 + " pkg: " + packageName + ", info:" + info); 3632 } 3633 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3634 } 3635 if (DEBUG_INSTANT) { 3636 Slog.v(TAG, "Ephemeral resolver NOT found"); 3637 } 3638 return null; 3639 } 3640 3641 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3642 String[] orderedActions = Build.IS_ENG 3643 ? new String[]{ 3644 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST", 3645 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE} 3646 : new String[]{ 3647 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}; 3648 3649 final int resolveFlags = 3650 MATCH_DIRECT_BOOT_AWARE 3651 | MATCH_DIRECT_BOOT_UNAWARE 3652 | Intent.FLAG_IGNORE_EPHEMERAL 3653 | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0); 3654 final Intent intent = new Intent(); 3655 intent.addCategory(Intent.CATEGORY_DEFAULT); 3656 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3657 List<ResolveInfo> matches = null; 3658 for (String action : orderedActions) { 3659 intent.setAction(action); 3660 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3661 resolveFlags, UserHandle.USER_SYSTEM); 3662 if (matches.isEmpty()) { 3663 if (DEBUG_INSTANT) { 3664 Slog.d(TAG, "Instant App installer not found with " + action); 3665 } 3666 } else { 3667 break; 3668 } 3669 } 3670 Iterator<ResolveInfo> iter = matches.iterator(); 3671 while (iter.hasNext()) { 3672 final ResolveInfo rInfo = iter.next(); 3673 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3674 if (ps != null) { 3675 final PermissionsState permissionsState = ps.getPermissionsState(); 3676 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0) 3677 || Build.IS_ENG) { 3678 continue; 3679 } 3680 } 3681 iter.remove(); 3682 } 3683 if (matches.size() == 0) { 3684 return null; 3685 } else if (matches.size() == 1) { 3686 return (ActivityInfo) matches.get(0).getComponentInfo(); 3687 } else { 3688 throw new RuntimeException( 3689 "There must be at most one ephemeral installer; found " + matches); 3690 } 3691 } 3692 3693 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3694 @NonNull ComponentName resolver) { 3695 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3696 .addCategory(Intent.CATEGORY_DEFAULT) 3697 .setPackage(resolver.getPackageName()); 3698 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3699 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3700 UserHandle.USER_SYSTEM); 3701 if (matches.isEmpty()) { 3702 return null; 3703 } 3704 return matches.get(0).getComponentInfo().getComponentName(); 3705 } 3706 3707 private void primeDomainVerificationsLPw(int userId) { 3708 if (DEBUG_DOMAIN_VERIFICATION) { 3709 Slog.d(TAG, "Priming domain verifications in user " + userId); 3710 } 3711 3712 SystemConfig systemConfig = SystemConfig.getInstance(); 3713 ArraySet<String> packages = systemConfig.getLinkedApps(); 3714 3715 for (String packageName : packages) { 3716 PackageParser.Package pkg = mPackages.get(packageName); 3717 if (pkg != null) { 3718 if (!pkg.isSystem()) { 3719 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3720 continue; 3721 } 3722 3723 ArraySet<String> domains = null; 3724 for (PackageParser.Activity a : pkg.activities) { 3725 for (ActivityIntentInfo filter : a.intents) { 3726 if (hasValidDomains(filter)) { 3727 if (domains == null) { 3728 domains = new ArraySet<String>(); 3729 } 3730 domains.addAll(filter.getHostsList()); 3731 } 3732 } 3733 } 3734 3735 if (domains != null && domains.size() > 0) { 3736 if (DEBUG_DOMAIN_VERIFICATION) { 3737 Slog.v(TAG, " + " + packageName); 3738 } 3739 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3740 // state w.r.t. the formal app-linkage "no verification attempted" state; 3741 // and then 'always' in the per-user state actually used for intent resolution. 3742 final IntentFilterVerificationInfo ivi; 3743 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3744 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3745 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3746 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3747 } else { 3748 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3749 + "' does not handle web links"); 3750 } 3751 } else { 3752 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3753 } 3754 } 3755 3756 scheduleWritePackageRestrictionsLocked(userId); 3757 scheduleWriteSettingsLocked(); 3758 } 3759 3760 private void applyFactoryDefaultBrowserLPw(int userId) { 3761 // The default browser app's package name is stored in a string resource, 3762 // with a product-specific overlay used for vendor customization. 3763 String browserPkg = mContext.getResources().getString( 3764 com.android.internal.R.string.default_browser); 3765 if (!TextUtils.isEmpty(browserPkg)) { 3766 // non-empty string => required to be a known package 3767 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3768 if (ps == null) { 3769 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3770 browserPkg = null; 3771 } else { 3772 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3773 } 3774 } 3775 3776 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3777 // default. If there's more than one, just leave everything alone. 3778 if (browserPkg == null) { 3779 calculateDefaultBrowserLPw(userId); 3780 } 3781 } 3782 3783 private void calculateDefaultBrowserLPw(int userId) { 3784 List<String> allBrowsers = resolveAllBrowserApps(userId); 3785 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3786 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3787 } 3788 3789 private List<String> resolveAllBrowserApps(int userId) { 3790 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3791 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3792 PackageManager.MATCH_ALL, userId); 3793 3794 final int count = list.size(); 3795 List<String> result = new ArrayList<String>(count); 3796 for (int i=0; i<count; i++) { 3797 ResolveInfo info = list.get(i); 3798 if (info.activityInfo == null 3799 || !info.handleAllWebDataURI 3800 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3801 || result.contains(info.activityInfo.packageName)) { 3802 continue; 3803 } 3804 result.add(info.activityInfo.packageName); 3805 } 3806 3807 return result; 3808 } 3809 3810 private boolean packageIsBrowser(String packageName, int userId) { 3811 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3812 PackageManager.MATCH_ALL, userId); 3813 final int N = list.size(); 3814 for (int i = 0; i < N; i++) { 3815 ResolveInfo info = list.get(i); 3816 if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) { 3817 return true; 3818 } 3819 } 3820 return false; 3821 } 3822 3823 private void checkDefaultBrowser() { 3824 final int myUserId = UserHandle.myUserId(); 3825 final String packageName = getDefaultBrowserPackageName(myUserId); 3826 if (packageName != null) { 3827 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3828 if (info == null) { 3829 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3830 synchronized (mPackages) { 3831 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3832 } 3833 } 3834 } 3835 } 3836 3837 @Override 3838 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3839 throws RemoteException { 3840 try { 3841 return super.onTransact(code, data, reply, flags); 3842 } catch (RuntimeException e) { 3843 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3844 Slog.wtf(TAG, "Package Manager Crash", e); 3845 } 3846 throw e; 3847 } 3848 } 3849 3850 static int[] appendInts(int[] cur, int[] add) { 3851 if (add == null) return cur; 3852 if (cur == null) return add; 3853 final int N = add.length; 3854 for (int i=0; i<N; i++) { 3855 cur = appendInt(cur, add[i]); 3856 } 3857 return cur; 3858 } 3859 3860 /** 3861 * Returns whether or not a full application can see an instant application. 3862 * <p> 3863 * Currently, there are three cases in which this can occur: 3864 * <ol> 3865 * <li>The calling application is a "special" process. Special processes 3866 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 3867 * <li>The calling application has the permission 3868 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 3869 * <li>The calling application is the default launcher on the 3870 * system partition.</li> 3871 * </ol> 3872 */ 3873 private boolean canViewInstantApps(int callingUid, int userId) { 3874 if (callingUid < Process.FIRST_APPLICATION_UID) { 3875 return true; 3876 } 3877 if (mContext.checkCallingOrSelfPermission( 3878 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3879 return true; 3880 } 3881 if (mContext.checkCallingOrSelfPermission( 3882 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3883 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3884 if (homeComponent != null 3885 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3886 return true; 3887 } 3888 } 3889 return false; 3890 } 3891 3892 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3893 if (!sUserManager.exists(userId)) return null; 3894 if (ps == null) { 3895 return null; 3896 } 3897 final int callingUid = Binder.getCallingUid(); 3898 // Filter out ephemeral app metadata: 3899 // * The system/shell/root can see metadata for any app 3900 // * An installed app can see metadata for 1) other installed apps 3901 // and 2) ephemeral apps that have explicitly interacted with it 3902 // * Ephemeral apps can only see their own data and exposed installed apps 3903 // * Holding a signature permission allows seeing instant apps 3904 if (filterAppAccessLPr(ps, callingUid, userId)) { 3905 return null; 3906 } 3907 3908 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3909 && ps.isSystem()) { 3910 flags |= MATCH_ANY_USER; 3911 } 3912 3913 final PackageUserState state = ps.readUserState(userId); 3914 PackageParser.Package p = ps.pkg; 3915 if (p != null) { 3916 final PermissionsState permissionsState = ps.getPermissionsState(); 3917 3918 // Compute GIDs only if requested 3919 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3920 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3921 // Compute granted permissions only if package has requested permissions 3922 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3923 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3924 3925 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3926 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3927 3928 if (packageInfo == null) { 3929 return null; 3930 } 3931 3932 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3933 resolveExternalPackageNameLPr(p); 3934 3935 return packageInfo; 3936 } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) { 3937 PackageInfo pi = new PackageInfo(); 3938 pi.packageName = ps.name; 3939 pi.setLongVersionCode(ps.versionCode); 3940 pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null; 3941 pi.firstInstallTime = ps.firstInstallTime; 3942 pi.lastUpdateTime = ps.lastUpdateTime; 3943 3944 ApplicationInfo ai = new ApplicationInfo(); 3945 ai.packageName = ps.name; 3946 ai.uid = UserHandle.getUid(userId, ps.appId); 3947 ai.primaryCpuAbi = ps.primaryCpuAbiString; 3948 ai.secondaryCpuAbi = ps.secondaryCpuAbiString; 3949 ai.setVersionCode(ps.versionCode); 3950 ai.flags = ps.pkgFlags; 3951 ai.privateFlags = ps.pkgPrivateFlags; 3952 pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId); 3953 3954 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for [" 3955 + ps.name + "]. Provides a minimum info."); 3956 return pi; 3957 } else { 3958 return null; 3959 } 3960 } 3961 3962 @Override 3963 public void checkPackageStartable(String packageName, int userId) { 3964 final int callingUid = Binder.getCallingUid(); 3965 if (getInstantAppPackageName(callingUid) != null) { 3966 throw new SecurityException("Instant applications don't have access to this method"); 3967 } 3968 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3969 synchronized (mPackages) { 3970 final PackageSetting ps = mSettings.mPackages.get(packageName); 3971 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 3972 throw new SecurityException("Package " + packageName + " was not found!"); 3973 } 3974 3975 if (!ps.getInstalled(userId)) { 3976 throw new SecurityException( 3977 "Package " + packageName + " was not installed for user " + userId + "!"); 3978 } 3979 3980 if (mSafeMode && !ps.isSystem()) { 3981 throw new SecurityException("Package " + packageName + " not a system app!"); 3982 } 3983 3984 if (mFrozenPackages.contains(packageName)) { 3985 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3986 } 3987 3988 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) { 3989 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3990 } 3991 } 3992 } 3993 3994 @Override 3995 public boolean isPackageAvailable(String packageName, int userId) { 3996 if (!sUserManager.exists(userId)) return false; 3997 final int callingUid = Binder.getCallingUid(); 3998 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 3999 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 4000 synchronized (mPackages) { 4001 PackageParser.Package p = mPackages.get(packageName); 4002 if (p != null) { 4003 final PackageSetting ps = (PackageSetting) p.mExtras; 4004 if (filterAppAccessLPr(ps, callingUid, userId)) { 4005 return false; 4006 } 4007 if (ps != null) { 4008 final PackageUserState state = ps.readUserState(userId); 4009 if (state != null) { 4010 return PackageParser.isAvailable(state); 4011 } 4012 } 4013 } 4014 } 4015 return false; 4016 } 4017 4018 @Override 4019 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 4020 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 4021 flags, Binder.getCallingUid(), userId); 4022 } 4023 4024 @Override 4025 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 4026 int flags, int userId) { 4027 return getPackageInfoInternal(versionedPackage.getPackageName(), 4028 versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId); 4029 } 4030 4031 /** 4032 * Important: The provided filterCallingUid is used exclusively to filter out packages 4033 * that can be seen based on user state. It's typically the original caller uid prior 4034 * to clearing. Because it can only be provided by trusted code, it's value can be 4035 * trusted and will be used as-is; unlike userId which will be validated by this method. 4036 */ 4037 private PackageInfo getPackageInfoInternal(String packageName, long versionCode, 4038 int flags, int filterCallingUid, int userId) { 4039 if (!sUserManager.exists(userId)) return null; 4040 flags = updateFlagsForPackage(flags, userId, packageName); 4041 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4042 false /* requireFullPermission */, false /* checkShell */, "get package info"); 4043 4044 // reader 4045 synchronized (mPackages) { 4046 // Normalize package name to handle renamed packages and static libs 4047 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 4048 4049 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 4050 if (matchFactoryOnly) { 4051 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 4052 if (ps != null) { 4053 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4054 return null; 4055 } 4056 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4057 return null; 4058 } 4059 return generatePackageInfo(ps, flags, userId); 4060 } 4061 } 4062 4063 PackageParser.Package p = mPackages.get(packageName); 4064 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 4065 return null; 4066 } 4067 if (DEBUG_PACKAGE_INFO) 4068 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 4069 if (p != null) { 4070 final PackageSetting ps = (PackageSetting) p.mExtras; 4071 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4072 return null; 4073 } 4074 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 4075 return null; 4076 } 4077 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 4078 } 4079 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 4080 final PackageSetting ps = mSettings.mPackages.get(packageName); 4081 if (ps == null) return null; 4082 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4083 return null; 4084 } 4085 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4086 return null; 4087 } 4088 return generatePackageInfo(ps, flags, userId); 4089 } 4090 } 4091 return null; 4092 } 4093 4094 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 4095 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 4096 return true; 4097 } 4098 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 4099 return true; 4100 } 4101 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 4102 return true; 4103 } 4104 return false; 4105 } 4106 4107 private boolean isComponentVisibleToInstantApp( 4108 @Nullable ComponentName component, @ComponentType int type) { 4109 if (type == TYPE_ACTIVITY) { 4110 final PackageParser.Activity activity = mActivities.mActivities.get(component); 4111 if (activity == null) { 4112 return false; 4113 } 4114 final boolean visibleToInstantApp = 4115 (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 4116 final boolean explicitlyVisibleToInstantApp = 4117 (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 4118 return visibleToInstantApp && explicitlyVisibleToInstantApp; 4119 } else if (type == TYPE_RECEIVER) { 4120 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 4121 if (activity == null) { 4122 return false; 4123 } 4124 final boolean visibleToInstantApp = 4125 (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 4126 final boolean explicitlyVisibleToInstantApp = 4127 (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 4128 return visibleToInstantApp && !explicitlyVisibleToInstantApp; 4129 } else if (type == TYPE_SERVICE) { 4130 final PackageParser.Service service = mServices.mServices.get(component); 4131 return service != null 4132 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4133 : false; 4134 } else if (type == TYPE_PROVIDER) { 4135 final PackageParser.Provider provider = mProviders.mProviders.get(component); 4136 return provider != null 4137 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4138 : false; 4139 } else if (type == TYPE_UNKNOWN) { 4140 return isComponentVisibleToInstantApp(component); 4141 } 4142 return false; 4143 } 4144 4145 /** 4146 * Returns whether or not access to the application should be filtered. 4147 * <p> 4148 * Access may be limited based upon whether the calling or target applications 4149 * are instant applications. 4150 * 4151 * @see #canAccessInstantApps(int) 4152 */ 4153 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 4154 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 4155 // if we're in an isolated process, get the real calling UID 4156 if (Process.isIsolated(callingUid)) { 4157 callingUid = mIsolatedOwners.get(callingUid); 4158 } 4159 final String instantAppPkgName = getInstantAppPackageName(callingUid); 4160 final boolean callerIsInstantApp = instantAppPkgName != null; 4161 if (ps == null) { 4162 if (callerIsInstantApp) { 4163 // pretend the application exists, but, needs to be filtered 4164 return true; 4165 } 4166 return false; 4167 } 4168 // if the target and caller are the same application, don't filter 4169 if (isCallerSameApp(ps.name, callingUid)) { 4170 return false; 4171 } 4172 if (callerIsInstantApp) { 4173 // both caller and target are both instant, but, different applications, filter 4174 if (ps.getInstantApp(userId)) { 4175 return true; 4176 } 4177 // request for a specific component; if it hasn't been explicitly exposed through 4178 // property or instrumentation target, filter 4179 if (component != null) { 4180 final PackageParser.Instrumentation instrumentation = 4181 mInstrumentation.get(component); 4182 if (instrumentation != null 4183 && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) { 4184 return false; 4185 } 4186 return !isComponentVisibleToInstantApp(component, componentType); 4187 } 4188 // request for application; if no components have been explicitly exposed, filter 4189 return !ps.pkg.visibleToInstantApps; 4190 } 4191 if (ps.getInstantApp(userId)) { 4192 // caller can see all components of all instant applications, don't filter 4193 if (canViewInstantApps(callingUid, userId)) { 4194 return false; 4195 } 4196 // request for a specific instant application component, filter 4197 if (component != null) { 4198 return true; 4199 } 4200 // request for an instant application; if the caller hasn't been granted access, filter 4201 return !mInstantAppRegistry.isInstantAccessGranted( 4202 userId, UserHandle.getAppId(callingUid), ps.appId); 4203 } 4204 return false; 4205 } 4206 4207 /** 4208 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 4209 */ 4210 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 4211 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 4212 } 4213 4214 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 4215 int flags) { 4216 // Callers can access only the libs they depend on, otherwise they need to explicitly 4217 // ask for the shared libraries given the caller is allowed to access all static libs. 4218 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 4219 // System/shell/root get to see all static libs 4220 final int appId = UserHandle.getAppId(uid); 4221 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 4222 || appId == Process.ROOT_UID) { 4223 return false; 4224 } 4225 } 4226 4227 // No package means no static lib as it is always on internal storage 4228 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4229 return false; 4230 } 4231 4232 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 4233 ps.pkg.staticSharedLibVersion); 4234 if (libEntry == null) { 4235 return false; 4236 } 4237 4238 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 4239 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 4240 if (uidPackageNames == null) { 4241 return true; 4242 } 4243 4244 for (String uidPackageName : uidPackageNames) { 4245 if (ps.name.equals(uidPackageName)) { 4246 return false; 4247 } 4248 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 4249 if (uidPs != null) { 4250 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 4251 libEntry.info.getName()); 4252 if (index < 0) { 4253 continue; 4254 } 4255 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) { 4256 return false; 4257 } 4258 } 4259 } 4260 return true; 4261 } 4262 4263 @Override 4264 public String[] currentToCanonicalPackageNames(String[] names) { 4265 final int callingUid = Binder.getCallingUid(); 4266 if (getInstantAppPackageName(callingUid) != null) { 4267 return names; 4268 } 4269 final String[] out = new String[names.length]; 4270 // reader 4271 synchronized (mPackages) { 4272 final int callingUserId = UserHandle.getUserId(callingUid); 4273 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4274 for (int i=names.length-1; i>=0; i--) { 4275 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4276 boolean translateName = false; 4277 if (ps != null && ps.realName != null) { 4278 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 4279 translateName = !targetIsInstantApp 4280 || canViewInstantApps 4281 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4282 UserHandle.getAppId(callingUid), ps.appId); 4283 } 4284 out[i] = translateName ? ps.realName : names[i]; 4285 } 4286 } 4287 return out; 4288 } 4289 4290 @Override 4291 public String[] canonicalToCurrentPackageNames(String[] names) { 4292 final int callingUid = Binder.getCallingUid(); 4293 if (getInstantAppPackageName(callingUid) != null) { 4294 return names; 4295 } 4296 final String[] out = new String[names.length]; 4297 // reader 4298 synchronized (mPackages) { 4299 final int callingUserId = UserHandle.getUserId(callingUid); 4300 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4301 for (int i=names.length-1; i>=0; i--) { 4302 final String cur = mSettings.getRenamedPackageLPr(names[i]); 4303 boolean translateName = false; 4304 if (cur != null) { 4305 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4306 final boolean targetIsInstantApp = 4307 ps != null && ps.getInstantApp(callingUserId); 4308 translateName = !targetIsInstantApp 4309 || canViewInstantApps 4310 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4311 UserHandle.getAppId(callingUid), ps.appId); 4312 } 4313 out[i] = translateName ? cur : names[i]; 4314 } 4315 } 4316 return out; 4317 } 4318 4319 @Override 4320 public int getPackageUid(String packageName, int flags, int userId) { 4321 if (!sUserManager.exists(userId)) return -1; 4322 final int callingUid = Binder.getCallingUid(); 4323 flags = updateFlagsForPackage(flags, userId, packageName); 4324 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4325 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 4326 4327 // reader 4328 synchronized (mPackages) { 4329 final PackageParser.Package p = mPackages.get(packageName); 4330 if (p != null && p.isMatch(flags)) { 4331 PackageSetting ps = (PackageSetting) p.mExtras; 4332 if (filterAppAccessLPr(ps, callingUid, userId)) { 4333 return -1; 4334 } 4335 return UserHandle.getUid(userId, p.applicationInfo.uid); 4336 } 4337 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4338 final PackageSetting ps = mSettings.mPackages.get(packageName); 4339 if (ps != null && ps.isMatch(flags) 4340 && !filterAppAccessLPr(ps, callingUid, userId)) { 4341 return UserHandle.getUid(userId, ps.appId); 4342 } 4343 } 4344 } 4345 4346 return -1; 4347 } 4348 4349 @Override 4350 public int[] getPackageGids(String packageName, int flags, int userId) { 4351 if (!sUserManager.exists(userId)) return null; 4352 final int callingUid = Binder.getCallingUid(); 4353 flags = updateFlagsForPackage(flags, userId, packageName); 4354 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4355 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 4356 4357 // reader 4358 synchronized (mPackages) { 4359 final PackageParser.Package p = mPackages.get(packageName); 4360 if (p != null && p.isMatch(flags)) { 4361 PackageSetting ps = (PackageSetting) p.mExtras; 4362 if (filterAppAccessLPr(ps, callingUid, userId)) { 4363 return null; 4364 } 4365 // TODO: Shouldn't this be checking for package installed state for userId and 4366 // return null? 4367 return ps.getPermissionsState().computeGids(userId); 4368 } 4369 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4370 final PackageSetting ps = mSettings.mPackages.get(packageName); 4371 if (ps != null && ps.isMatch(flags) 4372 && !filterAppAccessLPr(ps, callingUid, userId)) { 4373 return ps.getPermissionsState().computeGids(userId); 4374 } 4375 } 4376 } 4377 4378 return null; 4379 } 4380 4381 @Override 4382 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4383 return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid()); 4384 } 4385 4386 @Override 4387 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName, 4388 int flags) { 4389 final List<PermissionInfo> permissionList = 4390 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()); 4391 return (permissionList == null) ? null : new ParceledListSlice<>(permissionList); 4392 } 4393 4394 @Override 4395 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) { 4396 return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid()); 4397 } 4398 4399 @Override 4400 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4401 final List<PermissionGroupInfo> permissionList = 4402 mPermissionManager.getAllPermissionGroups(flags, getCallingUid()); 4403 return (permissionList == null) 4404 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList); 4405 } 4406 4407 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4408 int filterCallingUid, int userId) { 4409 if (!sUserManager.exists(userId)) return null; 4410 PackageSetting ps = mSettings.mPackages.get(packageName); 4411 if (ps != null) { 4412 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4413 return null; 4414 } 4415 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4416 return null; 4417 } 4418 if (ps.pkg == null) { 4419 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4420 if (pInfo != null) { 4421 return pInfo.applicationInfo; 4422 } 4423 return null; 4424 } 4425 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4426 ps.readUserState(userId), userId); 4427 if (ai != null) { 4428 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4429 } 4430 return ai; 4431 } 4432 return null; 4433 } 4434 4435 @Override 4436 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4437 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4438 } 4439 4440 /** 4441 * Important: The provided filterCallingUid is used exclusively to filter out applications 4442 * that can be seen based on user state. It's typically the original caller uid prior 4443 * to clearing. Because it can only be provided by trusted code, it's value can be 4444 * trusted and will be used as-is; unlike userId which will be validated by this method. 4445 */ 4446 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4447 int filterCallingUid, int userId) { 4448 if (!sUserManager.exists(userId)) return null; 4449 flags = updateFlagsForApplication(flags, userId, packageName); 4450 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4451 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4452 4453 // writer 4454 synchronized (mPackages) { 4455 // Normalize package name to handle renamed packages and static libs 4456 packageName = resolveInternalPackageNameLPr(packageName, 4457 PackageManager.VERSION_CODE_HIGHEST); 4458 4459 PackageParser.Package p = mPackages.get(packageName); 4460 if (DEBUG_PACKAGE_INFO) Log.v( 4461 TAG, "getApplicationInfo " + packageName 4462 + ": " + p); 4463 if (p != null) { 4464 PackageSetting ps = mSettings.mPackages.get(packageName); 4465 if (ps == null) return null; 4466 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4467 return null; 4468 } 4469 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4470 return null; 4471 } 4472 // Note: isEnabledLP() does not apply here - always return info 4473 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4474 p, flags, ps.readUserState(userId), userId); 4475 if (ai != null) { 4476 ai.packageName = resolveExternalPackageNameLPr(p); 4477 } 4478 return ai; 4479 } 4480 if ("android".equals(packageName)||"system".equals(packageName)) { 4481 return mAndroidApplication; 4482 } 4483 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4484 // Already generates the external package name 4485 return generateApplicationInfoFromSettingsLPw(packageName, 4486 flags, filterCallingUid, userId); 4487 } 4488 } 4489 return null; 4490 } 4491 4492 private String normalizePackageNameLPr(String packageName) { 4493 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4494 return normalizedPackageName != null ? normalizedPackageName : packageName; 4495 } 4496 4497 @Override 4498 public void deletePreloadsFileCache() { 4499 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4500 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4501 } 4502 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4503 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4504 FileUtils.deleteContents(dir); 4505 } 4506 4507 @Override 4508 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4509 final int storageFlags, final IPackageDataObserver observer) { 4510 mContext.enforceCallingOrSelfPermission( 4511 android.Manifest.permission.CLEAR_APP_CACHE, null); 4512 mHandler.post(() -> { 4513 boolean success = false; 4514 try { 4515 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4516 success = true; 4517 } catch (IOException e) { 4518 Slog.w(TAG, e); 4519 } 4520 if (observer != null) { 4521 try { 4522 observer.onRemoveCompleted(null, success); 4523 } catch (RemoteException e) { 4524 Slog.w(TAG, e); 4525 } 4526 } 4527 }); 4528 } 4529 4530 @Override 4531 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4532 final int storageFlags, final IntentSender pi) { 4533 mContext.enforceCallingOrSelfPermission( 4534 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4535 mHandler.post(() -> { 4536 boolean success = false; 4537 try { 4538 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4539 success = true; 4540 } catch (IOException e) { 4541 Slog.w(TAG, e); 4542 } 4543 if (pi != null) { 4544 try { 4545 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4546 } catch (SendIntentException e) { 4547 Slog.w(TAG, e); 4548 } 4549 } 4550 }); 4551 } 4552 4553 /** 4554 * Blocking call to clear various types of cached data across the system 4555 * until the requested bytes are available. 4556 */ 4557 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4558 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4559 final File file = storage.findPathForUuid(volumeUuid); 4560 if (file.getUsableSpace() >= bytes) return; 4561 4562 if (ENABLE_FREE_CACHE_V2) { 4563 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4564 volumeUuid); 4565 final boolean aggressive = (storageFlags 4566 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4567 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags); 4568 4569 // 1. Pre-flight to determine if we have any chance to succeed 4570 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4571 if (internalVolume && (aggressive || SystemProperties 4572 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4573 deletePreloadsFileCache(); 4574 if (file.getUsableSpace() >= bytes) return; 4575 } 4576 4577 // 3. Consider parsed APK data (aggressive only) 4578 if (internalVolume && aggressive) { 4579 FileUtils.deleteContents(mCacheDir); 4580 if (file.getUsableSpace() >= bytes) return; 4581 } 4582 4583 // 4. Consider cached app data (above quotas) 4584 try { 4585 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4586 Installer.FLAG_FREE_CACHE_V2); 4587 } catch (InstallerException ignored) { 4588 } 4589 if (file.getUsableSpace() >= bytes) return; 4590 4591 // 5. Consider shared libraries with refcount=0 and age>min cache period 4592 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4593 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4594 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4595 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4596 return; 4597 } 4598 4599 // 6. Consider dexopt output (aggressive only) 4600 // TODO: Implement 4601 4602 // 7. Consider installed instant apps unused longer than min cache period 4603 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4604 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4605 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4606 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4607 return; 4608 } 4609 4610 // 8. Consider cached app data (below quotas) 4611 try { 4612 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4613 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4614 } catch (InstallerException ignored) { 4615 } 4616 if (file.getUsableSpace() >= bytes) return; 4617 4618 // 9. Consider DropBox entries 4619 // TODO: Implement 4620 4621 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4622 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4623 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4624 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4625 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4626 return; 4627 } 4628 } else { 4629 try { 4630 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4631 } catch (InstallerException ignored) { 4632 } 4633 if (file.getUsableSpace() >= bytes) return; 4634 } 4635 4636 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4637 } 4638 4639 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4640 throws IOException { 4641 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4642 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4643 4644 List<VersionedPackage> packagesToDelete = null; 4645 final long now = System.currentTimeMillis(); 4646 4647 synchronized (mPackages) { 4648 final int[] allUsers = sUserManager.getUserIds(); 4649 final int libCount = mSharedLibraries.size(); 4650 for (int i = 0; i < libCount; i++) { 4651 final LongSparseArray<SharedLibraryEntry> versionedLib 4652 = mSharedLibraries.valueAt(i); 4653 if (versionedLib == null) { 4654 continue; 4655 } 4656 final int versionCount = versionedLib.size(); 4657 for (int j = 0; j < versionCount; j++) { 4658 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4659 // Skip packages that are not static shared libs. 4660 if (!libInfo.isStatic()) { 4661 break; 4662 } 4663 // Important: We skip static shared libs used for some user since 4664 // in such a case we need to keep the APK on the device. The check for 4665 // a lib being used for any user is performed by the uninstall call. 4666 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4667 // Resolve the package name - we use synthetic package names internally 4668 final String internalPackageName = resolveInternalPackageNameLPr( 4669 declaringPackage.getPackageName(), 4670 declaringPackage.getLongVersionCode()); 4671 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4672 // Skip unused static shared libs cached less than the min period 4673 // to prevent pruning a lib needed by a subsequently installed package. 4674 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4675 continue; 4676 } 4677 if (packagesToDelete == null) { 4678 packagesToDelete = new ArrayList<>(); 4679 } 4680 packagesToDelete.add(new VersionedPackage(internalPackageName, 4681 declaringPackage.getLongVersionCode())); 4682 } 4683 } 4684 } 4685 4686 if (packagesToDelete != null) { 4687 final int packageCount = packagesToDelete.size(); 4688 for (int i = 0; i < packageCount; i++) { 4689 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4690 // Delete the package synchronously (will fail of the lib used for any user). 4691 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(), 4692 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4693 == PackageManager.DELETE_SUCCEEDED) { 4694 if (volume.getUsableSpace() >= neededSpace) { 4695 return true; 4696 } 4697 } 4698 } 4699 } 4700 4701 return false; 4702 } 4703 4704 /** 4705 * Update given flags based on encryption status of current user. 4706 */ 4707 private int updateFlags(int flags, int userId) { 4708 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4709 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4710 // Caller expressed an explicit opinion about what encryption 4711 // aware/unaware components they want to see, so fall through and 4712 // give them what they want 4713 } else { 4714 // Caller expressed no opinion, so match based on user state 4715 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4716 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4717 } else { 4718 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4719 } 4720 } 4721 return flags; 4722 } 4723 4724 private UserManagerInternal getUserManagerInternal() { 4725 if (mUserManagerInternal == null) { 4726 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4727 } 4728 return mUserManagerInternal; 4729 } 4730 4731 private ActivityManagerInternal getActivityManagerInternal() { 4732 if (mActivityManagerInternal == null) { 4733 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class); 4734 } 4735 return mActivityManagerInternal; 4736 } 4737 4738 4739 private DeviceIdleController.LocalService getDeviceIdleController() { 4740 if (mDeviceIdleController == null) { 4741 mDeviceIdleController = 4742 LocalServices.getService(DeviceIdleController.LocalService.class); 4743 } 4744 return mDeviceIdleController; 4745 } 4746 4747 /** 4748 * Update given flags when being used to request {@link PackageInfo}. 4749 */ 4750 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4751 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4752 boolean triaged = true; 4753 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4754 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4755 // Caller is asking for component details, so they'd better be 4756 // asking for specific encryption matching behavior, or be triaged 4757 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4758 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4759 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4760 triaged = false; 4761 } 4762 } 4763 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4764 | PackageManager.MATCH_SYSTEM_ONLY 4765 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4766 triaged = false; 4767 } 4768 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4769 mPermissionManager.enforceCrossUserPermission( 4770 Binder.getCallingUid(), userId, false, false, 4771 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4772 + Debug.getCallers(5)); 4773 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4774 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4775 // If the caller wants all packages and has a restricted profile associated with it, 4776 // then match all users. This is to make sure that launchers that need to access work 4777 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4778 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4779 flags |= PackageManager.MATCH_ANY_USER; 4780 } 4781 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4782 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4783 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4784 } 4785 return updateFlags(flags, userId); 4786 } 4787 4788 /** 4789 * Update given flags when being used to request {@link ApplicationInfo}. 4790 */ 4791 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4792 return updateFlagsForPackage(flags, userId, cookie); 4793 } 4794 4795 /** 4796 * Update given flags when being used to request {@link ComponentInfo}. 4797 */ 4798 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4799 if (cookie instanceof Intent) { 4800 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4801 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4802 } 4803 } 4804 4805 boolean triaged = true; 4806 // Caller is asking for component details, so they'd better be 4807 // asking for specific encryption matching behavior, or be triaged 4808 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4809 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4810 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4811 triaged = false; 4812 } 4813 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4814 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4815 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4816 } 4817 4818 return updateFlags(flags, userId); 4819 } 4820 4821 /** 4822 * Update given intent when being used to request {@link ResolveInfo}. 4823 */ 4824 private Intent updateIntentForResolve(Intent intent) { 4825 if (intent.getSelector() != null) { 4826 intent = intent.getSelector(); 4827 } 4828 if (DEBUG_PREFERRED) { 4829 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4830 } 4831 return intent; 4832 } 4833 4834 /** 4835 * Update given flags when being used to request {@link ResolveInfo}. 4836 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4837 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4838 * flag set. However, this flag is only honoured in three circumstances: 4839 * <ul> 4840 * <li>when called from a system process</li> 4841 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4842 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4843 * action and a {@code android.intent.category.BROWSABLE} category</li> 4844 * </ul> 4845 */ 4846 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4847 return updateFlagsForResolve(flags, userId, intent, callingUid, 4848 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4849 } 4850 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4851 boolean wantInstantApps) { 4852 return updateFlagsForResolve(flags, userId, intent, callingUid, 4853 wantInstantApps, false /*onlyExposedExplicitly*/); 4854 } 4855 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4856 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4857 // Safe mode means we shouldn't match any third-party components 4858 if (mSafeMode) { 4859 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4860 } 4861 if (getInstantAppPackageName(callingUid) != null) { 4862 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4863 if (onlyExposedExplicitly) { 4864 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4865 } 4866 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4867 flags |= PackageManager.MATCH_INSTANT; 4868 } else { 4869 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 4870 final boolean allowMatchInstant = wantInstantApps 4871 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 4872 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4873 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4874 if (!allowMatchInstant) { 4875 flags &= ~PackageManager.MATCH_INSTANT; 4876 } 4877 } 4878 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4879 } 4880 4881 @Override 4882 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4883 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 4884 } 4885 4886 /** 4887 * Important: The provided filterCallingUid is used exclusively to filter out activities 4888 * that can be seen based on user state. It's typically the original caller uid prior 4889 * to clearing. Because it can only be provided by trusted code, it's value can be 4890 * trusted and will be used as-is; unlike userId which will be validated by this method. 4891 */ 4892 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 4893 int filterCallingUid, int userId) { 4894 if (!sUserManager.exists(userId)) return null; 4895 flags = updateFlagsForComponent(flags, userId, component); 4896 4897 if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) { 4898 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4899 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4900 } 4901 4902 synchronized (mPackages) { 4903 PackageParser.Activity a = mActivities.mActivities.get(component); 4904 4905 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4906 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4907 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4908 if (ps == null) return null; 4909 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 4910 return null; 4911 } 4912 return PackageParser.generateActivityInfo( 4913 a, flags, ps.readUserState(userId), userId); 4914 } 4915 if (mResolveComponentName.equals(component)) { 4916 return PackageParser.generateActivityInfo( 4917 mResolveActivity, flags, new PackageUserState(), userId); 4918 } 4919 } 4920 return null; 4921 } 4922 4923 private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) { 4924 if (!getActivityManagerInternal().isCallerRecents(callingUid)) { 4925 return false; 4926 } 4927 final long token = Binder.clearCallingIdentity(); 4928 try { 4929 final int callingUserId = UserHandle.getUserId(callingUid); 4930 if (ActivityManager.getCurrentUser() != callingUserId) { 4931 return false; 4932 } 4933 return sUserManager.isSameProfileGroup(callingUserId, targetUserId); 4934 } finally { 4935 Binder.restoreCallingIdentity(token); 4936 } 4937 } 4938 4939 @Override 4940 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4941 String resolvedType) { 4942 synchronized (mPackages) { 4943 if (component.equals(mResolveComponentName)) { 4944 // The resolver supports EVERYTHING! 4945 return true; 4946 } 4947 final int callingUid = Binder.getCallingUid(); 4948 final int callingUserId = UserHandle.getUserId(callingUid); 4949 PackageParser.Activity a = mActivities.mActivities.get(component); 4950 if (a == null) { 4951 return false; 4952 } 4953 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4954 if (ps == null) { 4955 return false; 4956 } 4957 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4958 return false; 4959 } 4960 for (int i=0; i<a.intents.size(); i++) { 4961 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4962 intent.getData(), intent.getCategories(), TAG) >= 0) { 4963 return true; 4964 } 4965 } 4966 return false; 4967 } 4968 } 4969 4970 @Override 4971 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4972 if (!sUserManager.exists(userId)) return null; 4973 final int callingUid = Binder.getCallingUid(); 4974 flags = updateFlagsForComponent(flags, userId, component); 4975 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4976 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4977 synchronized (mPackages) { 4978 PackageParser.Activity a = mReceivers.mActivities.get(component); 4979 if (DEBUG_PACKAGE_INFO) Log.v( 4980 TAG, "getReceiverInfo " + component + ": " + a); 4981 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4982 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4983 if (ps == null) return null; 4984 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4985 return null; 4986 } 4987 return PackageParser.generateActivityInfo( 4988 a, flags, ps.readUserState(userId), userId); 4989 } 4990 } 4991 return null; 4992 } 4993 4994 @Override 4995 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4996 int flags, int userId) { 4997 if (!sUserManager.exists(userId)) return null; 4998 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4999 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5000 return null; 5001 } 5002 5003 flags = updateFlagsForPackage(flags, userId, null); 5004 5005 final boolean canSeeStaticLibraries = 5006 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 5007 == PERMISSION_GRANTED 5008 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 5009 == PERMISSION_GRANTED 5010 || canRequestPackageInstallsInternal(packageName, 5011 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 5012 false /* throwIfPermNotDeclared*/) 5013 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 5014 == PERMISSION_GRANTED; 5015 5016 synchronized (mPackages) { 5017 List<SharedLibraryInfo> result = null; 5018 5019 final int libCount = mSharedLibraries.size(); 5020 for (int i = 0; i < libCount; i++) { 5021 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 5022 if (versionedLib == null) { 5023 continue; 5024 } 5025 5026 final int versionCount = versionedLib.size(); 5027 for (int j = 0; j < versionCount; j++) { 5028 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 5029 if (!canSeeStaticLibraries && libInfo.isStatic()) { 5030 break; 5031 } 5032 final long identity = Binder.clearCallingIdentity(); 5033 try { 5034 PackageInfo packageInfo = getPackageInfoVersioned( 5035 libInfo.getDeclaringPackage(), flags 5036 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 5037 if (packageInfo == null) { 5038 continue; 5039 } 5040 } finally { 5041 Binder.restoreCallingIdentity(identity); 5042 } 5043 5044 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 5045 libInfo.getLongVersion(), libInfo.getType(), 5046 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 5047 flags, userId)); 5048 5049 if (result == null) { 5050 result = new ArrayList<>(); 5051 } 5052 result.add(resLibInfo); 5053 } 5054 } 5055 5056 return result != null ? new ParceledListSlice<>(result) : null; 5057 } 5058 } 5059 5060 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 5061 SharedLibraryInfo libInfo, int flags, int userId) { 5062 List<VersionedPackage> versionedPackages = null; 5063 final int packageCount = mSettings.mPackages.size(); 5064 for (int i = 0; i < packageCount; i++) { 5065 PackageSetting ps = mSettings.mPackages.valueAt(i); 5066 5067 if (ps == null) { 5068 continue; 5069 } 5070 5071 if (!ps.getUserState().get(userId).isAvailable(flags)) { 5072 continue; 5073 } 5074 5075 final String libName = libInfo.getName(); 5076 if (libInfo.isStatic()) { 5077 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 5078 if (libIdx < 0) { 5079 continue; 5080 } 5081 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) { 5082 continue; 5083 } 5084 if (versionedPackages == null) { 5085 versionedPackages = new ArrayList<>(); 5086 } 5087 // If the dependent is a static shared lib, use the public package name 5088 String dependentPackageName = ps.name; 5089 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 5090 dependentPackageName = ps.pkg.manifestPackageName; 5091 } 5092 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 5093 } else if (ps.pkg != null) { 5094 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 5095 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 5096 if (versionedPackages == null) { 5097 versionedPackages = new ArrayList<>(); 5098 } 5099 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 5100 } 5101 } 5102 } 5103 5104 return versionedPackages; 5105 } 5106 5107 @Override 5108 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 5109 if (!sUserManager.exists(userId)) return null; 5110 final int callingUid = Binder.getCallingUid(); 5111 flags = updateFlagsForComponent(flags, userId, component); 5112 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5113 false /* requireFullPermission */, false /* checkShell */, "get service info"); 5114 synchronized (mPackages) { 5115 PackageParser.Service s = mServices.mServices.get(component); 5116 if (DEBUG_PACKAGE_INFO) Log.v( 5117 TAG, "getServiceInfo " + component + ": " + s); 5118 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 5119 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5120 if (ps == null) return null; 5121 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 5122 return null; 5123 } 5124 return PackageParser.generateServiceInfo( 5125 s, flags, ps.readUserState(userId), userId); 5126 } 5127 } 5128 return null; 5129 } 5130 5131 @Override 5132 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 5133 if (!sUserManager.exists(userId)) return null; 5134 final int callingUid = Binder.getCallingUid(); 5135 flags = updateFlagsForComponent(flags, userId, component); 5136 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5137 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 5138 synchronized (mPackages) { 5139 PackageParser.Provider p = mProviders.mProviders.get(component); 5140 if (DEBUG_PACKAGE_INFO) Log.v( 5141 TAG, "getProviderInfo " + component + ": " + p); 5142 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 5143 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5144 if (ps == null) return null; 5145 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 5146 return null; 5147 } 5148 return PackageParser.generateProviderInfo( 5149 p, flags, ps.readUserState(userId), userId); 5150 } 5151 } 5152 return null; 5153 } 5154 5155 @Override 5156 public String[] getSystemSharedLibraryNames() { 5157 // allow instant applications 5158 synchronized (mPackages) { 5159 Set<String> libs = null; 5160 final int libCount = mSharedLibraries.size(); 5161 for (int i = 0; i < libCount; i++) { 5162 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 5163 if (versionedLib == null) { 5164 continue; 5165 } 5166 final int versionCount = versionedLib.size(); 5167 for (int j = 0; j < versionCount; j++) { 5168 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 5169 if (!libEntry.info.isStatic()) { 5170 if (libs == null) { 5171 libs = new ArraySet<>(); 5172 } 5173 libs.add(libEntry.info.getName()); 5174 break; 5175 } 5176 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 5177 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 5178 UserHandle.getUserId(Binder.getCallingUid()), 5179 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 5180 if (libs == null) { 5181 libs = new ArraySet<>(); 5182 } 5183 libs.add(libEntry.info.getName()); 5184 break; 5185 } 5186 } 5187 } 5188 5189 if (libs != null) { 5190 String[] libsArray = new String[libs.size()]; 5191 libs.toArray(libsArray); 5192 return libsArray; 5193 } 5194 5195 return null; 5196 } 5197 } 5198 5199 @Override 5200 public @NonNull String getServicesSystemSharedLibraryPackageName() { 5201 // allow instant applications 5202 synchronized (mPackages) { 5203 return mServicesSystemSharedLibraryPackageName; 5204 } 5205 } 5206 5207 @Override 5208 public @NonNull String getSharedSystemSharedLibraryPackageName() { 5209 // allow instant applications 5210 synchronized (mPackages) { 5211 return mSharedSystemSharedLibraryPackageName; 5212 } 5213 } 5214 5215 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 5216 for (int i = userList.length - 1; i >= 0; --i) { 5217 final int userId = userList[i]; 5218 // don't add instant app to the list of updates 5219 if (pkgSetting.getInstantApp(userId)) { 5220 continue; 5221 } 5222 SparseArray<String> changedPackages = mChangedPackages.get(userId); 5223 if (changedPackages == null) { 5224 changedPackages = new SparseArray<>(); 5225 mChangedPackages.put(userId, changedPackages); 5226 } 5227 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 5228 if (sequenceNumbers == null) { 5229 sequenceNumbers = new HashMap<>(); 5230 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 5231 } 5232 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 5233 if (sequenceNumber != null) { 5234 changedPackages.remove(sequenceNumber); 5235 } 5236 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 5237 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 5238 } 5239 mChangedPackagesSequenceNumber++; 5240 } 5241 5242 @Override 5243 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5244 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5245 return null; 5246 } 5247 synchronized (mPackages) { 5248 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 5249 return null; 5250 } 5251 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 5252 if (changedPackages == null) { 5253 return null; 5254 } 5255 final List<String> packageNames = 5256 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 5257 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 5258 final String packageName = changedPackages.get(i); 5259 if (packageName != null) { 5260 packageNames.add(packageName); 5261 } 5262 } 5263 return packageNames.isEmpty() 5264 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 5265 } 5266 } 5267 5268 @Override 5269 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5270 // allow instant applications 5271 ArrayList<FeatureInfo> res; 5272 synchronized (mAvailableFeatures) { 5273 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5274 res.addAll(mAvailableFeatures.values()); 5275 } 5276 final FeatureInfo fi = new FeatureInfo(); 5277 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5278 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5279 res.add(fi); 5280 5281 return new ParceledListSlice<>(res); 5282 } 5283 5284 @Override 5285 public boolean hasSystemFeature(String name, int version) { 5286 // allow instant applications 5287 synchronized (mAvailableFeatures) { 5288 final FeatureInfo feat = mAvailableFeatures.get(name); 5289 if (feat == null) { 5290 return false; 5291 } else { 5292 return feat.version >= version; 5293 } 5294 } 5295 } 5296 5297 @Override 5298 public int checkPermission(String permName, String pkgName, int userId) { 5299 return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId); 5300 } 5301 5302 @Override 5303 public int checkUidPermission(String permName, int uid) { 5304 synchronized (mPackages) { 5305 final String[] packageNames = getPackagesForUid(uid); 5306 final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0) 5307 ? mSettings.getPackageLPr(packageNames[0]).getPackage() 5308 : null; 5309 return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid()); 5310 } 5311 } 5312 5313 @Override 5314 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5315 if (UserHandle.getCallingUserId() != userId) { 5316 mContext.enforceCallingPermission( 5317 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5318 "isPermissionRevokedByPolicy for user " + userId); 5319 } 5320 5321 if (checkPermission(permission, packageName, userId) 5322 == PackageManager.PERMISSION_GRANTED) { 5323 return false; 5324 } 5325 5326 final int callingUid = Binder.getCallingUid(); 5327 if (getInstantAppPackageName(callingUid) != null) { 5328 if (!isCallerSameApp(packageName, callingUid)) { 5329 return false; 5330 } 5331 } else { 5332 if (isInstantApp(packageName, userId)) { 5333 return false; 5334 } 5335 } 5336 5337 final long identity = Binder.clearCallingIdentity(); 5338 try { 5339 final int flags = getPermissionFlags(permission, packageName, userId); 5340 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5341 } finally { 5342 Binder.restoreCallingIdentity(identity); 5343 } 5344 } 5345 5346 @Override 5347 public String getPermissionControllerPackageName() { 5348 synchronized (mPackages) { 5349 return mRequiredInstallerPackage; 5350 } 5351 } 5352 5353 private boolean addDynamicPermission(PermissionInfo info, final boolean async) { 5354 return mPermissionManager.addDynamicPermission( 5355 info, async, getCallingUid(), new PermissionCallback() { 5356 @Override 5357 public void onPermissionChanged() { 5358 if (!async) { 5359 mSettings.writeLPr(); 5360 } else { 5361 scheduleWriteSettingsLocked(); 5362 } 5363 } 5364 }); 5365 } 5366 5367 @Override 5368 public boolean addPermission(PermissionInfo info) { 5369 synchronized (mPackages) { 5370 return addDynamicPermission(info, false); 5371 } 5372 } 5373 5374 @Override 5375 public boolean addPermissionAsync(PermissionInfo info) { 5376 synchronized (mPackages) { 5377 return addDynamicPermission(info, true); 5378 } 5379 } 5380 5381 @Override 5382 public void removePermission(String permName) { 5383 mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback); 5384 } 5385 5386 @Override 5387 public void grantRuntimePermission(String packageName, String permName, final int userId) { 5388 mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/, 5389 getCallingUid(), userId, mPermissionCallback); 5390 } 5391 5392 @Override 5393 public void revokeRuntimePermission(String packageName, String permName, int userId) { 5394 mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/, 5395 getCallingUid(), userId, mPermissionCallback); 5396 } 5397 5398 @Override 5399 public void resetRuntimePermissions() { 5400 mContext.enforceCallingOrSelfPermission( 5401 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5402 "revokeRuntimePermission"); 5403 5404 int callingUid = Binder.getCallingUid(); 5405 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5406 mContext.enforceCallingOrSelfPermission( 5407 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5408 "resetRuntimePermissions"); 5409 } 5410 5411 synchronized (mPackages) { 5412 mPermissionManager.updateAllPermissions( 5413 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 5414 mPermissionCallback); 5415 for (int userId : UserManagerService.getInstance().getUserIds()) { 5416 final int packageCount = mPackages.size(); 5417 for (int i = 0; i < packageCount; i++) { 5418 PackageParser.Package pkg = mPackages.valueAt(i); 5419 if (!(pkg.mExtras instanceof PackageSetting)) { 5420 continue; 5421 } 5422 PackageSetting ps = (PackageSetting) pkg.mExtras; 5423 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5424 } 5425 } 5426 } 5427 } 5428 5429 @Override 5430 public int getPermissionFlags(String permName, String packageName, int userId) { 5431 return mPermissionManager.getPermissionFlags( 5432 permName, packageName, getCallingUid(), userId); 5433 } 5434 5435 @Override 5436 public void updatePermissionFlags(String permName, String packageName, int flagMask, 5437 int flagValues, int userId) { 5438 mPermissionManager.updatePermissionFlags( 5439 permName, packageName, flagMask, flagValues, getCallingUid(), userId, 5440 mPermissionCallback); 5441 } 5442 5443 /** 5444 * Update the permission flags for all packages and runtime permissions of a user in order 5445 * to allow device or profile owner to remove POLICY_FIXED. 5446 */ 5447 @Override 5448 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5449 synchronized (mPackages) { 5450 final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps( 5451 flagMask, flagValues, getCallingUid(), userId, mPackages.values(), 5452 mPermissionCallback); 5453 if (changed) { 5454 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5455 } 5456 } 5457 } 5458 5459 @Override 5460 public boolean shouldShowRequestPermissionRationale(String permissionName, 5461 String packageName, int userId) { 5462 if (UserHandle.getCallingUserId() != userId) { 5463 mContext.enforceCallingPermission( 5464 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5465 "canShowRequestPermissionRationale for user " + userId); 5466 } 5467 5468 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5469 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5470 return false; 5471 } 5472 5473 if (checkPermission(permissionName, packageName, userId) 5474 == PackageManager.PERMISSION_GRANTED) { 5475 return false; 5476 } 5477 5478 final int flags; 5479 5480 final long identity = Binder.clearCallingIdentity(); 5481 try { 5482 flags = getPermissionFlags(permissionName, 5483 packageName, userId); 5484 } finally { 5485 Binder.restoreCallingIdentity(identity); 5486 } 5487 5488 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5489 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5490 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5491 5492 if ((flags & fixedFlags) != 0) { 5493 return false; 5494 } 5495 5496 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5497 } 5498 5499 @Override 5500 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5501 mContext.enforceCallingOrSelfPermission( 5502 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5503 "addOnPermissionsChangeListener"); 5504 5505 synchronized (mPackages) { 5506 mOnPermissionChangeListeners.addListenerLocked(listener); 5507 } 5508 } 5509 5510 @Override 5511 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5512 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5513 throw new SecurityException("Instant applications don't have access to this method"); 5514 } 5515 synchronized (mPackages) { 5516 mOnPermissionChangeListeners.removeListenerLocked(listener); 5517 } 5518 } 5519 5520 @Override 5521 public boolean isProtectedBroadcast(String actionName) { 5522 // allow instant applications 5523 synchronized (mProtectedBroadcasts) { 5524 if (mProtectedBroadcasts.contains(actionName)) { 5525 return true; 5526 } else if (actionName != null) { 5527 // TODO: remove these terrible hacks 5528 if (actionName.startsWith("android.net.netmon.lingerExpired") 5529 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5530 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5531 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5532 return true; 5533 } 5534 } 5535 } 5536 return false; 5537 } 5538 5539 @Override 5540 public int checkSignatures(String pkg1, String pkg2) { 5541 synchronized (mPackages) { 5542 final PackageParser.Package p1 = mPackages.get(pkg1); 5543 final PackageParser.Package p2 = mPackages.get(pkg2); 5544 if (p1 == null || p1.mExtras == null 5545 || p2 == null || p2.mExtras == null) { 5546 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5547 } 5548 final int callingUid = Binder.getCallingUid(); 5549 final int callingUserId = UserHandle.getUserId(callingUid); 5550 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 5551 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 5552 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 5553 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 5554 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5555 } 5556 return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures); 5557 } 5558 } 5559 5560 @Override 5561 public int checkUidSignatures(int uid1, int uid2) { 5562 final int callingUid = Binder.getCallingUid(); 5563 final int callingUserId = UserHandle.getUserId(callingUid); 5564 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5565 // Map to base uids. 5566 uid1 = UserHandle.getAppId(uid1); 5567 uid2 = UserHandle.getAppId(uid2); 5568 // reader 5569 synchronized (mPackages) { 5570 Signature[] s1; 5571 Signature[] s2; 5572 Object obj = mSettings.getUserIdLPr(uid1); 5573 if (obj != null) { 5574 if (obj instanceof SharedUserSetting) { 5575 if (isCallerInstantApp) { 5576 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5577 } 5578 s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5579 } else if (obj instanceof PackageSetting) { 5580 final PackageSetting ps = (PackageSetting) obj; 5581 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5582 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5583 } 5584 s1 = ps.signatures.mSigningDetails.signatures; 5585 } else { 5586 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5587 } 5588 } else { 5589 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5590 } 5591 obj = mSettings.getUserIdLPr(uid2); 5592 if (obj != null) { 5593 if (obj instanceof SharedUserSetting) { 5594 if (isCallerInstantApp) { 5595 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5596 } 5597 s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5598 } else if (obj instanceof PackageSetting) { 5599 final PackageSetting ps = (PackageSetting) obj; 5600 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5601 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5602 } 5603 s2 = ps.signatures.mSigningDetails.signatures; 5604 } else { 5605 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5606 } 5607 } else { 5608 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5609 } 5610 return compareSignatures(s1, s2); 5611 } 5612 } 5613 5614 @Override 5615 public boolean hasSigningCertificate( 5616 String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) { 5617 5618 synchronized (mPackages) { 5619 final PackageParser.Package p = mPackages.get(packageName); 5620 if (p == null || p.mExtras == null) { 5621 return false; 5622 } 5623 final int callingUid = Binder.getCallingUid(); 5624 final int callingUserId = UserHandle.getUserId(callingUid); 5625 final PackageSetting ps = (PackageSetting) p.mExtras; 5626 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5627 return false; 5628 } 5629 switch (type) { 5630 case CERT_INPUT_RAW_X509: 5631 return p.mSigningDetails.hasCertificate(certificate); 5632 case CERT_INPUT_SHA256: 5633 return p.mSigningDetails.hasSha256Certificate(certificate); 5634 default: 5635 return false; 5636 } 5637 } 5638 } 5639 5640 @Override 5641 public boolean hasUidSigningCertificate( 5642 int uid, byte[] certificate, @PackageManager.CertificateInputType int type) { 5643 final int callingUid = Binder.getCallingUid(); 5644 final int callingUserId = UserHandle.getUserId(callingUid); 5645 // Map to base uids. 5646 uid = UserHandle.getAppId(uid); 5647 // reader 5648 synchronized (mPackages) { 5649 final PackageParser.SigningDetails signingDetails; 5650 final Object obj = mSettings.getUserIdLPr(uid); 5651 if (obj != null) { 5652 if (obj instanceof SharedUserSetting) { 5653 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5654 if (isCallerInstantApp) { 5655 return false; 5656 } 5657 signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails; 5658 } else if (obj instanceof PackageSetting) { 5659 final PackageSetting ps = (PackageSetting) obj; 5660 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5661 return false; 5662 } 5663 signingDetails = ps.signatures.mSigningDetails; 5664 } else { 5665 return false; 5666 } 5667 } else { 5668 return false; 5669 } 5670 switch (type) { 5671 case CERT_INPUT_RAW_X509: 5672 return signingDetails.hasCertificate(certificate); 5673 case CERT_INPUT_SHA256: 5674 return signingDetails.hasSha256Certificate(certificate); 5675 default: 5676 return false; 5677 } 5678 } 5679 } 5680 5681 /** 5682 * This method should typically only be used when granting or revoking 5683 * permissions, since the app may immediately restart after this call. 5684 * <p> 5685 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5686 * guard your work against the app being relaunched. 5687 */ 5688 private void killUid(int appId, int userId, String reason) { 5689 final long identity = Binder.clearCallingIdentity(); 5690 try { 5691 IActivityManager am = ActivityManager.getService(); 5692 if (am != null) { 5693 try { 5694 am.killUid(appId, userId, reason); 5695 } catch (RemoteException e) { 5696 /* ignore - same process */ 5697 } 5698 } 5699 } finally { 5700 Binder.restoreCallingIdentity(identity); 5701 } 5702 } 5703 5704 /** 5705 * If the database version for this type of package (internal storage or 5706 * external storage) is less than the version where package signatures 5707 * were updated, return true. 5708 */ 5709 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5710 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5711 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5712 } 5713 5714 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5715 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5716 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5717 } 5718 5719 @Override 5720 public List<String> getAllPackages() { 5721 final int callingUid = Binder.getCallingUid(); 5722 final int callingUserId = UserHandle.getUserId(callingUid); 5723 synchronized (mPackages) { 5724 if (canViewInstantApps(callingUid, callingUserId)) { 5725 return new ArrayList<String>(mPackages.keySet()); 5726 } 5727 final String instantAppPkgName = getInstantAppPackageName(callingUid); 5728 final List<String> result = new ArrayList<>(); 5729 if (instantAppPkgName != null) { 5730 // caller is an instant application; filter unexposed applications 5731 for (PackageParser.Package pkg : mPackages.values()) { 5732 if (!pkg.visibleToInstantApps) { 5733 continue; 5734 } 5735 result.add(pkg.packageName); 5736 } 5737 } else { 5738 // caller is a normal application; filter instant applications 5739 for (PackageParser.Package pkg : mPackages.values()) { 5740 final PackageSetting ps = 5741 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 5742 if (ps != null 5743 && ps.getInstantApp(callingUserId) 5744 && !mInstantAppRegistry.isInstantAccessGranted( 5745 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 5746 continue; 5747 } 5748 result.add(pkg.packageName); 5749 } 5750 } 5751 return result; 5752 } 5753 } 5754 5755 @Override 5756 public String[] getPackagesForUid(int uid) { 5757 final int callingUid = Binder.getCallingUid(); 5758 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5759 final int userId = UserHandle.getUserId(uid); 5760 uid = UserHandle.getAppId(uid); 5761 // reader 5762 synchronized (mPackages) { 5763 Object obj = mSettings.getUserIdLPr(uid); 5764 if (obj instanceof SharedUserSetting) { 5765 if (isCallerInstantApp) { 5766 return null; 5767 } 5768 final SharedUserSetting sus = (SharedUserSetting) obj; 5769 final int N = sus.packages.size(); 5770 String[] res = new String[N]; 5771 final Iterator<PackageSetting> it = sus.packages.iterator(); 5772 int i = 0; 5773 while (it.hasNext()) { 5774 PackageSetting ps = it.next(); 5775 if (ps.getInstalled(userId)) { 5776 res[i++] = ps.name; 5777 } else { 5778 res = ArrayUtils.removeElement(String.class, res, res[i]); 5779 } 5780 } 5781 return res; 5782 } else if (obj instanceof PackageSetting) { 5783 final PackageSetting ps = (PackageSetting) obj; 5784 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 5785 return new String[]{ps.name}; 5786 } 5787 } 5788 } 5789 return null; 5790 } 5791 5792 @Override 5793 public String getNameForUid(int uid) { 5794 final int callingUid = Binder.getCallingUid(); 5795 if (getInstantAppPackageName(callingUid) != null) { 5796 return null; 5797 } 5798 synchronized (mPackages) { 5799 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5800 if (obj instanceof SharedUserSetting) { 5801 final SharedUserSetting sus = (SharedUserSetting) obj; 5802 return sus.name + ":" + sus.userId; 5803 } else if (obj instanceof PackageSetting) { 5804 final PackageSetting ps = (PackageSetting) obj; 5805 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5806 return null; 5807 } 5808 return ps.name; 5809 } 5810 return null; 5811 } 5812 } 5813 5814 @Override 5815 public String[] getNamesForUids(int[] uids) { 5816 if (uids == null || uids.length == 0) { 5817 return null; 5818 } 5819 final int callingUid = Binder.getCallingUid(); 5820 if (getInstantAppPackageName(callingUid) != null) { 5821 return null; 5822 } 5823 final String[] names = new String[uids.length]; 5824 synchronized (mPackages) { 5825 for (int i = uids.length - 1; i >= 0; i--) { 5826 final int uid = uids[i]; 5827 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5828 if (obj instanceof SharedUserSetting) { 5829 final SharedUserSetting sus = (SharedUserSetting) obj; 5830 names[i] = "shared:" + sus.name; 5831 } else if (obj instanceof PackageSetting) { 5832 final PackageSetting ps = (PackageSetting) obj; 5833 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5834 names[i] = null; 5835 } else { 5836 names[i] = ps.name; 5837 } 5838 } else { 5839 names[i] = null; 5840 } 5841 } 5842 } 5843 return names; 5844 } 5845 5846 @Override 5847 public int getUidForSharedUser(String sharedUserName) { 5848 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5849 return -1; 5850 } 5851 if (sharedUserName == null) { 5852 return -1; 5853 } 5854 // reader 5855 synchronized (mPackages) { 5856 SharedUserSetting suid; 5857 try { 5858 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5859 if (suid != null) { 5860 return suid.userId; 5861 } 5862 } catch (PackageManagerException ignore) { 5863 // can't happen, but, still need to catch it 5864 } 5865 return -1; 5866 } 5867 } 5868 5869 @Override 5870 public int getFlagsForUid(int uid) { 5871 final int callingUid = Binder.getCallingUid(); 5872 if (getInstantAppPackageName(callingUid) != null) { 5873 return 0; 5874 } 5875 synchronized (mPackages) { 5876 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5877 if (obj instanceof SharedUserSetting) { 5878 final SharedUserSetting sus = (SharedUserSetting) obj; 5879 return sus.pkgFlags; 5880 } else if (obj instanceof PackageSetting) { 5881 final PackageSetting ps = (PackageSetting) obj; 5882 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5883 return 0; 5884 } 5885 return ps.pkgFlags; 5886 } 5887 } 5888 return 0; 5889 } 5890 5891 @Override 5892 public int getPrivateFlagsForUid(int uid) { 5893 final int callingUid = Binder.getCallingUid(); 5894 if (getInstantAppPackageName(callingUid) != null) { 5895 return 0; 5896 } 5897 synchronized (mPackages) { 5898 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5899 if (obj instanceof SharedUserSetting) { 5900 final SharedUserSetting sus = (SharedUserSetting) obj; 5901 return sus.pkgPrivateFlags; 5902 } else if (obj instanceof PackageSetting) { 5903 final PackageSetting ps = (PackageSetting) obj; 5904 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5905 return 0; 5906 } 5907 return ps.pkgPrivateFlags; 5908 } 5909 } 5910 return 0; 5911 } 5912 5913 @Override 5914 public boolean isUidPrivileged(int uid) { 5915 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5916 return false; 5917 } 5918 uid = UserHandle.getAppId(uid); 5919 // reader 5920 synchronized (mPackages) { 5921 Object obj = mSettings.getUserIdLPr(uid); 5922 if (obj instanceof SharedUserSetting) { 5923 final SharedUserSetting sus = (SharedUserSetting) obj; 5924 final Iterator<PackageSetting> it = sus.packages.iterator(); 5925 while (it.hasNext()) { 5926 if (it.next().isPrivileged()) { 5927 return true; 5928 } 5929 } 5930 } else if (obj instanceof PackageSetting) { 5931 final PackageSetting ps = (PackageSetting) obj; 5932 return ps.isPrivileged(); 5933 } 5934 } 5935 return false; 5936 } 5937 5938 @Override 5939 public String[] getAppOpPermissionPackages(String permName) { 5940 return mPermissionManager.getAppOpPermissionPackages(permName); 5941 } 5942 5943 @Override 5944 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5945 int flags, int userId) { 5946 return resolveIntentInternal(intent, resolvedType, flags, userId, false, 5947 Binder.getCallingUid()); 5948 } 5949 5950 /** 5951 * Normally instant apps can only be resolved when they're visible to the caller. 5952 * However, if {@code resolveForStart} is {@code true}, all instant apps are visible 5953 * since we need to allow the system to start any installed application. 5954 */ 5955 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5956 int flags, int userId, boolean resolveForStart, int filterCallingUid) { 5957 try { 5958 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5959 5960 if (!sUserManager.exists(userId)) return null; 5961 final int callingUid = Binder.getCallingUid(); 5962 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart); 5963 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5964 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5965 5966 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5967 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5968 flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/); 5969 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5970 5971 final ResolveInfo bestChoice = 5972 chooseBestActivity(intent, resolvedType, flags, query, userId); 5973 return bestChoice; 5974 } finally { 5975 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5976 } 5977 } 5978 5979 @Override 5980 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5981 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5982 throw new SecurityException( 5983 "findPersistentPreferredActivity can only be run by the system"); 5984 } 5985 if (!sUserManager.exists(userId)) { 5986 return null; 5987 } 5988 final int callingUid = Binder.getCallingUid(); 5989 intent = updateIntentForResolve(intent); 5990 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5991 final int flags = updateFlagsForResolve( 5992 0, userId, intent, callingUid, false /*includeInstantApps*/); 5993 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5994 userId); 5995 synchronized (mPackages) { 5996 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5997 userId); 5998 } 5999 } 6000 6001 @Override 6002 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 6003 IntentFilter filter, int match, ComponentName activity) { 6004 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6005 return; 6006 } 6007 final int userId = UserHandle.getCallingUserId(); 6008 if (DEBUG_PREFERRED) { 6009 Log.v(TAG, "setLastChosenActivity intent=" + intent 6010 + " resolvedType=" + resolvedType 6011 + " flags=" + flags 6012 + " filter=" + filter 6013 + " match=" + match 6014 + " activity=" + activity); 6015 filter.dump(new PrintStreamPrinter(System.out), " "); 6016 } 6017 intent.setComponent(null); 6018 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6019 userId); 6020 // Find any earlier preferred or last chosen entries and nuke them 6021 findPreferredActivity(intent, resolvedType, 6022 flags, query, 0, false, true, false, userId); 6023 // Add the new activity as the last chosen for this filter 6024 addPreferredActivityInternal(filter, match, null, activity, false, userId, 6025 "Setting last chosen"); 6026 } 6027 6028 @Override 6029 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 6030 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6031 return null; 6032 } 6033 final int userId = UserHandle.getCallingUserId(); 6034 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 6035 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6036 userId); 6037 return findPreferredActivity(intent, resolvedType, flags, query, 0, 6038 false, false, false, userId); 6039 } 6040 6041 /** 6042 * Returns whether or not instant apps have been disabled remotely. 6043 */ 6044 private boolean areWebInstantAppsDisabled() { 6045 return mWebInstantAppsDisabled; 6046 } 6047 6048 private boolean isInstantAppResolutionAllowed( 6049 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 6050 boolean skipPackageCheck) { 6051 if (mInstantAppResolverConnection == null) { 6052 return false; 6053 } 6054 if (mInstantAppInstallerActivity == null) { 6055 return false; 6056 } 6057 if (intent.getComponent() != null) { 6058 return false; 6059 } 6060 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 6061 return false; 6062 } 6063 if (!skipPackageCheck && intent.getPackage() != null) { 6064 return false; 6065 } 6066 if (!intent.isWebIntent()) { 6067 // for non web intents, we should not resolve externally if an app already exists to 6068 // handle it or if the caller didn't explicitly request it. 6069 if ((resolvedActivities != null && resolvedActivities.size() != 0) 6070 || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) { 6071 return false; 6072 } 6073 } else { 6074 if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) { 6075 return false; 6076 } else if (areWebInstantAppsDisabled()) { 6077 return false; 6078 } 6079 } 6080 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 6081 // Or if there's already an ephemeral app installed that handles the action 6082 synchronized (mPackages) { 6083 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 6084 for (int n = 0; n < count; n++) { 6085 final ResolveInfo info = resolvedActivities.get(n); 6086 final String packageName = info.activityInfo.packageName; 6087 final PackageSetting ps = mSettings.mPackages.get(packageName); 6088 if (ps != null) { 6089 // only check domain verification status if the app is not a browser 6090 if (!info.handleAllWebDataURI) { 6091 // Try to get the status from User settings first 6092 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6093 final int status = (int) (packedStatus >> 32); 6094 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 6095 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6096 if (DEBUG_INSTANT) { 6097 Slog.v(TAG, "DENY instant app;" 6098 + " pkg: " + packageName + ", status: " + status); 6099 } 6100 return false; 6101 } 6102 } 6103 if (ps.getInstantApp(userId)) { 6104 if (DEBUG_INSTANT) { 6105 Slog.v(TAG, "DENY instant app installed;" 6106 + " pkg: " + packageName); 6107 } 6108 return false; 6109 } 6110 } 6111 } 6112 } 6113 // We've exhausted all ways to deny ephemeral application; let the system look for them. 6114 return true; 6115 } 6116 6117 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 6118 Intent origIntent, String resolvedType, String callingPackage, 6119 Bundle verificationBundle, int userId) { 6120 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 6121 new InstantAppRequest(responseObj, origIntent, resolvedType, 6122 callingPackage, userId, verificationBundle, false /*resolveForStart*/)); 6123 mHandler.sendMessage(msg); 6124 } 6125 6126 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 6127 int flags, List<ResolveInfo> query, int userId) { 6128 if (query != null) { 6129 final int N = query.size(); 6130 if (N == 1) { 6131 return query.get(0); 6132 } else if (N > 1) { 6133 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 6134 // If there is more than one activity with the same priority, 6135 // then let the user decide between them. 6136 ResolveInfo r0 = query.get(0); 6137 ResolveInfo r1 = query.get(1); 6138 if (DEBUG_INTENT_MATCHING || debug) { 6139 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 6140 + r1.activityInfo.name + "=" + r1.priority); 6141 } 6142 // If the first activity has a higher priority, or a different 6143 // default, then it is always desirable to pick it. 6144 if (r0.priority != r1.priority 6145 || r0.preferredOrder != r1.preferredOrder 6146 || r0.isDefault != r1.isDefault) { 6147 return query.get(0); 6148 } 6149 // If we have saved a preference for a preferred activity for 6150 // this Intent, use that. 6151 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 6152 flags, query, r0.priority, true, false, debug, userId); 6153 if (ri != null) { 6154 return ri; 6155 } 6156 // If we have an ephemeral app, use it 6157 for (int i = 0; i < N; i++) { 6158 ri = query.get(i); 6159 if (ri.activityInfo.applicationInfo.isInstantApp()) { 6160 final String packageName = ri.activityInfo.packageName; 6161 final PackageSetting ps = mSettings.mPackages.get(packageName); 6162 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6163 final int status = (int)(packedStatus >> 32); 6164 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6165 return ri; 6166 } 6167 } 6168 } 6169 ri = new ResolveInfo(mResolveInfo); 6170 ri.activityInfo = new ActivityInfo(ri.activityInfo); 6171 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 6172 // If all of the options come from the same package, show the application's 6173 // label and icon instead of the generic resolver's. 6174 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 6175 // and then throw away the ResolveInfo itself, meaning that the caller loses 6176 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 6177 // a fallback for this case; we only set the target package's resources on 6178 // the ResolveInfo, not the ActivityInfo. 6179 final String intentPackage = intent.getPackage(); 6180 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 6181 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 6182 ri.resolvePackageName = intentPackage; 6183 if (userNeedsBadging(userId)) { 6184 ri.noResourceId = true; 6185 } else { 6186 ri.icon = appi.icon; 6187 } 6188 ri.iconResourceId = appi.icon; 6189 ri.labelRes = appi.labelRes; 6190 } 6191 ri.activityInfo.applicationInfo = new ApplicationInfo( 6192 ri.activityInfo.applicationInfo); 6193 if (userId != 0) { 6194 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6195 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6196 } 6197 // Make sure that the resolver is displayable in car mode 6198 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6199 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6200 return ri; 6201 } 6202 } 6203 return null; 6204 } 6205 6206 /** 6207 * Return true if the given list is not empty and all of its contents have 6208 * an activityInfo with the given package name. 6209 */ 6210 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6211 if (ArrayUtils.isEmpty(list)) { 6212 return false; 6213 } 6214 for (int i = 0, N = list.size(); i < N; i++) { 6215 final ResolveInfo ri = list.get(i); 6216 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6217 if (ai == null || !packageName.equals(ai.packageName)) { 6218 return false; 6219 } 6220 } 6221 return true; 6222 } 6223 6224 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6225 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6226 final int N = query.size(); 6227 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6228 .get(userId); 6229 // Get the list of persistent preferred activities that handle the intent 6230 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6231 List<PersistentPreferredActivity> pprefs = ppir != null 6232 ? ppir.queryIntent(intent, resolvedType, 6233 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6234 userId) 6235 : null; 6236 if (pprefs != null && pprefs.size() > 0) { 6237 final int M = pprefs.size(); 6238 for (int i=0; i<M; i++) { 6239 final PersistentPreferredActivity ppa = pprefs.get(i); 6240 if (DEBUG_PREFERRED || debug) { 6241 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6242 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6243 + "\n component=" + ppa.mComponent); 6244 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6245 } 6246 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6247 flags | MATCH_DISABLED_COMPONENTS, userId); 6248 if (DEBUG_PREFERRED || debug) { 6249 Slog.v(TAG, "Found persistent preferred activity:"); 6250 if (ai != null) { 6251 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6252 } else { 6253 Slog.v(TAG, " null"); 6254 } 6255 } 6256 if (ai == null) { 6257 // This previously registered persistent preferred activity 6258 // component is no longer known. Ignore it and do NOT remove it. 6259 continue; 6260 } 6261 for (int j=0; j<N; j++) { 6262 final ResolveInfo ri = query.get(j); 6263 if (!ri.activityInfo.applicationInfo.packageName 6264 .equals(ai.applicationInfo.packageName)) { 6265 continue; 6266 } 6267 if (!ri.activityInfo.name.equals(ai.name)) { 6268 continue; 6269 } 6270 // Found a persistent preference that can handle the intent. 6271 if (DEBUG_PREFERRED || debug) { 6272 Slog.v(TAG, "Returning persistent preferred activity: " + 6273 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6274 } 6275 return ri; 6276 } 6277 } 6278 } 6279 return null; 6280 } 6281 6282 // TODO: handle preferred activities missing while user has amnesia 6283 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6284 List<ResolveInfo> query, int priority, boolean always, 6285 boolean removeMatches, boolean debug, int userId) { 6286 if (!sUserManager.exists(userId)) return null; 6287 final int callingUid = Binder.getCallingUid(); 6288 flags = updateFlagsForResolve( 6289 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6290 intent = updateIntentForResolve(intent); 6291 // writer 6292 synchronized (mPackages) { 6293 // Try to find a matching persistent preferred activity. 6294 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6295 debug, userId); 6296 6297 // If a persistent preferred activity matched, use it. 6298 if (pri != null) { 6299 return pri; 6300 } 6301 6302 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6303 // Get the list of preferred activities that handle the intent 6304 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6305 List<PreferredActivity> prefs = pir != null 6306 ? pir.queryIntent(intent, resolvedType, 6307 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6308 userId) 6309 : null; 6310 if (prefs != null && prefs.size() > 0) { 6311 boolean changed = false; 6312 try { 6313 // First figure out how good the original match set is. 6314 // We will only allow preferred activities that came 6315 // from the same match quality. 6316 int match = 0; 6317 6318 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6319 6320 final int N = query.size(); 6321 for (int j=0; j<N; j++) { 6322 final ResolveInfo ri = query.get(j); 6323 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6324 + ": 0x" + Integer.toHexString(match)); 6325 if (ri.match > match) { 6326 match = ri.match; 6327 } 6328 } 6329 6330 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6331 + Integer.toHexString(match)); 6332 6333 match &= IntentFilter.MATCH_CATEGORY_MASK; 6334 final int M = prefs.size(); 6335 for (int i=0; i<M; i++) { 6336 final PreferredActivity pa = prefs.get(i); 6337 if (DEBUG_PREFERRED || debug) { 6338 Slog.v(TAG, "Checking PreferredActivity ds=" 6339 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6340 + "\n component=" + pa.mPref.mComponent); 6341 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6342 } 6343 if (pa.mPref.mMatch != match) { 6344 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6345 + Integer.toHexString(pa.mPref.mMatch)); 6346 continue; 6347 } 6348 // If it's not an "always" type preferred activity and that's what we're 6349 // looking for, skip it. 6350 if (always && !pa.mPref.mAlways) { 6351 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6352 continue; 6353 } 6354 final ActivityInfo ai = getActivityInfo( 6355 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6356 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6357 userId); 6358 if (DEBUG_PREFERRED || debug) { 6359 Slog.v(TAG, "Found preferred activity:"); 6360 if (ai != null) { 6361 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6362 } else { 6363 Slog.v(TAG, " null"); 6364 } 6365 } 6366 if (ai == null) { 6367 // This previously registered preferred activity 6368 // component is no longer known. Most likely an update 6369 // to the app was installed and in the new version this 6370 // component no longer exists. Clean it up by removing 6371 // it from the preferred activities list, and skip it. 6372 Slog.w(TAG, "Removing dangling preferred activity: " 6373 + pa.mPref.mComponent); 6374 pir.removeFilter(pa); 6375 changed = true; 6376 continue; 6377 } 6378 for (int j=0; j<N; j++) { 6379 final ResolveInfo ri = query.get(j); 6380 if (!ri.activityInfo.applicationInfo.packageName 6381 .equals(ai.applicationInfo.packageName)) { 6382 continue; 6383 } 6384 if (!ri.activityInfo.name.equals(ai.name)) { 6385 continue; 6386 } 6387 6388 if (removeMatches) { 6389 pir.removeFilter(pa); 6390 changed = true; 6391 if (DEBUG_PREFERRED) { 6392 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6393 } 6394 break; 6395 } 6396 6397 // Okay we found a previously set preferred or last chosen app. 6398 // If the result set is different from when this 6399 // was created, and is not a subset of the preferred set, we need to 6400 // clear it and re-ask the user their preference, if we're looking for 6401 // an "always" type entry. 6402 if (always && !pa.mPref.sameSet(query)) { 6403 if (pa.mPref.isSuperset(query)) { 6404 // some components of the set are no longer present in 6405 // the query, but the preferred activity can still be reused 6406 if (DEBUG_PREFERRED) { 6407 Slog.i(TAG, "Result set changed, but PreferredActivity is" 6408 + " still valid as only non-preferred components" 6409 + " were removed for " + intent + " type " 6410 + resolvedType); 6411 } 6412 // remove obsolete components and re-add the up-to-date filter 6413 PreferredActivity freshPa = new PreferredActivity(pa, 6414 pa.mPref.mMatch, 6415 pa.mPref.discardObsoleteComponents(query), 6416 pa.mPref.mComponent, 6417 pa.mPref.mAlways); 6418 pir.removeFilter(pa); 6419 pir.addFilter(freshPa); 6420 changed = true; 6421 } else { 6422 Slog.i(TAG, 6423 "Result set changed, dropping preferred activity for " 6424 + intent + " type " + resolvedType); 6425 if (DEBUG_PREFERRED) { 6426 Slog.v(TAG, "Removing preferred activity since set changed " 6427 + pa.mPref.mComponent); 6428 } 6429 pir.removeFilter(pa); 6430 // Re-add the filter as a "last chosen" entry (!always) 6431 PreferredActivity lastChosen = new PreferredActivity( 6432 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6433 pir.addFilter(lastChosen); 6434 changed = true; 6435 return null; 6436 } 6437 } 6438 6439 // Yay! Either the set matched or we're looking for the last chosen 6440 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6441 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6442 return ri; 6443 } 6444 } 6445 } finally { 6446 if (changed) { 6447 if (DEBUG_PREFERRED) { 6448 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6449 } 6450 scheduleWritePackageRestrictionsLocked(userId); 6451 } 6452 } 6453 } 6454 } 6455 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6456 return null; 6457 } 6458 6459 /* 6460 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6461 */ 6462 @Override 6463 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6464 int targetUserId) { 6465 mContext.enforceCallingOrSelfPermission( 6466 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6467 List<CrossProfileIntentFilter> matches = 6468 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6469 if (matches != null) { 6470 int size = matches.size(); 6471 for (int i = 0; i < size; i++) { 6472 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6473 } 6474 } 6475 if (intent.hasWebURI()) { 6476 // cross-profile app linking works only towards the parent. 6477 final int callingUid = Binder.getCallingUid(); 6478 final UserInfo parent = getProfileParent(sourceUserId); 6479 synchronized(mPackages) { 6480 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6481 false /*includeInstantApps*/); 6482 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6483 intent, resolvedType, flags, sourceUserId, parent.id); 6484 return xpDomainInfo != null; 6485 } 6486 } 6487 return false; 6488 } 6489 6490 private UserInfo getProfileParent(int userId) { 6491 final long identity = Binder.clearCallingIdentity(); 6492 try { 6493 return sUserManager.getProfileParent(userId); 6494 } finally { 6495 Binder.restoreCallingIdentity(identity); 6496 } 6497 } 6498 6499 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6500 String resolvedType, int userId) { 6501 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6502 if (resolver != null) { 6503 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6504 } 6505 return null; 6506 } 6507 6508 @Override 6509 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6510 String resolvedType, int flags, int userId) { 6511 try { 6512 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6513 6514 return new ParceledListSlice<>( 6515 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6516 } finally { 6517 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6518 } 6519 } 6520 6521 /** 6522 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6523 * instant, returns {@code null}. 6524 */ 6525 private String getInstantAppPackageName(int callingUid) { 6526 synchronized (mPackages) { 6527 // If the caller is an isolated app use the owner's uid for the lookup. 6528 if (Process.isIsolated(callingUid)) { 6529 callingUid = mIsolatedOwners.get(callingUid); 6530 } 6531 final int appId = UserHandle.getAppId(callingUid); 6532 final Object obj = mSettings.getUserIdLPr(appId); 6533 if (obj instanceof PackageSetting) { 6534 final PackageSetting ps = (PackageSetting) obj; 6535 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6536 return isInstantApp ? ps.pkg.packageName : null; 6537 } 6538 } 6539 return null; 6540 } 6541 6542 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6543 String resolvedType, int flags, int userId) { 6544 return queryIntentActivitiesInternal( 6545 intent, resolvedType, flags, Binder.getCallingUid(), userId, 6546 false /*resolveForStart*/, true /*allowDynamicSplits*/); 6547 } 6548 6549 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6550 String resolvedType, int flags, int filterCallingUid, int userId, 6551 boolean resolveForStart, boolean allowDynamicSplits) { 6552 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6553 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 6554 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 6555 false /* requireFullPermission */, false /* checkShell */, 6556 "query intent activities"); 6557 final String pkgName = intent.getPackage(); 6558 ComponentName comp = intent.getComponent(); 6559 if (comp == null) { 6560 if (intent.getSelector() != null) { 6561 intent = intent.getSelector(); 6562 comp = intent.getComponent(); 6563 } 6564 } 6565 6566 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 6567 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6568 if (comp != null) { 6569 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6570 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6571 if (ai != null) { 6572 // When specifying an explicit component, we prevent the activity from being 6573 // used when either 1) the calling package is normal and the activity is within 6574 // an ephemeral application or 2) the calling package is ephemeral and the 6575 // activity is not visible to ephemeral applications. 6576 final boolean matchInstantApp = 6577 (flags & PackageManager.MATCH_INSTANT) != 0; 6578 final boolean matchVisibleToInstantAppOnly = 6579 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6580 final boolean matchExplicitlyVisibleOnly = 6581 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6582 final boolean isCallerInstantApp = 6583 instantAppPkgName != null; 6584 final boolean isTargetSameInstantApp = 6585 comp.getPackageName().equals(instantAppPkgName); 6586 final boolean isTargetInstantApp = 6587 (ai.applicationInfo.privateFlags 6588 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6589 final boolean isTargetVisibleToInstantApp = 6590 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6591 final boolean isTargetExplicitlyVisibleToInstantApp = 6592 isTargetVisibleToInstantApp 6593 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6594 final boolean isTargetHiddenFromInstantApp = 6595 !isTargetVisibleToInstantApp 6596 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6597 final boolean blockResolution = 6598 !isTargetSameInstantApp 6599 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6600 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6601 && isTargetHiddenFromInstantApp)); 6602 if (!blockResolution) { 6603 final ResolveInfo ri = new ResolveInfo(); 6604 ri.activityInfo = ai; 6605 list.add(ri); 6606 } 6607 } 6608 return applyPostResolutionFilter( 6609 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent); 6610 } 6611 6612 // reader 6613 boolean sortResult = false; 6614 boolean addInstant = false; 6615 List<ResolveInfo> result; 6616 synchronized (mPackages) { 6617 if (pkgName == null) { 6618 List<CrossProfileIntentFilter> matchingFilters = 6619 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6620 // Check for results that need to skip the current profile. 6621 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6622 resolvedType, flags, userId); 6623 if (xpResolveInfo != null) { 6624 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6625 xpResult.add(xpResolveInfo); 6626 return applyPostResolutionFilter( 6627 filterIfNotSystemUser(xpResult, userId), instantAppPkgName, 6628 allowDynamicSplits, filterCallingUid, userId, intent); 6629 } 6630 6631 // Check for results in the current profile. 6632 result = filterIfNotSystemUser(mActivities.queryIntent( 6633 intent, resolvedType, flags, userId), userId); 6634 addInstant = isInstantAppResolutionAllowed(intent, result, userId, 6635 false /*skipPackageCheck*/); 6636 // Check for cross profile results. 6637 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6638 xpResolveInfo = queryCrossProfileIntents( 6639 matchingFilters, intent, resolvedType, flags, userId, 6640 hasNonNegativePriorityResult); 6641 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6642 boolean isVisibleToUser = filterIfNotSystemUser( 6643 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6644 if (isVisibleToUser) { 6645 result.add(xpResolveInfo); 6646 sortResult = true; 6647 } 6648 } 6649 if (intent.hasWebURI()) { 6650 CrossProfileDomainInfo xpDomainInfo = null; 6651 final UserInfo parent = getProfileParent(userId); 6652 if (parent != null) { 6653 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6654 flags, userId, parent.id); 6655 } 6656 if (xpDomainInfo != null) { 6657 if (xpResolveInfo != null) { 6658 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6659 // in the result. 6660 result.remove(xpResolveInfo); 6661 } 6662 if (result.size() == 0 && !addInstant) { 6663 // No result in current profile, but found candidate in parent user. 6664 // And we are not going to add emphemeral app, so we can return the 6665 // result straight away. 6666 result.add(xpDomainInfo.resolveInfo); 6667 return applyPostResolutionFilter(result, instantAppPkgName, 6668 allowDynamicSplits, filterCallingUid, userId, intent); 6669 } 6670 } else if (result.size() <= 1 && !addInstant) { 6671 // No result in parent user and <= 1 result in current profile, and we 6672 // are not going to add emphemeral app, so we can return the result without 6673 // further processing. 6674 return applyPostResolutionFilter(result, instantAppPkgName, 6675 allowDynamicSplits, filterCallingUid, userId, intent); 6676 } 6677 // We have more than one candidate (combining results from current and parent 6678 // profile), so we need filtering and sorting. 6679 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6680 intent, flags, result, xpDomainInfo, userId); 6681 sortResult = true; 6682 } 6683 } else { 6684 final PackageParser.Package pkg = mPackages.get(pkgName); 6685 result = null; 6686 if (pkg != null) { 6687 result = filterIfNotSystemUser( 6688 mActivities.queryIntentForPackage( 6689 intent, resolvedType, flags, pkg.activities, userId), 6690 userId); 6691 } 6692 if (result == null || result.size() == 0) { 6693 // the caller wants to resolve for a particular package; however, there 6694 // were no installed results, so, try to find an ephemeral result 6695 addInstant = isInstantAppResolutionAllowed( 6696 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6697 if (result == null) { 6698 result = new ArrayList<>(); 6699 } 6700 } 6701 } 6702 } 6703 if (addInstant) { 6704 result = maybeAddInstantAppInstaller( 6705 result, intent, resolvedType, flags, userId, resolveForStart); 6706 } 6707 if (sortResult) { 6708 Collections.sort(result, mResolvePrioritySorter); 6709 } 6710 return applyPostResolutionFilter( 6711 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent); 6712 } 6713 6714 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 6715 String resolvedType, int flags, int userId, boolean resolveForStart) { 6716 // first, check to see if we've got an instant app already installed 6717 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 6718 ResolveInfo localInstantApp = null; 6719 boolean blockResolution = false; 6720 if (!alreadyResolvedLocally) { 6721 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 6722 flags 6723 | PackageManager.GET_RESOLVED_FILTER 6724 | PackageManager.MATCH_INSTANT 6725 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 6726 userId); 6727 for (int i = instantApps.size() - 1; i >= 0; --i) { 6728 final ResolveInfo info = instantApps.get(i); 6729 final String packageName = info.activityInfo.packageName; 6730 final PackageSetting ps = mSettings.mPackages.get(packageName); 6731 if (ps.getInstantApp(userId)) { 6732 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6733 final int status = (int)(packedStatus >> 32); 6734 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6735 // there's a local instant application installed, but, the user has 6736 // chosen to never use it; skip resolution and don't acknowledge 6737 // an instant application is even available 6738 if (DEBUG_INSTANT) { 6739 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 6740 } 6741 blockResolution = true; 6742 break; 6743 } else { 6744 // we have a locally installed instant application; skip resolution 6745 // but acknowledge there's an instant application available 6746 if (DEBUG_INSTANT) { 6747 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 6748 } 6749 localInstantApp = info; 6750 break; 6751 } 6752 } 6753 } 6754 } 6755 // no app installed, let's see if one's available 6756 AuxiliaryResolveInfo auxiliaryResponse = null; 6757 if (!blockResolution) { 6758 if (localInstantApp == null) { 6759 // we don't have an instant app locally, resolve externally 6760 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6761 final InstantAppRequest requestObject = new InstantAppRequest( 6762 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6763 null /*callingPackage*/, userId, null /*verificationBundle*/, 6764 resolveForStart); 6765 auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne( 6766 mInstantAppResolverConnection, requestObject); 6767 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6768 } else { 6769 // we have an instant application locally, but, we can't admit that since 6770 // callers shouldn't be able to determine prior browsing. create a dummy 6771 // auxiliary response so the downstream code behaves as if there's an 6772 // instant application available externally. when it comes time to start 6773 // the instant application, we'll do the right thing. 6774 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 6775 auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */, 6776 ai.packageName, ai.longVersionCode, null /* splitName */); 6777 } 6778 } 6779 if (intent.isWebIntent() && auxiliaryResponse == null) { 6780 return result; 6781 } 6782 final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6783 if (ps == null 6784 || ps.getUserState().get(userId) == null 6785 || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) { 6786 return result; 6787 } 6788 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6789 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6790 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6791 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6792 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6793 // add a non-generic filter 6794 ephemeralInstaller.filter = new IntentFilter(); 6795 if (intent.getAction() != null) { 6796 ephemeralInstaller.filter.addAction(intent.getAction()); 6797 } 6798 if (intent.getData() != null && intent.getData().getPath() != null) { 6799 ephemeralInstaller.filter.addDataPath( 6800 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6801 } 6802 ephemeralInstaller.isInstantAppAvailable = true; 6803 // make sure this resolver is the default 6804 ephemeralInstaller.isDefault = true; 6805 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6806 if (DEBUG_INSTANT) { 6807 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6808 } 6809 6810 result.add(ephemeralInstaller); 6811 return result; 6812 } 6813 6814 private static class CrossProfileDomainInfo { 6815 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6816 ResolveInfo resolveInfo; 6817 /* Best domain verification status of the activities found in the other profile */ 6818 int bestDomainVerificationStatus; 6819 } 6820 6821 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6822 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6823 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6824 sourceUserId)) { 6825 return null; 6826 } 6827 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6828 resolvedType, flags, parentUserId); 6829 6830 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6831 return null; 6832 } 6833 CrossProfileDomainInfo result = null; 6834 int size = resultTargetUser.size(); 6835 for (int i = 0; i < size; i++) { 6836 ResolveInfo riTargetUser = resultTargetUser.get(i); 6837 // Intent filter verification is only for filters that specify a host. So don't return 6838 // those that handle all web uris. 6839 if (riTargetUser.handleAllWebDataURI) { 6840 continue; 6841 } 6842 String packageName = riTargetUser.activityInfo.packageName; 6843 PackageSetting ps = mSettings.mPackages.get(packageName); 6844 if (ps == null) { 6845 continue; 6846 } 6847 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6848 int status = (int)(verificationState >> 32); 6849 if (result == null) { 6850 result = new CrossProfileDomainInfo(); 6851 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6852 sourceUserId, parentUserId); 6853 result.bestDomainVerificationStatus = status; 6854 } else { 6855 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6856 result.bestDomainVerificationStatus); 6857 } 6858 } 6859 // Don't consider matches with status NEVER across profiles. 6860 if (result != null && result.bestDomainVerificationStatus 6861 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6862 return null; 6863 } 6864 return result; 6865 } 6866 6867 /** 6868 * Verification statuses are ordered from the worse to the best, except for 6869 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6870 */ 6871 private int bestDomainVerificationStatus(int status1, int status2) { 6872 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6873 return status2; 6874 } 6875 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6876 return status1; 6877 } 6878 return (int) MathUtils.max(status1, status2); 6879 } 6880 6881 private boolean isUserEnabled(int userId) { 6882 long callingId = Binder.clearCallingIdentity(); 6883 try { 6884 UserInfo userInfo = sUserManager.getUserInfo(userId); 6885 return userInfo != null && userInfo.isEnabled(); 6886 } finally { 6887 Binder.restoreCallingIdentity(callingId); 6888 } 6889 } 6890 6891 /** 6892 * Filter out activities with systemUserOnly flag set, when current user is not System. 6893 * 6894 * @return filtered list 6895 */ 6896 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6897 if (userId == UserHandle.USER_SYSTEM) { 6898 return resolveInfos; 6899 } 6900 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6901 ResolveInfo info = resolveInfos.get(i); 6902 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6903 resolveInfos.remove(i); 6904 } 6905 } 6906 return resolveInfos; 6907 } 6908 6909 /** 6910 * Filters out ephemeral activities. 6911 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6912 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6913 * 6914 * @param resolveInfos The pre-filtered list of resolved activities 6915 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6916 * is performed. 6917 * @param intent 6918 * @return A filtered list of resolved activities. 6919 */ 6920 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6921 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId, 6922 Intent intent) { 6923 final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled(); 6924 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6925 final ResolveInfo info = resolveInfos.get(i); 6926 // remove locally resolved instant app web results when disabled 6927 if (info.isInstantAppAvailable && blockInstant) { 6928 resolveInfos.remove(i); 6929 continue; 6930 } 6931 // allow activities that are defined in the provided package 6932 if (allowDynamicSplits 6933 && info.activityInfo != null 6934 && info.activityInfo.splitName != null 6935 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6936 info.activityInfo.splitName)) { 6937 if (mInstantAppInstallerActivity == null) { 6938 if (DEBUG_INSTALL) { 6939 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 6940 } 6941 resolveInfos.remove(i); 6942 continue; 6943 } 6944 if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) { 6945 resolveInfos.remove(i); 6946 continue; 6947 } 6948 // requested activity is defined in a split that hasn't been installed yet. 6949 // add the installer to the resolve list 6950 if (DEBUG_INSTALL) { 6951 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 6952 } 6953 final ResolveInfo installerInfo = new ResolveInfo( 6954 mInstantAppInstallerInfo); 6955 final ComponentName installFailureActivity = findInstallFailureActivity( 6956 info.activityInfo.packageName, filterCallingUid, userId); 6957 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6958 installFailureActivity, 6959 info.activityInfo.packageName, 6960 info.activityInfo.applicationInfo.longVersionCode, 6961 info.activityInfo.splitName); 6962 // add a non-generic filter 6963 installerInfo.filter = new IntentFilter(); 6964 6965 // This resolve info may appear in the chooser UI, so let us make it 6966 // look as the one it replaces as far as the user is concerned which 6967 // requires loading the correct label and icon for the resolve info. 6968 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6969 installerInfo.labelRes = info.resolveLabelResId(); 6970 installerInfo.icon = info.resolveIconResId(); 6971 installerInfo.isInstantAppAvailable = true; 6972 resolveInfos.set(i, installerInfo); 6973 continue; 6974 } 6975 // caller is a full app, don't need to apply any other filtering 6976 if (ephemeralPkgName == null) { 6977 continue; 6978 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 6979 // caller is same app; don't need to apply any other filtering 6980 continue; 6981 } 6982 // allow activities that have been explicitly exposed to ephemeral apps 6983 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6984 if (!isEphemeralApp 6985 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 6986 continue; 6987 } 6988 resolveInfos.remove(i); 6989 } 6990 return resolveInfos; 6991 } 6992 6993 /** 6994 * Returns the activity component that can handle install failures. 6995 * <p>By default, the instant application installer handles failures. However, an 6996 * application may want to handle failures on its own. Applications do this by 6997 * creating an activity with an intent filter that handles the action 6998 * {@link Intent#ACTION_INSTALL_FAILURE}. 6999 */ 7000 private @Nullable ComponentName findInstallFailureActivity( 7001 String packageName, int filterCallingUid, int userId) { 7002 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 7003 failureActivityIntent.setPackage(packageName); 7004 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 7005 final List<ResolveInfo> result = queryIntentActivitiesInternal( 7006 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId, 7007 false /*resolveForStart*/, false /*allowDynamicSplits*/); 7008 final int NR = result.size(); 7009 if (NR > 0) { 7010 for (int i = 0; i < NR; i++) { 7011 final ResolveInfo info = result.get(i); 7012 if (info.activityInfo.splitName != null) { 7013 continue; 7014 } 7015 return new ComponentName(packageName, info.activityInfo.name); 7016 } 7017 } 7018 return null; 7019 } 7020 7021 /** 7022 * @param resolveInfos list of resolve infos in descending priority order 7023 * @return if the list contains a resolve info with non-negative priority 7024 */ 7025 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 7026 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 7027 } 7028 7029 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 7030 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 7031 int userId) { 7032 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 7033 7034 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7035 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 7036 candidates.size()); 7037 } 7038 7039 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 7040 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 7041 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 7042 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 7043 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 7044 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 7045 7046 synchronized (mPackages) { 7047 final int count = candidates.size(); 7048 // First, try to use linked apps. Partition the candidates into four lists: 7049 // one for the final results, one for the "do not use ever", one for "undefined status" 7050 // and finally one for "browser app type". 7051 for (int n=0; n<count; n++) { 7052 ResolveInfo info = candidates.get(n); 7053 String packageName = info.activityInfo.packageName; 7054 PackageSetting ps = mSettings.mPackages.get(packageName); 7055 if (ps != null) { 7056 // Add to the special match all list (Browser use case) 7057 if (info.handleAllWebDataURI) { 7058 matchAllList.add(info); 7059 continue; 7060 } 7061 // Try to get the status from User settings first 7062 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 7063 int status = (int)(packedStatus >> 32); 7064 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 7065 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 7066 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7067 Slog.i(TAG, " + always: " + info.activityInfo.packageName 7068 + " : linkgen=" + linkGeneration); 7069 } 7070 // Use link-enabled generation as preferredOrder, i.e. 7071 // prefer newly-enabled over earlier-enabled. 7072 info.preferredOrder = linkGeneration; 7073 alwaysList.add(info); 7074 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7075 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7076 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 7077 } 7078 neverList.add(info); 7079 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 7080 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7081 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 7082 } 7083 alwaysAskList.add(info); 7084 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 7085 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 7086 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7087 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 7088 } 7089 undefinedList.add(info); 7090 } 7091 } 7092 } 7093 7094 // We'll want to include browser possibilities in a few cases 7095 boolean includeBrowser = false; 7096 7097 // First try to add the "always" resolution(s) for the current user, if any 7098 if (alwaysList.size() > 0) { 7099 result.addAll(alwaysList); 7100 } else { 7101 // Add all undefined apps as we want them to appear in the disambiguation dialog. 7102 result.addAll(undefinedList); 7103 // Maybe add one for the other profile. 7104 if (xpDomainInfo != null && ( 7105 xpDomainInfo.bestDomainVerificationStatus 7106 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 7107 result.add(xpDomainInfo.resolveInfo); 7108 } 7109 includeBrowser = true; 7110 } 7111 7112 // The presence of any 'always ask' alternatives means we'll also offer browsers. 7113 // If there were 'always' entries their preferred order has been set, so we also 7114 // back that off to make the alternatives equivalent 7115 if (alwaysAskList.size() > 0) { 7116 for (ResolveInfo i : result) { 7117 i.preferredOrder = 0; 7118 } 7119 result.addAll(alwaysAskList); 7120 includeBrowser = true; 7121 } 7122 7123 if (includeBrowser) { 7124 // Also add browsers (all of them or only the default one) 7125 if (DEBUG_DOMAIN_VERIFICATION) { 7126 Slog.v(TAG, " ...including browsers in candidate set"); 7127 } 7128 if ((matchFlags & MATCH_ALL) != 0) { 7129 result.addAll(matchAllList); 7130 } else { 7131 // Browser/generic handling case. If there's a default browser, go straight 7132 // to that (but only if there is no other higher-priority match). 7133 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 7134 int maxMatchPrio = 0; 7135 ResolveInfo defaultBrowserMatch = null; 7136 final int numCandidates = matchAllList.size(); 7137 for (int n = 0; n < numCandidates; n++) { 7138 ResolveInfo info = matchAllList.get(n); 7139 // track the highest overall match priority... 7140 if (info.priority > maxMatchPrio) { 7141 maxMatchPrio = info.priority; 7142 } 7143 // ...and the highest-priority default browser match 7144 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 7145 if (defaultBrowserMatch == null 7146 || (defaultBrowserMatch.priority < info.priority)) { 7147 if (debug) { 7148 Slog.v(TAG, "Considering default browser match " + info); 7149 } 7150 defaultBrowserMatch = info; 7151 } 7152 } 7153 } 7154 if (defaultBrowserMatch != null 7155 && defaultBrowserMatch.priority >= maxMatchPrio 7156 && !TextUtils.isEmpty(defaultBrowserPackageName)) 7157 { 7158 if (debug) { 7159 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 7160 } 7161 result.add(defaultBrowserMatch); 7162 } else { 7163 result.addAll(matchAllList); 7164 } 7165 } 7166 7167 // If there is nothing selected, add all candidates and remove the ones that the user 7168 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 7169 if (result.size() == 0) { 7170 result.addAll(candidates); 7171 result.removeAll(neverList); 7172 } 7173 } 7174 } 7175 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7176 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 7177 result.size()); 7178 for (ResolveInfo info : result) { 7179 Slog.v(TAG, " + " + info.activityInfo); 7180 } 7181 } 7182 return result; 7183 } 7184 7185 // Returns a packed value as a long: 7186 // 7187 // high 'int'-sized word: link status: undefined/ask/never/always. 7188 // low 'int'-sized word: relative priority among 'always' results. 7189 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 7190 long result = ps.getDomainVerificationStatusForUser(userId); 7191 // if none available, get the master status 7192 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 7193 if (ps.getIntentFilterVerificationInfo() != null) { 7194 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 7195 } 7196 } 7197 return result; 7198 } 7199 7200 private ResolveInfo querySkipCurrentProfileIntents( 7201 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7202 int flags, int sourceUserId) { 7203 if (matchingFilters != null) { 7204 int size = matchingFilters.size(); 7205 for (int i = 0; i < size; i ++) { 7206 CrossProfileIntentFilter filter = matchingFilters.get(i); 7207 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 7208 // Checking if there are activities in the target user that can handle the 7209 // intent. 7210 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7211 resolvedType, flags, sourceUserId); 7212 if (resolveInfo != null) { 7213 return resolveInfo; 7214 } 7215 } 7216 } 7217 } 7218 return null; 7219 } 7220 7221 // Return matching ResolveInfo in target user if any. 7222 private ResolveInfo queryCrossProfileIntents( 7223 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7224 int flags, int sourceUserId, boolean matchInCurrentProfile) { 7225 if (matchingFilters != null) { 7226 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 7227 // match the same intent. For performance reasons, it is better not to 7228 // run queryIntent twice for the same userId 7229 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 7230 int size = matchingFilters.size(); 7231 for (int i = 0; i < size; i++) { 7232 CrossProfileIntentFilter filter = matchingFilters.get(i); 7233 int targetUserId = filter.getTargetUserId(); 7234 boolean skipCurrentProfile = 7235 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 7236 boolean skipCurrentProfileIfNoMatchFound = 7237 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 7238 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 7239 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 7240 // Checking if there are activities in the target user that can handle the 7241 // intent. 7242 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7243 resolvedType, flags, sourceUserId); 7244 if (resolveInfo != null) return resolveInfo; 7245 alreadyTriedUserIds.put(targetUserId, true); 7246 } 7247 } 7248 } 7249 return null; 7250 } 7251 7252 /** 7253 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 7254 * will forward the intent to the filter's target user. 7255 * Otherwise, returns null. 7256 */ 7257 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 7258 String resolvedType, int flags, int sourceUserId) { 7259 int targetUserId = filter.getTargetUserId(); 7260 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7261 resolvedType, flags, targetUserId); 7262 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7263 // If all the matches in the target profile are suspended, return null. 7264 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7265 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7266 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7267 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7268 targetUserId); 7269 } 7270 } 7271 } 7272 return null; 7273 } 7274 7275 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7276 int sourceUserId, int targetUserId) { 7277 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7278 long ident = Binder.clearCallingIdentity(); 7279 boolean targetIsProfile; 7280 try { 7281 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7282 } finally { 7283 Binder.restoreCallingIdentity(ident); 7284 } 7285 String className; 7286 if (targetIsProfile) { 7287 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7288 } else { 7289 className = FORWARD_INTENT_TO_PARENT; 7290 } 7291 ComponentName forwardingActivityComponentName = new ComponentName( 7292 mAndroidApplication.packageName, className); 7293 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7294 sourceUserId); 7295 if (!targetIsProfile) { 7296 forwardingActivityInfo.showUserIcon = targetUserId; 7297 forwardingResolveInfo.noResourceId = true; 7298 } 7299 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7300 forwardingResolveInfo.priority = 0; 7301 forwardingResolveInfo.preferredOrder = 0; 7302 forwardingResolveInfo.match = 0; 7303 forwardingResolveInfo.isDefault = true; 7304 forwardingResolveInfo.filter = filter; 7305 forwardingResolveInfo.targetUserId = targetUserId; 7306 return forwardingResolveInfo; 7307 } 7308 7309 @Override 7310 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7311 Intent[] specifics, String[] specificTypes, Intent intent, 7312 String resolvedType, int flags, int userId) { 7313 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7314 specificTypes, intent, resolvedType, flags, userId)); 7315 } 7316 7317 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7318 Intent[] specifics, String[] specificTypes, Intent intent, 7319 String resolvedType, int flags, int userId) { 7320 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7321 final int callingUid = Binder.getCallingUid(); 7322 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7323 false /*includeInstantApps*/); 7324 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7325 false /*requireFullPermission*/, false /*checkShell*/, 7326 "query intent activity options"); 7327 final String resultsAction = intent.getAction(); 7328 7329 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7330 | PackageManager.GET_RESOLVED_FILTER, userId); 7331 7332 if (DEBUG_INTENT_MATCHING) { 7333 Log.v(TAG, "Query " + intent + ": " + results); 7334 } 7335 7336 int specificsPos = 0; 7337 int N; 7338 7339 // todo: note that the algorithm used here is O(N^2). This 7340 // isn't a problem in our current environment, but if we start running 7341 // into situations where we have more than 5 or 10 matches then this 7342 // should probably be changed to something smarter... 7343 7344 // First we go through and resolve each of the specific items 7345 // that were supplied, taking care of removing any corresponding 7346 // duplicate items in the generic resolve list. 7347 if (specifics != null) { 7348 for (int i=0; i<specifics.length; i++) { 7349 final Intent sintent = specifics[i]; 7350 if (sintent == null) { 7351 continue; 7352 } 7353 7354 if (DEBUG_INTENT_MATCHING) { 7355 Log.v(TAG, "Specific #" + i + ": " + sintent); 7356 } 7357 7358 String action = sintent.getAction(); 7359 if (resultsAction != null && resultsAction.equals(action)) { 7360 // If this action was explicitly requested, then don't 7361 // remove things that have it. 7362 action = null; 7363 } 7364 7365 ResolveInfo ri = null; 7366 ActivityInfo ai = null; 7367 7368 ComponentName comp = sintent.getComponent(); 7369 if (comp == null) { 7370 ri = resolveIntent( 7371 sintent, 7372 specificTypes != null ? specificTypes[i] : null, 7373 flags, userId); 7374 if (ri == null) { 7375 continue; 7376 } 7377 if (ri == mResolveInfo) { 7378 // ACK! Must do something better with this. 7379 } 7380 ai = ri.activityInfo; 7381 comp = new ComponentName(ai.applicationInfo.packageName, 7382 ai.name); 7383 } else { 7384 ai = getActivityInfo(comp, flags, userId); 7385 if (ai == null) { 7386 continue; 7387 } 7388 } 7389 7390 // Look for any generic query activities that are duplicates 7391 // of this specific one, and remove them from the results. 7392 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7393 N = results.size(); 7394 int j; 7395 for (j=specificsPos; j<N; j++) { 7396 ResolveInfo sri = results.get(j); 7397 if ((sri.activityInfo.name.equals(comp.getClassName()) 7398 && sri.activityInfo.applicationInfo.packageName.equals( 7399 comp.getPackageName())) 7400 || (action != null && sri.filter.matchAction(action))) { 7401 results.remove(j); 7402 if (DEBUG_INTENT_MATCHING) Log.v( 7403 TAG, "Removing duplicate item from " + j 7404 + " due to specific " + specificsPos); 7405 if (ri == null) { 7406 ri = sri; 7407 } 7408 j--; 7409 N--; 7410 } 7411 } 7412 7413 // Add this specific item to its proper place. 7414 if (ri == null) { 7415 ri = new ResolveInfo(); 7416 ri.activityInfo = ai; 7417 } 7418 results.add(specificsPos, ri); 7419 ri.specificIndex = i; 7420 specificsPos++; 7421 } 7422 } 7423 7424 // Now we go through the remaining generic results and remove any 7425 // duplicate actions that are found here. 7426 N = results.size(); 7427 for (int i=specificsPos; i<N-1; i++) { 7428 final ResolveInfo rii = results.get(i); 7429 if (rii.filter == null) { 7430 continue; 7431 } 7432 7433 // Iterate over all of the actions of this result's intent 7434 // filter... typically this should be just one. 7435 final Iterator<String> it = rii.filter.actionsIterator(); 7436 if (it == null) { 7437 continue; 7438 } 7439 while (it.hasNext()) { 7440 final String action = it.next(); 7441 if (resultsAction != null && resultsAction.equals(action)) { 7442 // If this action was explicitly requested, then don't 7443 // remove things that have it. 7444 continue; 7445 } 7446 for (int j=i+1; j<N; j++) { 7447 final ResolveInfo rij = results.get(j); 7448 if (rij.filter != null && rij.filter.hasAction(action)) { 7449 results.remove(j); 7450 if (DEBUG_INTENT_MATCHING) Log.v( 7451 TAG, "Removing duplicate item from " + j 7452 + " due to action " + action + " at " + i); 7453 j--; 7454 N--; 7455 } 7456 } 7457 } 7458 7459 // If the caller didn't request filter information, drop it now 7460 // so we don't have to marshall/unmarshall it. 7461 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7462 rii.filter = null; 7463 } 7464 } 7465 7466 // Filter out the caller activity if so requested. 7467 if (caller != null) { 7468 N = results.size(); 7469 for (int i=0; i<N; i++) { 7470 ActivityInfo ainfo = results.get(i).activityInfo; 7471 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7472 && caller.getClassName().equals(ainfo.name)) { 7473 results.remove(i); 7474 break; 7475 } 7476 } 7477 } 7478 7479 // If the caller didn't request filter information, 7480 // drop them now so we don't have to 7481 // marshall/unmarshall it. 7482 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7483 N = results.size(); 7484 for (int i=0; i<N; i++) { 7485 results.get(i).filter = null; 7486 } 7487 } 7488 7489 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7490 return results; 7491 } 7492 7493 @Override 7494 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7495 String resolvedType, int flags, int userId) { 7496 return new ParceledListSlice<>( 7497 queryIntentReceiversInternal(intent, resolvedType, flags, userId, 7498 false /*allowDynamicSplits*/)); 7499 } 7500 7501 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7502 String resolvedType, int flags, int userId, boolean allowDynamicSplits) { 7503 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7504 final int callingUid = Binder.getCallingUid(); 7505 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7506 false /*requireFullPermission*/, false /*checkShell*/, 7507 "query intent receivers"); 7508 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7509 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7510 false /*includeInstantApps*/); 7511 ComponentName comp = intent.getComponent(); 7512 if (comp == null) { 7513 if (intent.getSelector() != null) { 7514 intent = intent.getSelector(); 7515 comp = intent.getComponent(); 7516 } 7517 } 7518 if (comp != null) { 7519 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7520 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7521 if (ai != null) { 7522 // When specifying an explicit component, we prevent the activity from being 7523 // used when either 1) the calling package is normal and the activity is within 7524 // an instant application or 2) the calling package is ephemeral and the 7525 // activity is not visible to instant applications. 7526 final boolean matchInstantApp = 7527 (flags & PackageManager.MATCH_INSTANT) != 0; 7528 final boolean matchVisibleToInstantAppOnly = 7529 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7530 final boolean matchExplicitlyVisibleOnly = 7531 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7532 final boolean isCallerInstantApp = 7533 instantAppPkgName != null; 7534 final boolean isTargetSameInstantApp = 7535 comp.getPackageName().equals(instantAppPkgName); 7536 final boolean isTargetInstantApp = 7537 (ai.applicationInfo.privateFlags 7538 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7539 final boolean isTargetVisibleToInstantApp = 7540 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7541 final boolean isTargetExplicitlyVisibleToInstantApp = 7542 isTargetVisibleToInstantApp 7543 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7544 final boolean isTargetHiddenFromInstantApp = 7545 !isTargetVisibleToInstantApp 7546 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7547 final boolean blockResolution = 7548 !isTargetSameInstantApp 7549 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7550 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7551 && isTargetHiddenFromInstantApp)); 7552 if (!blockResolution) { 7553 ResolveInfo ri = new ResolveInfo(); 7554 ri.activityInfo = ai; 7555 list.add(ri); 7556 } 7557 } 7558 return applyPostResolutionFilter( 7559 list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent); 7560 } 7561 7562 // reader 7563 synchronized (mPackages) { 7564 String pkgName = intent.getPackage(); 7565 if (pkgName == null) { 7566 final List<ResolveInfo> result = 7567 mReceivers.queryIntent(intent, resolvedType, flags, userId); 7568 return applyPostResolutionFilter( 7569 result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent); 7570 } 7571 final PackageParser.Package pkg = mPackages.get(pkgName); 7572 if (pkg != null) { 7573 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 7574 intent, resolvedType, flags, pkg.receivers, userId); 7575 return applyPostResolutionFilter( 7576 result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent); 7577 } 7578 return Collections.emptyList(); 7579 } 7580 } 7581 7582 @Override 7583 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7584 final int callingUid = Binder.getCallingUid(); 7585 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7586 } 7587 7588 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7589 int userId, int callingUid) { 7590 if (!sUserManager.exists(userId)) return null; 7591 flags = updateFlagsForResolve( 7592 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7593 List<ResolveInfo> query = queryIntentServicesInternal( 7594 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7595 if (query != null) { 7596 if (query.size() >= 1) { 7597 // If there is more than one service with the same priority, 7598 // just arbitrarily pick the first one. 7599 return query.get(0); 7600 } 7601 } 7602 return null; 7603 } 7604 7605 @Override 7606 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7607 String resolvedType, int flags, int userId) { 7608 final int callingUid = Binder.getCallingUid(); 7609 return new ParceledListSlice<>(queryIntentServicesInternal( 7610 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7611 } 7612 7613 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7614 String resolvedType, int flags, int userId, int callingUid, 7615 boolean includeInstantApps) { 7616 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7617 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7618 false /*requireFullPermission*/, false /*checkShell*/, 7619 "query intent receivers"); 7620 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7621 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7622 ComponentName comp = intent.getComponent(); 7623 if (comp == null) { 7624 if (intent.getSelector() != null) { 7625 intent = intent.getSelector(); 7626 comp = intent.getComponent(); 7627 } 7628 } 7629 if (comp != null) { 7630 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7631 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7632 if (si != null) { 7633 // When specifying an explicit component, we prevent the service from being 7634 // used when either 1) the service is in an instant application and the 7635 // caller is not the same instant application or 2) the calling package is 7636 // ephemeral and the activity is not visible to ephemeral applications. 7637 final boolean matchInstantApp = 7638 (flags & PackageManager.MATCH_INSTANT) != 0; 7639 final boolean matchVisibleToInstantAppOnly = 7640 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7641 final boolean isCallerInstantApp = 7642 instantAppPkgName != null; 7643 final boolean isTargetSameInstantApp = 7644 comp.getPackageName().equals(instantAppPkgName); 7645 final boolean isTargetInstantApp = 7646 (si.applicationInfo.privateFlags 7647 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7648 final boolean isTargetHiddenFromInstantApp = 7649 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7650 final boolean blockResolution = 7651 !isTargetSameInstantApp 7652 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7653 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7654 && isTargetHiddenFromInstantApp)); 7655 if (!blockResolution) { 7656 final ResolveInfo ri = new ResolveInfo(); 7657 ri.serviceInfo = si; 7658 list.add(ri); 7659 } 7660 } 7661 return list; 7662 } 7663 7664 // reader 7665 synchronized (mPackages) { 7666 String pkgName = intent.getPackage(); 7667 if (pkgName == null) { 7668 return applyPostServiceResolutionFilter( 7669 mServices.queryIntent(intent, resolvedType, flags, userId), 7670 instantAppPkgName); 7671 } 7672 final PackageParser.Package pkg = mPackages.get(pkgName); 7673 if (pkg != null) { 7674 return applyPostServiceResolutionFilter( 7675 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7676 userId), 7677 instantAppPkgName); 7678 } 7679 return Collections.emptyList(); 7680 } 7681 } 7682 7683 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7684 String instantAppPkgName) { 7685 if (instantAppPkgName == null) { 7686 return resolveInfos; 7687 } 7688 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7689 final ResolveInfo info = resolveInfos.get(i); 7690 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7691 // allow services that are defined in the provided package 7692 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7693 if (info.serviceInfo.splitName != null 7694 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7695 info.serviceInfo.splitName)) { 7696 // requested service is defined in a split that hasn't been installed yet. 7697 // add the installer to the resolve list 7698 if (DEBUG_INSTANT) { 7699 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7700 } 7701 final ResolveInfo installerInfo = new ResolveInfo( 7702 mInstantAppInstallerInfo); 7703 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7704 null /* installFailureActivity */, 7705 info.serviceInfo.packageName, 7706 info.serviceInfo.applicationInfo.longVersionCode, 7707 info.serviceInfo.splitName); 7708 // add a non-generic filter 7709 installerInfo.filter = new IntentFilter(); 7710 // load resources from the correct package 7711 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7712 resolveInfos.set(i, installerInfo); 7713 } 7714 continue; 7715 } 7716 // allow services that have been explicitly exposed to ephemeral apps 7717 if (!isEphemeralApp 7718 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7719 continue; 7720 } 7721 resolveInfos.remove(i); 7722 } 7723 return resolveInfos; 7724 } 7725 7726 @Override 7727 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7728 String resolvedType, int flags, int userId) { 7729 return new ParceledListSlice<>( 7730 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7731 } 7732 7733 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7734 Intent intent, String resolvedType, int flags, int userId) { 7735 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7736 final int callingUid = Binder.getCallingUid(); 7737 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7738 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7739 false /*includeInstantApps*/); 7740 ComponentName comp = intent.getComponent(); 7741 if (comp == null) { 7742 if (intent.getSelector() != null) { 7743 intent = intent.getSelector(); 7744 comp = intent.getComponent(); 7745 } 7746 } 7747 if (comp != null) { 7748 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7749 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7750 if (pi != null) { 7751 // When specifying an explicit component, we prevent the provider from being 7752 // used when either 1) the provider is in an instant application and the 7753 // caller is not the same instant application or 2) the calling package is an 7754 // instant application and the provider is not visible to instant applications. 7755 final boolean matchInstantApp = 7756 (flags & PackageManager.MATCH_INSTANT) != 0; 7757 final boolean matchVisibleToInstantAppOnly = 7758 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7759 final boolean isCallerInstantApp = 7760 instantAppPkgName != null; 7761 final boolean isTargetSameInstantApp = 7762 comp.getPackageName().equals(instantAppPkgName); 7763 final boolean isTargetInstantApp = 7764 (pi.applicationInfo.privateFlags 7765 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7766 final boolean isTargetHiddenFromInstantApp = 7767 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7768 final boolean blockResolution = 7769 !isTargetSameInstantApp 7770 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7771 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7772 && isTargetHiddenFromInstantApp)); 7773 if (!blockResolution) { 7774 final ResolveInfo ri = new ResolveInfo(); 7775 ri.providerInfo = pi; 7776 list.add(ri); 7777 } 7778 } 7779 return list; 7780 } 7781 7782 // reader 7783 synchronized (mPackages) { 7784 String pkgName = intent.getPackage(); 7785 if (pkgName == null) { 7786 return applyPostContentProviderResolutionFilter( 7787 mProviders.queryIntent(intent, resolvedType, flags, userId), 7788 instantAppPkgName); 7789 } 7790 final PackageParser.Package pkg = mPackages.get(pkgName); 7791 if (pkg != null) { 7792 return applyPostContentProviderResolutionFilter( 7793 mProviders.queryIntentForPackage( 7794 intent, resolvedType, flags, pkg.providers, userId), 7795 instantAppPkgName); 7796 } 7797 return Collections.emptyList(); 7798 } 7799 } 7800 7801 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7802 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7803 if (instantAppPkgName == null) { 7804 return resolveInfos; 7805 } 7806 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7807 final ResolveInfo info = resolveInfos.get(i); 7808 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7809 // allow providers that are defined in the provided package 7810 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7811 if (info.providerInfo.splitName != null 7812 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7813 info.providerInfo.splitName)) { 7814 // requested provider is defined in a split that hasn't been installed yet. 7815 // add the installer to the resolve list 7816 if (DEBUG_INSTANT) { 7817 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7818 } 7819 final ResolveInfo installerInfo = new ResolveInfo( 7820 mInstantAppInstallerInfo); 7821 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7822 null /*failureActivity*/, 7823 info.providerInfo.packageName, 7824 info.providerInfo.applicationInfo.longVersionCode, 7825 info.providerInfo.splitName); 7826 // add a non-generic filter 7827 installerInfo.filter = new IntentFilter(); 7828 // load resources from the correct package 7829 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7830 resolveInfos.set(i, installerInfo); 7831 } 7832 continue; 7833 } 7834 // allow providers that have been explicitly exposed to instant applications 7835 if (!isEphemeralApp 7836 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7837 continue; 7838 } 7839 resolveInfos.remove(i); 7840 } 7841 return resolveInfos; 7842 } 7843 7844 @Override 7845 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7846 final int callingUid = Binder.getCallingUid(); 7847 if (getInstantAppPackageName(callingUid) != null) { 7848 return ParceledListSlice.emptyList(); 7849 } 7850 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7851 flags = updateFlagsForPackage(flags, userId, null); 7852 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7853 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7854 true /* requireFullPermission */, false /* checkShell */, 7855 "get installed packages"); 7856 7857 // writer 7858 synchronized (mPackages) { 7859 ArrayList<PackageInfo> list; 7860 if (listUninstalled) { 7861 list = new ArrayList<>(mSettings.mPackages.size()); 7862 for (PackageSetting ps : mSettings.mPackages.values()) { 7863 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7864 continue; 7865 } 7866 if (filterAppAccessLPr(ps, callingUid, userId)) { 7867 continue; 7868 } 7869 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7870 if (pi != null) { 7871 list.add(pi); 7872 } 7873 } 7874 } else { 7875 list = new ArrayList<>(mPackages.size()); 7876 for (PackageParser.Package p : mPackages.values()) { 7877 final PackageSetting ps = (PackageSetting) p.mExtras; 7878 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7879 continue; 7880 } 7881 if (filterAppAccessLPr(ps, callingUid, userId)) { 7882 continue; 7883 } 7884 final PackageInfo pi = generatePackageInfo((PackageSetting) 7885 p.mExtras, flags, userId); 7886 if (pi != null) { 7887 list.add(pi); 7888 } 7889 } 7890 } 7891 7892 return new ParceledListSlice<>(list); 7893 } 7894 } 7895 7896 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7897 String[] permissions, boolean[] tmp, int flags, int userId) { 7898 int numMatch = 0; 7899 final PermissionsState permissionsState = ps.getPermissionsState(); 7900 for (int i=0; i<permissions.length; i++) { 7901 final String permission = permissions[i]; 7902 if (permissionsState.hasPermission(permission, userId)) { 7903 tmp[i] = true; 7904 numMatch++; 7905 } else { 7906 tmp[i] = false; 7907 } 7908 } 7909 if (numMatch == 0) { 7910 return; 7911 } 7912 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7913 7914 // The above might return null in cases of uninstalled apps or install-state 7915 // skew across users/profiles. 7916 if (pi != null) { 7917 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7918 if (numMatch == permissions.length) { 7919 pi.requestedPermissions = permissions; 7920 } else { 7921 pi.requestedPermissions = new String[numMatch]; 7922 numMatch = 0; 7923 for (int i=0; i<permissions.length; i++) { 7924 if (tmp[i]) { 7925 pi.requestedPermissions[numMatch] = permissions[i]; 7926 numMatch++; 7927 } 7928 } 7929 } 7930 } 7931 list.add(pi); 7932 } 7933 } 7934 7935 @Override 7936 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7937 String[] permissions, int flags, int userId) { 7938 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7939 flags = updateFlagsForPackage(flags, userId, permissions); 7940 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7941 true /* requireFullPermission */, false /* checkShell */, 7942 "get packages holding permissions"); 7943 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7944 7945 // writer 7946 synchronized (mPackages) { 7947 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7948 boolean[] tmpBools = new boolean[permissions.length]; 7949 if (listUninstalled) { 7950 for (PackageSetting ps : mSettings.mPackages.values()) { 7951 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7952 userId); 7953 } 7954 } else { 7955 for (PackageParser.Package pkg : mPackages.values()) { 7956 PackageSetting ps = (PackageSetting)pkg.mExtras; 7957 if (ps != null) { 7958 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7959 userId); 7960 } 7961 } 7962 } 7963 7964 return new ParceledListSlice<PackageInfo>(list); 7965 } 7966 } 7967 7968 @Override 7969 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7970 final int callingUid = Binder.getCallingUid(); 7971 if (getInstantAppPackageName(callingUid) != null) { 7972 return ParceledListSlice.emptyList(); 7973 } 7974 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7975 flags = updateFlagsForApplication(flags, userId, null); 7976 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7977 7978 // writer 7979 synchronized (mPackages) { 7980 ArrayList<ApplicationInfo> list; 7981 if (listUninstalled) { 7982 list = new ArrayList<>(mSettings.mPackages.size()); 7983 for (PackageSetting ps : mSettings.mPackages.values()) { 7984 ApplicationInfo ai; 7985 int effectiveFlags = flags; 7986 if (ps.isSystem()) { 7987 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7988 } 7989 if (ps.pkg != null) { 7990 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7991 continue; 7992 } 7993 if (filterAppAccessLPr(ps, callingUid, userId)) { 7994 continue; 7995 } 7996 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7997 ps.readUserState(userId), userId); 7998 if (ai != null) { 7999 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 8000 } 8001 } else { 8002 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 8003 // and already converts to externally visible package name 8004 ai = generateApplicationInfoFromSettingsLPw(ps.name, 8005 callingUid, effectiveFlags, userId); 8006 } 8007 if (ai != null) { 8008 list.add(ai); 8009 } 8010 } 8011 } else { 8012 list = new ArrayList<>(mPackages.size()); 8013 for (PackageParser.Package p : mPackages.values()) { 8014 if (p.mExtras != null) { 8015 PackageSetting ps = (PackageSetting) p.mExtras; 8016 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 8017 continue; 8018 } 8019 if (filterAppAccessLPr(ps, callingUid, userId)) { 8020 continue; 8021 } 8022 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8023 ps.readUserState(userId), userId); 8024 if (ai != null) { 8025 ai.packageName = resolveExternalPackageNameLPr(p); 8026 list.add(ai); 8027 } 8028 } 8029 } 8030 } 8031 8032 return new ParceledListSlice<>(list); 8033 } 8034 } 8035 8036 @Override 8037 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 8038 if (HIDE_EPHEMERAL_APIS) { 8039 return null; 8040 } 8041 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8042 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8043 "getEphemeralApplications"); 8044 } 8045 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8046 true /* requireFullPermission */, false /* checkShell */, 8047 "getEphemeralApplications"); 8048 synchronized (mPackages) { 8049 List<InstantAppInfo> instantApps = mInstantAppRegistry 8050 .getInstantAppsLPr(userId); 8051 if (instantApps != null) { 8052 return new ParceledListSlice<>(instantApps); 8053 } 8054 } 8055 return null; 8056 } 8057 8058 @Override 8059 public boolean isInstantApp(String packageName, int userId) { 8060 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8061 true /* requireFullPermission */, false /* checkShell */, 8062 "isInstantApp"); 8063 if (HIDE_EPHEMERAL_APIS) { 8064 return false; 8065 } 8066 8067 synchronized (mPackages) { 8068 int callingUid = Binder.getCallingUid(); 8069 if (Process.isIsolated(callingUid)) { 8070 callingUid = mIsolatedOwners.get(callingUid); 8071 } 8072 final PackageSetting ps = mSettings.mPackages.get(packageName); 8073 final boolean returnAllowed = 8074 ps != null 8075 && (isCallerSameApp(packageName, callingUid) 8076 || canViewInstantApps(callingUid, userId) 8077 || mInstantAppRegistry.isInstantAccessGranted( 8078 userId, UserHandle.getAppId(callingUid), ps.appId)); 8079 if (returnAllowed) { 8080 return ps.getInstantApp(userId); 8081 } 8082 } 8083 return false; 8084 } 8085 8086 @Override 8087 public byte[] getInstantAppCookie(String packageName, int userId) { 8088 if (HIDE_EPHEMERAL_APIS) { 8089 return null; 8090 } 8091 8092 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8093 true /* requireFullPermission */, false /* checkShell */, 8094 "getInstantAppCookie"); 8095 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8096 return null; 8097 } 8098 synchronized (mPackages) { 8099 return mInstantAppRegistry.getInstantAppCookieLPw( 8100 packageName, userId); 8101 } 8102 } 8103 8104 @Override 8105 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 8106 if (HIDE_EPHEMERAL_APIS) { 8107 return true; 8108 } 8109 8110 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8111 true /* requireFullPermission */, true /* checkShell */, 8112 "setInstantAppCookie"); 8113 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8114 return false; 8115 } 8116 synchronized (mPackages) { 8117 return mInstantAppRegistry.setInstantAppCookieLPw( 8118 packageName, cookie, userId); 8119 } 8120 } 8121 8122 @Override 8123 public Bitmap getInstantAppIcon(String packageName, int userId) { 8124 if (HIDE_EPHEMERAL_APIS) { 8125 return null; 8126 } 8127 8128 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8129 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8130 "getInstantAppIcon"); 8131 } 8132 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8133 true /* requireFullPermission */, false /* checkShell */, 8134 "getInstantAppIcon"); 8135 8136 synchronized (mPackages) { 8137 return mInstantAppRegistry.getInstantAppIconLPw( 8138 packageName, userId); 8139 } 8140 } 8141 8142 private boolean isCallerSameApp(String packageName, int uid) { 8143 PackageParser.Package pkg = mSettings.getPackageLPr(packageName).getPackage(); 8144 return pkg != null 8145 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 8146 } 8147 8148 @Override 8149 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 8150 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8151 return ParceledListSlice.emptyList(); 8152 } 8153 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 8154 } 8155 8156 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 8157 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 8158 8159 // reader 8160 synchronized (mPackages) { 8161 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 8162 final int userId = UserHandle.getCallingUserId(); 8163 while (i.hasNext()) { 8164 final PackageParser.Package p = i.next(); 8165 if (p.applicationInfo == null) continue; 8166 8167 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 8168 && !p.applicationInfo.isDirectBootAware(); 8169 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 8170 && p.applicationInfo.isDirectBootAware(); 8171 8172 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 8173 && (!mSafeMode || isSystemApp(p)) 8174 && (matchesUnaware || matchesAware)) { 8175 PackageSetting ps = mSettings.mPackages.get(p.packageName); 8176 if (ps != null) { 8177 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8178 ps.readUserState(userId), userId); 8179 if (ai != null) { 8180 finalList.add(ai); 8181 } 8182 } 8183 } 8184 } 8185 } 8186 8187 return finalList; 8188 } 8189 8190 @Override 8191 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 8192 return resolveContentProviderInternal(name, flags, userId); 8193 } 8194 8195 private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) { 8196 if (!sUserManager.exists(userId)) return null; 8197 flags = updateFlagsForComponent(flags, userId, name); 8198 final int callingUid = Binder.getCallingUid(); 8199 synchronized (mPackages) { 8200 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 8201 PackageSetting ps = provider != null 8202 ? mSettings.mPackages.get(provider.owner.packageName) 8203 : null; 8204 if (ps != null) { 8205 // provider not enabled 8206 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 8207 return null; 8208 } 8209 final ComponentName component = 8210 new ComponentName(provider.info.packageName, provider.info.name); 8211 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8212 return null; 8213 } 8214 return PackageParser.generateProviderInfo( 8215 provider, flags, ps.readUserState(userId), userId); 8216 } 8217 return null; 8218 } 8219 } 8220 8221 /** 8222 * @deprecated 8223 */ 8224 @Deprecated 8225 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 8226 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8227 return; 8228 } 8229 // reader 8230 synchronized (mPackages) { 8231 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 8232 .entrySet().iterator(); 8233 final int userId = UserHandle.getCallingUserId(); 8234 while (i.hasNext()) { 8235 Map.Entry<String, PackageParser.Provider> entry = i.next(); 8236 PackageParser.Provider p = entry.getValue(); 8237 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8238 8239 if (ps != null && p.syncable 8240 && (!mSafeMode || (p.info.applicationInfo.flags 8241 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 8242 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 8243 ps.readUserState(userId), userId); 8244 if (info != null) { 8245 outNames.add(entry.getKey()); 8246 outInfo.add(info); 8247 } 8248 } 8249 } 8250 } 8251 } 8252 8253 @Override 8254 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8255 int uid, int flags, String metaDataKey) { 8256 final int callingUid = Binder.getCallingUid(); 8257 final int userId = processName != null ? UserHandle.getUserId(uid) 8258 : UserHandle.getCallingUserId(); 8259 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8260 flags = updateFlagsForComponent(flags, userId, processName); 8261 ArrayList<ProviderInfo> finalList = null; 8262 // reader 8263 synchronized (mPackages) { 8264 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 8265 while (i.hasNext()) { 8266 final PackageParser.Provider p = i.next(); 8267 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8268 if (ps != null && p.info.authority != null 8269 && (processName == null 8270 || (p.info.processName.equals(processName) 8271 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 8272 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 8273 8274 // See PM.queryContentProviders()'s javadoc for why we have the metaData 8275 // parameter. 8276 if (metaDataKey != null 8277 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 8278 continue; 8279 } 8280 final ComponentName component = 8281 new ComponentName(p.info.packageName, p.info.name); 8282 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8283 continue; 8284 } 8285 if (finalList == null) { 8286 finalList = new ArrayList<ProviderInfo>(3); 8287 } 8288 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8289 ps.readUserState(userId), userId); 8290 if (info != null) { 8291 finalList.add(info); 8292 } 8293 } 8294 } 8295 } 8296 8297 if (finalList != null) { 8298 Collections.sort(finalList, mProviderInitOrderSorter); 8299 return new ParceledListSlice<ProviderInfo>(finalList); 8300 } 8301 8302 return ParceledListSlice.emptyList(); 8303 } 8304 8305 @Override 8306 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8307 // reader 8308 synchronized (mPackages) { 8309 final int callingUid = Binder.getCallingUid(); 8310 final int callingUserId = UserHandle.getUserId(callingUid); 8311 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8312 if (ps == null) return null; 8313 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8314 return null; 8315 } 8316 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8317 return PackageParser.generateInstrumentationInfo(i, flags); 8318 } 8319 } 8320 8321 @Override 8322 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8323 String targetPackage, int flags) { 8324 final int callingUid = Binder.getCallingUid(); 8325 final int callingUserId = UserHandle.getUserId(callingUid); 8326 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8327 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8328 return ParceledListSlice.emptyList(); 8329 } 8330 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8331 } 8332 8333 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8334 int flags) { 8335 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 8336 8337 // reader 8338 synchronized (mPackages) { 8339 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8340 while (i.hasNext()) { 8341 final PackageParser.Instrumentation p = i.next(); 8342 if (targetPackage == null 8343 || targetPackage.equals(p.info.targetPackage)) { 8344 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8345 flags); 8346 if (ii != null) { 8347 finalList.add(ii); 8348 } 8349 } 8350 } 8351 } 8352 8353 return finalList; 8354 } 8355 8356 private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) { 8357 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]"); 8358 try { 8359 scanDirLI(scanDir, parseFlags, scanFlags, currentTime); 8360 } finally { 8361 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8362 } 8363 } 8364 8365 private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) { 8366 final File[] files = scanDir.listFiles(); 8367 if (ArrayUtils.isEmpty(files)) { 8368 Log.d(TAG, "No files in app dir " + scanDir); 8369 return; 8370 } 8371 8372 if (DEBUG_PACKAGE_SCANNING) { 8373 Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags 8374 + " flags=0x" + Integer.toHexString(parseFlags)); 8375 } 8376 try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8377 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8378 mParallelPackageParserCallback)) { 8379 // Submit files for parsing in parallel 8380 int fileCount = 0; 8381 for (File file : files) { 8382 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8383 && !PackageInstallerService.isStageName(file.getName()); 8384 if (!isPackage) { 8385 // Ignore entries which are not packages 8386 continue; 8387 } 8388 parallelPackageParser.submit(file, parseFlags); 8389 fileCount++; 8390 } 8391 8392 // Process results one by one 8393 for (; fileCount > 0; fileCount--) { 8394 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8395 Throwable throwable = parseResult.throwable; 8396 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8397 8398 if (throwable == null) { 8399 // TODO(toddke): move lower in the scan chain 8400 // Static shared libraries have synthetic package names 8401 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8402 renameStaticSharedLibraryPackage(parseResult.pkg); 8403 } 8404 try { 8405 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8406 scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags, 8407 currentTime, null); 8408 } 8409 } catch (PackageManagerException e) { 8410 errorCode = e.error; 8411 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8412 } 8413 } else if (throwable instanceof PackageParser.PackageParserException) { 8414 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8415 throwable; 8416 errorCode = e.error; 8417 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8418 } else { 8419 throw new IllegalStateException("Unexpected exception occurred while parsing " 8420 + parseResult.scanFile, throwable); 8421 } 8422 8423 // Delete invalid userdata apps 8424 if ((scanFlags & SCAN_AS_SYSTEM) == 0 && 8425 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8426 logCriticalInfo(Log.WARN, 8427 "Deleting invalid package at " + parseResult.scanFile); 8428 removeCodePathLI(parseResult.scanFile); 8429 } 8430 } 8431 } 8432 } 8433 8434 public static void reportSettingsProblem(int priority, String msg) { 8435 logCriticalInfo(priority, msg); 8436 } 8437 8438 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, 8439 boolean forceCollect, boolean skipVerify) throws PackageManagerException { 8440 // When upgrading from pre-N MR1, verify the package time stamp using the package 8441 // directory and not the APK file. 8442 final long lastModifiedTime = mIsPreNMR1Upgrade 8443 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg); 8444 if (ps != null && !forceCollect 8445 && ps.codePathString.equals(pkg.codePath) 8446 && ps.timeStamp == lastModifiedTime 8447 && !isCompatSignatureUpdateNeeded(pkg) 8448 && !isRecoverSignatureUpdateNeeded(pkg)) { 8449 if (ps.signatures.mSigningDetails.signatures != null 8450 && ps.signatures.mSigningDetails.signatures.length != 0 8451 && ps.signatures.mSigningDetails.signatureSchemeVersion 8452 != SignatureSchemeVersion.UNKNOWN) { 8453 // Optimization: reuse the existing cached signing data 8454 // if the package appears to be unchanged. 8455 pkg.mSigningDetails = 8456 new PackageParser.SigningDetails(ps.signatures.mSigningDetails); 8457 return; 8458 } 8459 8460 Slog.w(TAG, "PackageSetting for " + ps.name 8461 + " is missing signatures. Collecting certs again to recover them."); 8462 } else { 8463 Slog.i(TAG, pkg.codePath + " changed; collecting certs" + 8464 (forceCollect ? " (forced)" : "")); 8465 } 8466 8467 try { 8468 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8469 PackageParser.collectCertificates(pkg, skipVerify); 8470 } catch (PackageParserException e) { 8471 throw PackageManagerException.from(e); 8472 } finally { 8473 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8474 } 8475 } 8476 8477 /** 8478 * Traces a package scan. 8479 * @see #scanPackageLI(File, int, int, long, UserHandle) 8480 */ 8481 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8482 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8483 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8484 try { 8485 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8486 } finally { 8487 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8488 } 8489 } 8490 8491 /** 8492 * Scans a package and returns the newly parsed package. 8493 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8494 */ 8495 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8496 long currentTime, UserHandle user) throws PackageManagerException { 8497 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8498 PackageParser pp = new PackageParser(); 8499 pp.setSeparateProcesses(mSeparateProcesses); 8500 pp.setOnlyCoreApps(mOnlyCore); 8501 pp.setDisplayMetrics(mMetrics); 8502 pp.setCallback(mPackageParserCallback); 8503 8504 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8505 final PackageParser.Package pkg; 8506 try { 8507 pkg = pp.parsePackage(scanFile, parseFlags); 8508 } catch (PackageParserException e) { 8509 throw PackageManagerException.from(e); 8510 } finally { 8511 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8512 } 8513 8514 // Static shared libraries have synthetic package names 8515 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8516 renameStaticSharedLibraryPackage(pkg); 8517 } 8518 8519 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8520 } 8521 8522 /** 8523 * Scans a package and returns the newly parsed package. 8524 * @throws PackageManagerException on a parse error. 8525 */ 8526 private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg, 8527 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8528 @Nullable UserHandle user) 8529 throws PackageManagerException { 8530 // If the package has children and this is the first dive in the function 8531 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8532 // packages (parent and children) would be successfully scanned before the 8533 // actual scan since scanning mutates internal state and we want to atomically 8534 // install the package and its children. 8535 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8536 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8537 scanFlags |= SCAN_CHECK_ONLY; 8538 } 8539 } else { 8540 scanFlags &= ~SCAN_CHECK_ONLY; 8541 } 8542 8543 // Scan the parent 8544 PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags, 8545 scanFlags, currentTime, user); 8546 8547 // Scan the children 8548 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8549 for (int i = 0; i < childCount; i++) { 8550 PackageParser.Package childPackage = pkg.childPackages.get(i); 8551 addForInitLI(childPackage, parseFlags, scanFlags, 8552 currentTime, user); 8553 } 8554 8555 8556 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8557 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8558 } 8559 8560 return scannedPkg; 8561 } 8562 8563 /** 8564 * Returns if full apk verification can be skipped for the whole package, including the splits. 8565 */ 8566 private boolean canSkipFullPackageVerification(PackageParser.Package pkg) { 8567 if (!canSkipFullApkVerification(pkg.baseCodePath)) { 8568 return false; 8569 } 8570 // TODO: Allow base and splits to be verified individually. 8571 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8572 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8573 if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) { 8574 return false; 8575 } 8576 } 8577 } 8578 return true; 8579 } 8580 8581 /** 8582 * Returns if full apk verification can be skipped, depending on current FSVerity setup and 8583 * whether the apk contains signed root hash. Note that the signer's certificate still needs to 8584 * match one in a trusted source, and should be done separately. 8585 */ 8586 private boolean canSkipFullApkVerification(String apkPath) { 8587 byte[] rootHashObserved = null; 8588 try { 8589 rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath); 8590 if (rootHashObserved == null) { 8591 return false; // APK does not contain Merkle tree root hash. 8592 } 8593 synchronized (mInstallLock) { 8594 // Returns whether the observed root hash matches what kernel has. 8595 mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved); 8596 return true; 8597 } 8598 } catch (InstallerException | IOException | DigestException | 8599 NoSuchAlgorithmException e) { 8600 Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e); 8601 } 8602 return false; 8603 } 8604 8605 /** 8606 * Adds a new package to the internal data structures during platform initialization. 8607 * <p>After adding, the package is known to the system and available for querying. 8608 * <p>For packages located on the device ROM [eg. packages located in /system, /vendor, 8609 * etc...], additional checks are performed. Basic verification [such as ensuring 8610 * matching signatures, checking version codes, etc...] occurs if the package is 8611 * identical to a previously known package. If the package fails a signature check, 8612 * the version installed on /data will be removed. If the version of the new package 8613 * is less than or equal than the version on /data, it will be ignored. 8614 * <p>Regardless of the package location, the results are applied to the internal 8615 * structures and the package is made available to the rest of the system. 8616 * <p>NOTE: The return value should be removed. It's the passed in package object. 8617 */ 8618 private PackageParser.Package addForInitLI(PackageParser.Package pkg, 8619 @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8620 @Nullable UserHandle user) 8621 throws PackageManagerException { 8622 final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0; 8623 final String renamedPkgName; 8624 final PackageSetting disabledPkgSetting; 8625 final boolean isSystemPkgUpdated; 8626 final boolean pkgAlreadyExists; 8627 PackageSetting pkgSetting; 8628 8629 // NOTE: installPackageLI() has the same code to setup the package's 8630 // application info. This probably should be done lower in the call 8631 // stack [such as scanPackageOnly()]. However, we verify the application 8632 // info prior to that [in scanPackageNew()] and thus have to setup 8633 // the application info early. 8634 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8635 pkg.setApplicationInfoCodePath(pkg.codePath); 8636 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8637 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8638 pkg.setApplicationInfoResourcePath(pkg.codePath); 8639 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 8640 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8641 8642 synchronized (mPackages) { 8643 renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8644 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 8645 if (realPkgName != null) { 8646 ensurePackageRenamed(pkg, renamedPkgName); 8647 } 8648 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 8649 final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName); 8650 pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting; 8651 pkgAlreadyExists = pkgSetting != null; 8652 final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName; 8653 disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName); 8654 isSystemPkgUpdated = disabledPkgSetting != null; 8655 8656 if (DEBUG_INSTALL && isSystemPkgUpdated) { 8657 Slog.d(TAG, "updatedPkg = " + disabledPkgSetting); 8658 } 8659 8660 final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null) 8661 ? mSettings.getSharedUserLPw(pkg.mSharedUserId, 8662 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true) 8663 : null; 8664 if (DEBUG_PACKAGE_SCANNING 8665 && (parseFlags & PackageParser.PARSE_CHATTY) != 0 8666 && sharedUserSetting != null) { 8667 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 8668 + " (uid=" + sharedUserSetting.userId + "):" 8669 + " packages=" + sharedUserSetting.packages); 8670 } 8671 8672 if (scanSystemPartition) { 8673 // Potentially prune child packages. If the application on the /system 8674 // partition has been updated via OTA, but, is still disabled by a 8675 // version on /data, cycle through all of its children packages and 8676 // remove children that are no longer defined. 8677 if (isSystemPkgUpdated) { 8678 final int scannedChildCount = (pkg.childPackages != null) 8679 ? pkg.childPackages.size() : 0; 8680 final int disabledChildCount = disabledPkgSetting.childPackageNames != null 8681 ? disabledPkgSetting.childPackageNames.size() : 0; 8682 for (int i = 0; i < disabledChildCount; i++) { 8683 String disabledChildPackageName = 8684 disabledPkgSetting.childPackageNames.get(i); 8685 boolean disabledPackageAvailable = false; 8686 for (int j = 0; j < scannedChildCount; j++) { 8687 PackageParser.Package childPkg = pkg.childPackages.get(j); 8688 if (childPkg.packageName.equals(disabledChildPackageName)) { 8689 disabledPackageAvailable = true; 8690 break; 8691 } 8692 } 8693 if (!disabledPackageAvailable) { 8694 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8695 } 8696 } 8697 // we're updating the disabled package, so, scan it as the package setting 8698 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, 8699 disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */, 8700 null /* originalPkgSetting */, null, parseFlags, scanFlags, 8701 (pkg == mPlatformPackage), user); 8702 applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage); 8703 scanPackageOnlyLI(request, mFactoryTest, -1L); 8704 } 8705 } 8706 } 8707 8708 final boolean newPkgChangedPaths = 8709 pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath); 8710 final boolean newPkgVersionGreater = 8711 pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode; 8712 final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated 8713 && newPkgChangedPaths && newPkgVersionGreater; 8714 if (isSystemPkgBetter) { 8715 // The version of the application on /system is greater than the version on 8716 // /data. Switch back to the application on /system. 8717 // It's safe to assume the application on /system will correctly scan. If not, 8718 // there won't be a working copy of the application. 8719 synchronized (mPackages) { 8720 // just remove the loaded entries from package lists 8721 mPackages.remove(pkgSetting.name); 8722 } 8723 8724 logCriticalInfo(Log.WARN, 8725 "System package updated;" 8726 + " name: " + pkgSetting.name 8727 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8728 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8729 8730 final InstallArgs args = createInstallArgsForExisting( 8731 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8732 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8733 args.cleanUpResourcesLI(); 8734 synchronized (mPackages) { 8735 mSettings.enableSystemPackageLPw(pkgSetting.name); 8736 } 8737 } 8738 8739 if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) { 8740 // The version of the application on the /system partition is less than or 8741 // equal to the version on the /data partition. Throw an exception and use 8742 // the application already installed on the /data partition. 8743 throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at " 8744 + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode 8745 + " better than this " + pkg.getLongVersionCode()); 8746 } 8747 8748 // Verify certificates against what was last scanned. If it is an updated priv app, we will 8749 // force re-collecting certificate. 8750 final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced( 8751 disabledPkgSetting); 8752 // Full APK verification can be skipped during certificate collection, only if the file is 8753 // in verified partition, or can be verified on access (when apk verity is enabled). In both 8754 // cases, only data in Signing Block is verified instead of the whole file. 8755 final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) || 8756 (forceCollect && canSkipFullPackageVerification(pkg)); 8757 collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify); 8758 8759 boolean shouldHideSystemApp = false; 8760 // A new application appeared on /system, but, we already have a copy of 8761 // the application installed on /data. 8762 if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists 8763 && !pkgSetting.isSystem()) { 8764 8765 if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails, 8766 PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA) 8767 && !pkgSetting.signatures.mSigningDetails.checkCapability( 8768 pkg.mSigningDetails, 8769 PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) { 8770 logCriticalInfo(Log.WARN, 8771 "System package signature mismatch;" 8772 + " name: " + pkgSetting.name); 8773 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8774 "scanPackageInternalLI")) { 8775 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8776 } 8777 pkgSetting = null; 8778 } else if (newPkgVersionGreater) { 8779 // The application on /system is newer than the application on /data. 8780 // Simply remove the application on /data [keeping application data] 8781 // and replace it with the version on /system. 8782 logCriticalInfo(Log.WARN, 8783 "System package enabled;" 8784 + " name: " + pkgSetting.name 8785 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8786 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8787 InstallArgs args = createInstallArgsForExisting( 8788 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8789 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8790 synchronized (mInstallLock) { 8791 args.cleanUpResourcesLI(); 8792 } 8793 } else { 8794 // The application on /system is older than the application on /data. Hide 8795 // the application on /system and the version on /data will be scanned later 8796 // and re-added like an update. 8797 shouldHideSystemApp = true; 8798 logCriticalInfo(Log.INFO, 8799 "System package disabled;" 8800 + " name: " + pkgSetting.name 8801 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8802 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8803 } 8804 } 8805 8806 final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags 8807 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8808 8809 if (shouldHideSystemApp) { 8810 synchronized (mPackages) { 8811 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8812 } 8813 } 8814 return scannedPkg; 8815 } 8816 8817 private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8818 // Derive the new package synthetic package name 8819 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8820 + pkg.staticSharedLibVersion); 8821 } 8822 8823 private static String fixProcessName(String defProcessName, 8824 String processName) { 8825 if (processName == null) { 8826 return defProcessName; 8827 } 8828 return processName; 8829 } 8830 8831 /** 8832 * Enforces that only the system UID or root's UID can call a method exposed 8833 * via Binder. 8834 * 8835 * @param message used as message if SecurityException is thrown 8836 * @throws SecurityException if the caller is not system or root 8837 */ 8838 private static final void enforceSystemOrRoot(String message) { 8839 final int uid = Binder.getCallingUid(); 8840 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 8841 throw new SecurityException(message); 8842 } 8843 } 8844 8845 @Override 8846 public void performFstrimIfNeeded() { 8847 enforceSystemOrRoot("Only the system can request fstrim"); 8848 8849 // Before everything else, see whether we need to fstrim. 8850 try { 8851 IStorageManager sm = PackageHelper.getStorageManager(); 8852 if (sm != null) { 8853 boolean doTrim = false; 8854 final long interval = android.provider.Settings.Global.getLong( 8855 mContext.getContentResolver(), 8856 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8857 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8858 if (interval > 0) { 8859 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8860 if (timeSinceLast > interval) { 8861 doTrim = true; 8862 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8863 + "; running immediately"); 8864 } 8865 } 8866 if (doTrim) { 8867 final boolean dexOptDialogShown; 8868 synchronized (mPackages) { 8869 dexOptDialogShown = mDexOptDialogShown; 8870 } 8871 if (!isFirstBoot() && dexOptDialogShown) { 8872 try { 8873 ActivityManager.getService().showBootMessage( 8874 mContext.getResources().getString( 8875 R.string.android_upgrading_fstrim), true); 8876 } catch (RemoteException e) { 8877 } 8878 } 8879 sm.runMaintenance(); 8880 } 8881 } else { 8882 Slog.e(TAG, "storageManager service unavailable!"); 8883 } 8884 } catch (RemoteException e) { 8885 // Can't happen; StorageManagerService is local 8886 } 8887 } 8888 8889 @Override 8890 public void updatePackagesIfNeeded() { 8891 enforceSystemOrRoot("Only the system can request package update"); 8892 8893 // We need to re-extract after an OTA. 8894 boolean causeUpgrade = isUpgrade(); 8895 8896 // First boot or factory reset. 8897 // Note: we also handle devices that are upgrading to N right now as if it is their 8898 // first boot, as they do not have profile data. 8899 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8900 8901 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8902 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8903 8904 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8905 return; 8906 } 8907 8908 List<PackageParser.Package> pkgs; 8909 synchronized (mPackages) { 8910 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8911 } 8912 8913 final long startTime = System.nanoTime(); 8914 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8915 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 8916 false /* bootComplete */); 8917 8918 final int elapsedTimeSeconds = 8919 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8920 8921 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8922 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8923 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8924 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8925 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8926 } 8927 8928 /* 8929 * Return the prebuilt profile path given a package base code path. 8930 */ 8931 private static String getPrebuildProfilePath(PackageParser.Package pkg) { 8932 return pkg.baseCodePath + ".prof"; 8933 } 8934 8935 /** 8936 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8937 * containing statistics about the invocation. The array consists of three elements, 8938 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8939 * and {@code numberOfPackagesFailed}. 8940 */ 8941 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8942 final int compilationReason, boolean bootComplete) { 8943 8944 int numberOfPackagesVisited = 0; 8945 int numberOfPackagesOptimized = 0; 8946 int numberOfPackagesSkipped = 0; 8947 int numberOfPackagesFailed = 0; 8948 final int numberOfPackagesToDexopt = pkgs.size(); 8949 8950 for (PackageParser.Package pkg : pkgs) { 8951 numberOfPackagesVisited++; 8952 8953 boolean useProfileForDexopt = false; 8954 8955 if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) { 8956 // Copy over initial preopt profiles since we won't get any JIT samples for methods 8957 // that are already compiled. 8958 File profileFile = new File(getPrebuildProfilePath(pkg)); 8959 // Copy profile if it exists. 8960 if (profileFile.exists()) { 8961 try { 8962 // We could also do this lazily before calling dexopt in 8963 // PackageDexOptimizer to prevent this happening on first boot. The issue 8964 // is that we don't have a good way to say "do this only once". 8965 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8966 pkg.applicationInfo.uid, pkg.packageName, 8967 ArtManager.getProfileName(null))) { 8968 Log.e(TAG, "Installer failed to copy system profile!"); 8969 } else { 8970 // Disabled as this causes speed-profile compilation during first boot 8971 // even if things are already compiled. 8972 // useProfileForDexopt = true; 8973 } 8974 } catch (Exception e) { 8975 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", 8976 e); 8977 } 8978 } else { 8979 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8980 // Handle compressed APKs in this path. Only do this for stubs with profiles to 8981 // minimize the number off apps being speed-profile compiled during first boot. 8982 // The other paths will not change the filter. 8983 if (disabledPs != null && disabledPs.pkg.isStub) { 8984 // The package is the stub one, remove the stub suffix to get the normal 8985 // package and APK names. 8986 String systemProfilePath = 8987 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, ""); 8988 profileFile = new File(systemProfilePath); 8989 // If we have a profile for a compressed APK, copy it to the reference 8990 // location. 8991 // Note that copying the profile here will cause it to override the 8992 // reference profile every OTA even though the existing reference profile 8993 // may have more data. We can't copy during decompression since the 8994 // directories are not set up at that point. 8995 if (profileFile.exists()) { 8996 try { 8997 // We could also do this lazily before calling dexopt in 8998 // PackageDexOptimizer to prevent this happening on first boot. The 8999 // issue is that we don't have a good way to say "do this only 9000 // once". 9001 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 9002 pkg.applicationInfo.uid, pkg.packageName, 9003 ArtManager.getProfileName(null))) { 9004 Log.e(TAG, "Failed to copy system profile for stub package!"); 9005 } else { 9006 useProfileForDexopt = true; 9007 } 9008 } catch (Exception e) { 9009 Log.e(TAG, "Failed to copy profile " + 9010 profileFile.getAbsolutePath() + " ", e); 9011 } 9012 } 9013 } 9014 } 9015 } 9016 9017 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 9018 if (DEBUG_DEXOPT) { 9019 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 9020 } 9021 numberOfPackagesSkipped++; 9022 continue; 9023 } 9024 9025 if (DEBUG_DEXOPT) { 9026 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 9027 numberOfPackagesToDexopt + ": " + pkg.packageName); 9028 } 9029 9030 if (showDialog) { 9031 try { 9032 ActivityManager.getService().showBootMessage( 9033 mContext.getResources().getString(R.string.android_upgrading_apk, 9034 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 9035 } catch (RemoteException e) { 9036 } 9037 synchronized (mPackages) { 9038 mDexOptDialogShown = true; 9039 } 9040 } 9041 9042 int pkgCompilationReason = compilationReason; 9043 if (useProfileForDexopt) { 9044 // Use background dexopt mode to try and use the profile. Note that this does not 9045 // guarantee usage of the profile. 9046 pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT; 9047 } 9048 9049 // checkProfiles is false to avoid merging profiles during boot which 9050 // might interfere with background compilation (b/28612421). 9051 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 9052 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 9053 // trade-off worth doing to save boot time work. 9054 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0; 9055 if (compilationReason == REASON_FIRST_BOOT) { 9056 // TODO: This doesn't cover the upgrade case, we should check for this too. 9057 dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE; 9058 } 9059 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions( 9060 pkg.packageName, 9061 pkgCompilationReason, 9062 dexoptFlags)); 9063 9064 switch (primaryDexOptStaus) { 9065 case PackageDexOptimizer.DEX_OPT_PERFORMED: 9066 numberOfPackagesOptimized++; 9067 break; 9068 case PackageDexOptimizer.DEX_OPT_SKIPPED: 9069 numberOfPackagesSkipped++; 9070 break; 9071 case PackageDexOptimizer.DEX_OPT_FAILED: 9072 numberOfPackagesFailed++; 9073 break; 9074 default: 9075 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus); 9076 break; 9077 } 9078 } 9079 9080 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 9081 numberOfPackagesFailed }; 9082 } 9083 9084 @Override 9085 public void notifyPackageUse(String packageName, int reason) { 9086 synchronized (mPackages) { 9087 final int callingUid = Binder.getCallingUid(); 9088 final int callingUserId = UserHandle.getUserId(callingUid); 9089 if (getInstantAppPackageName(callingUid) != null) { 9090 if (!isCallerSameApp(packageName, callingUid)) { 9091 return; 9092 } 9093 } else { 9094 if (isInstantApp(packageName, callingUserId)) { 9095 return; 9096 } 9097 } 9098 notifyPackageUseLocked(packageName, reason); 9099 } 9100 } 9101 9102 @GuardedBy("mPackages") 9103 private void notifyPackageUseLocked(String packageName, int reason) { 9104 final PackageParser.Package p = mPackages.get(packageName); 9105 if (p == null) { 9106 return; 9107 } 9108 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 9109 } 9110 9111 @Override 9112 public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames, 9113 List<String> classPaths, String loaderIsa) { 9114 int userId = UserHandle.getCallingUserId(); 9115 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 9116 if (ai == null) { 9117 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 9118 + loadingPackageName + ", user=" + userId); 9119 return; 9120 } 9121 mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId); 9122 } 9123 9124 @Override 9125 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule, 9126 IDexModuleRegisterCallback callback) { 9127 int userId = UserHandle.getCallingUserId(); 9128 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId); 9129 DexManager.RegisterDexModuleResult result; 9130 if (ai == null) { 9131 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" + 9132 " calling user. package=" + packageName + ", user=" + userId); 9133 result = new DexManager.RegisterDexModuleResult(false, "Package not installed"); 9134 } else { 9135 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId); 9136 } 9137 9138 if (callback != null) { 9139 mHandler.post(() -> { 9140 try { 9141 callback.onDexModuleRegistered(dexModulePath, result.success, result.message); 9142 } catch (RemoteException e) { 9143 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e); 9144 } 9145 }); 9146 } 9147 } 9148 9149 /** 9150 * Ask the package manager to perform a dex-opt with the given compiler filter. 9151 * 9152 * Note: exposed only for the shell command to allow moving packages explicitly to a 9153 * definite state. 9154 */ 9155 @Override 9156 public boolean performDexOptMode(String packageName, 9157 boolean checkProfiles, String targetCompilerFilter, boolean force, 9158 boolean bootComplete, String splitName) { 9159 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) | 9160 (force ? DexoptOptions.DEXOPT_FORCE : 0) | 9161 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0); 9162 return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN, 9163 targetCompilerFilter, splitName, flags)); 9164 } 9165 9166 /** 9167 * Ask the package manager to perform a dex-opt with the given compiler filter on the 9168 * secondary dex files belonging to the given package. 9169 * 9170 * Note: exposed only for the shell command to allow moving packages explicitly to a 9171 * definite state. 9172 */ 9173 @Override 9174 public boolean performDexOptSecondary(String packageName, String compilerFilter, 9175 boolean force) { 9176 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX | 9177 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES | 9178 DexoptOptions.DEXOPT_BOOT_COMPLETE | 9179 (force ? DexoptOptions.DEXOPT_FORCE : 0); 9180 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags)); 9181 } 9182 9183 /*package*/ boolean performDexOpt(DexoptOptions options) { 9184 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9185 return false; 9186 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) { 9187 return false; 9188 } 9189 9190 if (options.isDexoptOnlySecondaryDex()) { 9191 return mDexManager.dexoptSecondaryDex(options); 9192 } else { 9193 int dexoptStatus = performDexOptWithStatus(options); 9194 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9195 } 9196 } 9197 9198 /** 9199 * Perform dexopt on the given package and return one of following result: 9200 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9201 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9202 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9203 */ 9204 /* package */ int performDexOptWithStatus(DexoptOptions options) { 9205 return performDexOptTraced(options); 9206 } 9207 9208 private int performDexOptTraced(DexoptOptions options) { 9209 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9210 try { 9211 return performDexOptInternal(options); 9212 } finally { 9213 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9214 } 9215 } 9216 9217 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9218 // if the package can now be considered up to date for the given filter. 9219 private int performDexOptInternal(DexoptOptions options) { 9220 PackageParser.Package p; 9221 synchronized (mPackages) { 9222 p = mPackages.get(options.getPackageName()); 9223 if (p == null) { 9224 // Package could not be found. Report failure. 9225 return PackageDexOptimizer.DEX_OPT_FAILED; 9226 } 9227 mPackageUsage.maybeWriteAsync(mPackages); 9228 mCompilerStats.maybeWriteAsync(); 9229 } 9230 long callingId = Binder.clearCallingIdentity(); 9231 try { 9232 synchronized (mInstallLock) { 9233 return performDexOptInternalWithDependenciesLI(p, options); 9234 } 9235 } finally { 9236 Binder.restoreCallingIdentity(callingId); 9237 } 9238 } 9239 9240 public ArraySet<String> getOptimizablePackages() { 9241 ArraySet<String> pkgs = new ArraySet<String>(); 9242 synchronized (mPackages) { 9243 for (PackageParser.Package p : mPackages.values()) { 9244 if (PackageDexOptimizer.canOptimizePackage(p)) { 9245 pkgs.add(p.packageName); 9246 } 9247 } 9248 } 9249 return pkgs; 9250 } 9251 9252 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9253 DexoptOptions options) { 9254 // Select the dex optimizer based on the force parameter. 9255 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9256 // allocate an object here. 9257 PackageDexOptimizer pdo = options.isForce() 9258 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9259 : mPackageDexOptimizer; 9260 9261 // Dexopt all dependencies first. Note: we ignore the return value and march on 9262 // on errors. 9263 // Note that we are going to call performDexOpt on those libraries as many times as 9264 // they are referenced in packages. When we do a batch of performDexOpt (for example 9265 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9266 // and the first package that uses the library will dexopt it. The 9267 // others will see that the compiled code for the library is up to date. 9268 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 9269 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9270 if (!deps.isEmpty()) { 9271 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(), 9272 options.getCompilationReason(), options.getCompilerFilter(), 9273 options.getSplitName(), 9274 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY); 9275 for (PackageParser.Package depPackage : deps) { 9276 // TODO: Analyze and investigate if we (should) profile libraries. 9277 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 9278 getOrCreateCompilerPackageStats(depPackage), 9279 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions); 9280 } 9281 } 9282 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, 9283 getOrCreateCompilerPackageStats(p), 9284 mDexManager.getPackageUseInfoOrDefault(p.packageName), options); 9285 } 9286 9287 /** 9288 * Reconcile the information we have about the secondary dex files belonging to 9289 * {@code packagName} and the actual dex files. For all dex files that were 9290 * deleted, update the internal records and delete the generated oat files. 9291 */ 9292 @Override 9293 public void reconcileSecondaryDexFiles(String packageName) { 9294 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9295 return; 9296 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9297 return; 9298 } 9299 mDexManager.reconcileSecondaryDexFiles(packageName); 9300 } 9301 9302 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 9303 // a reference there. 9304 /*package*/ DexManager getDexManager() { 9305 return mDexManager; 9306 } 9307 9308 /** 9309 * Execute the background dexopt job immediately. 9310 */ 9311 @Override 9312 public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) { 9313 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9314 return false; 9315 } 9316 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames); 9317 } 9318 9319 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 9320 if (p.usesLibraries != null || p.usesOptionalLibraries != null 9321 || p.usesStaticLibraries != null) { 9322 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 9323 Set<String> collectedNames = new HashSet<>(); 9324 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 9325 9326 retValue.remove(p); 9327 9328 return retValue; 9329 } else { 9330 return Collections.emptyList(); 9331 } 9332 } 9333 9334 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 9335 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9336 if (!collectedNames.contains(p.packageName)) { 9337 collectedNames.add(p.packageName); 9338 collected.add(p); 9339 9340 if (p.usesLibraries != null) { 9341 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 9342 null, collected, collectedNames); 9343 } 9344 if (p.usesOptionalLibraries != null) { 9345 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 9346 null, collected, collectedNames); 9347 } 9348 if (p.usesStaticLibraries != null) { 9349 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 9350 p.usesStaticLibrariesVersions, collected, collectedNames); 9351 } 9352 } 9353 } 9354 9355 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions, 9356 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9357 final int libNameCount = libs.size(); 9358 for (int i = 0; i < libNameCount; i++) { 9359 String libName = libs.get(i); 9360 long version = (versions != null && versions.length == libNameCount) 9361 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 9362 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 9363 if (libPkg != null) { 9364 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 9365 } 9366 } 9367 } 9368 9369 private PackageParser.Package findSharedNonSystemLibrary(String name, long version) { 9370 synchronized (mPackages) { 9371 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 9372 if (libEntry != null) { 9373 return mPackages.get(libEntry.apk); 9374 } 9375 return null; 9376 } 9377 } 9378 9379 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) { 9380 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9381 if (versionedLib == null) { 9382 return null; 9383 } 9384 return versionedLib.get(version); 9385 } 9386 9387 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9388 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9389 pkg.staticSharedLibName); 9390 if (versionedLib == null) { 9391 return null; 9392 } 9393 long previousLibVersion = -1; 9394 final int versionCount = versionedLib.size(); 9395 for (int i = 0; i < versionCount; i++) { 9396 final long libVersion = versionedLib.keyAt(i); 9397 if (libVersion < pkg.staticSharedLibVersion) { 9398 previousLibVersion = Math.max(previousLibVersion, libVersion); 9399 } 9400 } 9401 if (previousLibVersion >= 0) { 9402 return versionedLib.get(previousLibVersion); 9403 } 9404 return null; 9405 } 9406 9407 public void shutdown() { 9408 mPackageUsage.writeNow(mPackages); 9409 mCompilerStats.writeNow(); 9410 mDexManager.writePackageDexUsageNow(); 9411 } 9412 9413 @Override 9414 public void dumpProfiles(String packageName) { 9415 PackageParser.Package pkg; 9416 synchronized (mPackages) { 9417 pkg = mPackages.get(packageName); 9418 if (pkg == null) { 9419 throw new IllegalArgumentException("Unknown package: " + packageName); 9420 } 9421 } 9422 /* Only the shell, root, or the app user should be able to dump profiles. */ 9423 int callingUid = Binder.getCallingUid(); 9424 if (callingUid != Process.SHELL_UID && 9425 callingUid != Process.ROOT_UID && 9426 callingUid != pkg.applicationInfo.uid) { 9427 throw new SecurityException("dumpProfiles"); 9428 } 9429 9430 synchronized (mInstallLock) { 9431 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9432 mArtManagerService.dumpProfiles(pkg); 9433 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9434 } 9435 } 9436 9437 @Override 9438 public void forceDexOpt(String packageName) { 9439 enforceSystemOrRoot("forceDexOpt"); 9440 9441 PackageParser.Package pkg; 9442 synchronized (mPackages) { 9443 pkg = mPackages.get(packageName); 9444 if (pkg == null) { 9445 throw new IllegalArgumentException("Unknown package: " + packageName); 9446 } 9447 } 9448 9449 synchronized (mInstallLock) { 9450 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9451 9452 // Whoever is calling forceDexOpt wants a compiled package. 9453 // Don't use profiles since that may cause compilation to be skipped. 9454 final int res = performDexOptInternalWithDependenciesLI( 9455 pkg, 9456 new DexoptOptions(packageName, 9457 getDefaultCompilerFilter(), 9458 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE)); 9459 9460 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9461 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9462 throw new IllegalStateException("Failed to dexopt: " + res); 9463 } 9464 } 9465 } 9466 9467 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9468 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9469 Slog.w(TAG, "Unable to update from " + oldPkg.name 9470 + " to " + newPkg.packageName 9471 + ": old package not in system partition"); 9472 return false; 9473 } else if (mPackages.get(oldPkg.name) != null) { 9474 Slog.w(TAG, "Unable to update from " + oldPkg.name 9475 + " to " + newPkg.packageName 9476 + ": old package still exists"); 9477 return false; 9478 } 9479 return true; 9480 } 9481 9482 void removeCodePathLI(File codePath) { 9483 if (codePath.isDirectory()) { 9484 try { 9485 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9486 } catch (InstallerException e) { 9487 Slog.w(TAG, "Failed to remove code path", e); 9488 } 9489 } else { 9490 codePath.delete(); 9491 } 9492 } 9493 9494 private int[] resolveUserIds(int userId) { 9495 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9496 } 9497 9498 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9499 if (pkg == null) { 9500 Slog.wtf(TAG, "Package was null!", new Throwable()); 9501 return; 9502 } 9503 clearAppDataLeafLIF(pkg, userId, flags); 9504 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9505 for (int i = 0; i < childCount; i++) { 9506 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9507 } 9508 9509 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 9510 } 9511 9512 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9513 final PackageSetting ps; 9514 synchronized (mPackages) { 9515 ps = mSettings.mPackages.get(pkg.packageName); 9516 } 9517 for (int realUserId : resolveUserIds(userId)) { 9518 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9519 try { 9520 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9521 ceDataInode); 9522 } catch (InstallerException e) { 9523 Slog.w(TAG, String.valueOf(e)); 9524 } 9525 } 9526 } 9527 9528 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9529 if (pkg == null) { 9530 Slog.wtf(TAG, "Package was null!", new Throwable()); 9531 return; 9532 } 9533 destroyAppDataLeafLIF(pkg, userId, flags); 9534 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9535 for (int i = 0; i < childCount; i++) { 9536 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9537 } 9538 } 9539 9540 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9541 final PackageSetting ps; 9542 synchronized (mPackages) { 9543 ps = mSettings.mPackages.get(pkg.packageName); 9544 } 9545 for (int realUserId : resolveUserIds(userId)) { 9546 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9547 try { 9548 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9549 ceDataInode); 9550 } catch (InstallerException e) { 9551 Slog.w(TAG, String.valueOf(e)); 9552 } 9553 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9554 } 9555 } 9556 9557 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9558 if (pkg == null) { 9559 Slog.wtf(TAG, "Package was null!", new Throwable()); 9560 return; 9561 } 9562 destroyAppProfilesLeafLIF(pkg); 9563 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9564 for (int i = 0; i < childCount; i++) { 9565 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9566 } 9567 } 9568 9569 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9570 try { 9571 mInstaller.destroyAppProfiles(pkg.packageName); 9572 } catch (InstallerException e) { 9573 Slog.w(TAG, String.valueOf(e)); 9574 } 9575 } 9576 9577 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9578 if (pkg == null) { 9579 Slog.wtf(TAG, "Package was null!", new Throwable()); 9580 return; 9581 } 9582 mArtManagerService.clearAppProfiles(pkg); 9583 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9584 for (int i = 0; i < childCount; i++) { 9585 mArtManagerService.clearAppProfiles(pkg.childPackages.get(i)); 9586 } 9587 } 9588 9589 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9590 long lastUpdateTime) { 9591 // Set parent install/update time 9592 PackageSetting ps = (PackageSetting) pkg.mExtras; 9593 if (ps != null) { 9594 ps.firstInstallTime = firstInstallTime; 9595 ps.lastUpdateTime = lastUpdateTime; 9596 } 9597 // Set children install/update time 9598 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9599 for (int i = 0; i < childCount; i++) { 9600 PackageParser.Package childPkg = pkg.childPackages.get(i); 9601 ps = (PackageSetting) childPkg.mExtras; 9602 if (ps != null) { 9603 ps.firstInstallTime = firstInstallTime; 9604 ps.lastUpdateTime = lastUpdateTime; 9605 } 9606 } 9607 } 9608 9609 private void addSharedLibraryLPr(Set<String> usesLibraryFiles, 9610 SharedLibraryEntry file, 9611 PackageParser.Package changingLib) { 9612 if (file.path != null) { 9613 usesLibraryFiles.add(file.path); 9614 return; 9615 } 9616 PackageParser.Package p = mPackages.get(file.apk); 9617 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9618 // If we are doing this while in the middle of updating a library apk, 9619 // then we need to make sure to use that new apk for determining the 9620 // dependencies here. (We haven't yet finished committing the new apk 9621 // to the package manager state.) 9622 if (p == null || p.packageName.equals(changingLib.packageName)) { 9623 p = changingLib; 9624 } 9625 } 9626 if (p != null) { 9627 usesLibraryFiles.addAll(p.getAllCodePaths()); 9628 if (p.usesLibraryFiles != null) { 9629 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 9630 } 9631 } 9632 } 9633 9634 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9635 PackageParser.Package changingLib) throws PackageManagerException { 9636 if (pkg == null) { 9637 return; 9638 } 9639 // The collection used here must maintain the order of addition (so 9640 // that libraries are searched in the correct order) and must have no 9641 // duplicates. 9642 Set<String> usesLibraryFiles = null; 9643 if (pkg.usesLibraries != null) { 9644 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9645 null, null, pkg.packageName, changingLib, true, 9646 pkg.applicationInfo.targetSdkVersion, null); 9647 } 9648 if (pkg.usesStaticLibraries != null) { 9649 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9650 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9651 pkg.packageName, changingLib, true, 9652 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9653 } 9654 if (pkg.usesOptionalLibraries != null) { 9655 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9656 null, null, pkg.packageName, changingLib, false, 9657 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9658 } 9659 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9660 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9661 } else { 9662 pkg.usesLibraryFiles = null; 9663 } 9664 } 9665 9666 private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9667 @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests, 9668 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9669 boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries) 9670 throws PackageManagerException { 9671 final int libCount = requestedLibraries.size(); 9672 for (int i = 0; i < libCount; i++) { 9673 final String libName = requestedLibraries.get(i); 9674 final long libVersion = requiredVersions != null ? requiredVersions[i] 9675 : SharedLibraryInfo.VERSION_UNDEFINED; 9676 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9677 if (libEntry == null) { 9678 if (required) { 9679 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9680 "Package " + packageName + " requires unavailable shared library " 9681 + libName + "; failing!"); 9682 } else if (DEBUG_SHARED_LIBRARIES) { 9683 Slog.i(TAG, "Package " + packageName 9684 + " desires unavailable shared library " 9685 + libName + "; ignoring!"); 9686 } 9687 } else { 9688 if (requiredVersions != null && requiredCertDigests != null) { 9689 if (libEntry.info.getLongVersion() != requiredVersions[i]) { 9690 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9691 "Package " + packageName + " requires unavailable static shared" 9692 + " library " + libName + " version " 9693 + libEntry.info.getLongVersion() + "; failing!"); 9694 } 9695 9696 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9697 if (libPkg == null) { 9698 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9699 "Package " + packageName + " requires unavailable static shared" 9700 + " library; failing!"); 9701 } 9702 9703 final String[] expectedCertDigests = requiredCertDigests[i]; 9704 9705 9706 if (expectedCertDigests.length > 1) { 9707 9708 // For apps targeting O MR1 we require explicit enumeration of all certs. 9709 final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O) 9710 ? PackageUtils.computeSignaturesSha256Digests( 9711 libPkg.mSigningDetails.signatures) 9712 : PackageUtils.computeSignaturesSha256Digests( 9713 new Signature[]{libPkg.mSigningDetails.signatures[0]}); 9714 9715 // Take a shortcut if sizes don't match. Note that if an app doesn't 9716 // target O we don't parse the "additional-certificate" tags similarly 9717 // how we only consider all certs only for apps targeting O (see above). 9718 // Therefore, the size check is safe to make. 9719 if (expectedCertDigests.length != libCertDigests.length) { 9720 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9721 "Package " + packageName + " requires differently signed" + 9722 " static shared library; failing!"); 9723 } 9724 9725 // Use a predictable order as signature order may vary 9726 Arrays.sort(libCertDigests); 9727 Arrays.sort(expectedCertDigests); 9728 9729 final int certCount = libCertDigests.length; 9730 for (int j = 0; j < certCount; j++) { 9731 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) { 9732 throw new PackageManagerException( 9733 INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9734 "Package " + packageName + " requires differently signed" + 9735 " static shared library; failing!"); 9736 } 9737 } 9738 } else { 9739 9740 // lib signing cert could have rotated beyond the one expected, check to see 9741 // if the new one has been blessed by the old 9742 if (!libPkg.mSigningDetails.hasSha256Certificate( 9743 ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) { 9744 throw new PackageManagerException( 9745 INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9746 "Package " + packageName + " requires differently signed" + 9747 " static shared library; failing!"); 9748 } 9749 } 9750 } 9751 9752 if (outUsedLibraries == null) { 9753 // Use LinkedHashSet to preserve the order of files added to 9754 // usesLibraryFiles while eliminating duplicates. 9755 outUsedLibraries = new LinkedHashSet<>(); 9756 } 9757 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9758 } 9759 } 9760 return outUsedLibraries; 9761 } 9762 9763 private static boolean hasString(List<String> list, List<String> which) { 9764 if (list == null) { 9765 return false; 9766 } 9767 for (int i=list.size()-1; i>=0; i--) { 9768 for (int j=which.size()-1; j>=0; j--) { 9769 if (which.get(j).equals(list.get(i))) { 9770 return true; 9771 } 9772 } 9773 } 9774 return false; 9775 } 9776 9777 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9778 PackageParser.Package changingPkg) { 9779 ArrayList<PackageParser.Package> res = null; 9780 for (PackageParser.Package pkg : mPackages.values()) { 9781 if (changingPkg != null 9782 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9783 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9784 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9785 changingPkg.staticSharedLibName)) { 9786 return null; 9787 } 9788 if (res == null) { 9789 res = new ArrayList<>(); 9790 } 9791 res.add(pkg); 9792 try { 9793 updateSharedLibrariesLPr(pkg, changingPkg); 9794 } catch (PackageManagerException e) { 9795 // If a system app update or an app and a required lib missing we 9796 // delete the package and for updated system apps keep the data as 9797 // it is better for the user to reinstall than to be in an limbo 9798 // state. Also libs disappearing under an app should never happen 9799 // - just in case. 9800 if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) { 9801 final int flags = pkg.isUpdatedSystemApp() 9802 ? PackageManager.DELETE_KEEP_DATA : 0; 9803 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9804 flags , null, true, null); 9805 } 9806 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9807 } 9808 } 9809 return res; 9810 } 9811 9812 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9813 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9814 @Nullable UserHandle user) throws PackageManagerException { 9815 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9816 // If the package has children and this is the first dive in the function 9817 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9818 // whether all packages (parent and children) would be successfully scanned 9819 // before the actual scan since scanning mutates internal state and we want 9820 // to atomically install the package and its children. 9821 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9822 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9823 scanFlags |= SCAN_CHECK_ONLY; 9824 } 9825 } else { 9826 scanFlags &= ~SCAN_CHECK_ONLY; 9827 } 9828 9829 final PackageParser.Package scannedPkg; 9830 try { 9831 // Scan the parent 9832 scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user); 9833 // Scan the children 9834 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9835 for (int i = 0; i < childCount; i++) { 9836 PackageParser.Package childPkg = pkg.childPackages.get(i); 9837 scanPackageNewLI(childPkg, parseFlags, 9838 scanFlags, currentTime, user); 9839 } 9840 } finally { 9841 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9842 } 9843 9844 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9845 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 9846 } 9847 9848 return scannedPkg; 9849 } 9850 9851 /** The result of a package scan. */ 9852 private static class ScanResult { 9853 /** Whether or not the package scan was successful */ 9854 public final boolean success; 9855 /** 9856 * The final package settings. This may be the same object passed in 9857 * the {@link ScanRequest}, but, with modified values. 9858 */ 9859 @Nullable public final PackageSetting pkgSetting; 9860 /** ABI code paths that have changed in the package scan */ 9861 @Nullable public final List<String> changedAbiCodePath; 9862 public ScanResult( 9863 boolean success, 9864 @Nullable PackageSetting pkgSetting, 9865 @Nullable List<String> changedAbiCodePath) { 9866 this.success = success; 9867 this.pkgSetting = pkgSetting; 9868 this.changedAbiCodePath = changedAbiCodePath; 9869 } 9870 } 9871 9872 /** A package to be scanned */ 9873 private static class ScanRequest { 9874 /** The parsed package */ 9875 @NonNull public final PackageParser.Package pkg; 9876 /** Shared user settings, if the package has a shared user */ 9877 @Nullable public final SharedUserSetting sharedUserSetting; 9878 /** 9879 * Package settings of the currently installed version. 9880 * <p><em>IMPORTANT:</em> The contents of this object may be modified 9881 * during scan. 9882 */ 9883 @Nullable public final PackageSetting pkgSetting; 9884 /** A copy of the settings for the currently installed version */ 9885 @Nullable public final PackageSetting oldPkgSetting; 9886 /** Package settings for the disabled version on the /system partition */ 9887 @Nullable public final PackageSetting disabledPkgSetting; 9888 /** Package settings for the installed version under its original package name */ 9889 @Nullable public final PackageSetting originalPkgSetting; 9890 /** The real package name of a renamed application */ 9891 @Nullable public final String realPkgName; 9892 public final @ParseFlags int parseFlags; 9893 public final @ScanFlags int scanFlags; 9894 /** The user for which the package is being scanned */ 9895 @Nullable public final UserHandle user; 9896 /** Whether or not the platform package is being scanned */ 9897 public final boolean isPlatformPackage; 9898 public ScanRequest( 9899 @NonNull PackageParser.Package pkg, 9900 @Nullable SharedUserSetting sharedUserSetting, 9901 @Nullable PackageSetting pkgSetting, 9902 @Nullable PackageSetting disabledPkgSetting, 9903 @Nullable PackageSetting originalPkgSetting, 9904 @Nullable String realPkgName, 9905 @ParseFlags int parseFlags, 9906 @ScanFlags int scanFlags, 9907 boolean isPlatformPackage, 9908 @Nullable UserHandle user) { 9909 this.pkg = pkg; 9910 this.pkgSetting = pkgSetting; 9911 this.sharedUserSetting = sharedUserSetting; 9912 this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting); 9913 this.disabledPkgSetting = disabledPkgSetting; 9914 this.originalPkgSetting = originalPkgSetting; 9915 this.realPkgName = realPkgName; 9916 this.parseFlags = parseFlags; 9917 this.scanFlags = scanFlags; 9918 this.isPlatformPackage = isPlatformPackage; 9919 this.user = user; 9920 } 9921 } 9922 9923 /** 9924 * Returns the actual scan flags depending upon the state of the other settings. 9925 * <p>Updated system applications will not have the following flags set 9926 * by default and need to be adjusted after the fact: 9927 * <ul> 9928 * <li>{@link #SCAN_AS_SYSTEM}</li> 9929 * <li>{@link #SCAN_AS_PRIVILEGED}</li> 9930 * <li>{@link #SCAN_AS_OEM}</li> 9931 * <li>{@link #SCAN_AS_VENDOR}</li> 9932 * <li>{@link #SCAN_AS_PRODUCT}</li> 9933 * <li>{@link #SCAN_AS_INSTANT_APP}</li> 9934 * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li> 9935 * </ul> 9936 */ 9937 private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags, 9938 PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user, 9939 PackageParser.Package pkg) { 9940 if (disabledPkgSetting != null) { 9941 // updated system application, must at least have SCAN_AS_SYSTEM 9942 scanFlags |= SCAN_AS_SYSTEM; 9943 if ((disabledPkgSetting.pkgPrivateFlags 9944 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 9945 scanFlags |= SCAN_AS_PRIVILEGED; 9946 } 9947 if ((disabledPkgSetting.pkgPrivateFlags 9948 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) { 9949 scanFlags |= SCAN_AS_OEM; 9950 } 9951 if ((disabledPkgSetting.pkgPrivateFlags 9952 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) { 9953 scanFlags |= SCAN_AS_VENDOR; 9954 } 9955 if ((disabledPkgSetting.pkgPrivateFlags 9956 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) { 9957 scanFlags |= SCAN_AS_PRODUCT; 9958 } 9959 } 9960 if (pkgSetting != null) { 9961 final int userId = ((user == null) ? 0 : user.getIdentifier()); 9962 if (pkgSetting.getInstantApp(userId)) { 9963 scanFlags |= SCAN_AS_INSTANT_APP; 9964 } 9965 if (pkgSetting.getVirtulalPreload(userId)) { 9966 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 9967 } 9968 } 9969 9970 // Scan as privileged apps that share a user with a priv-app. 9971 if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged() 9972 && (pkg.mSharedUserId != null)) { 9973 SharedUserSetting sharedUserSetting = null; 9974 try { 9975 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 9976 } catch (PackageManagerException ignore) {} 9977 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 9978 // Exempt SharedUsers signed with the platform key. 9979 // TODO(b/72378145) Fix this exemption. Force signature apps 9980 // to whitelist their privileged permissions just like other 9981 // priv-apps. 9982 synchronized (mPackages) { 9983 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 9984 if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures, 9985 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) { 9986 scanFlags |= SCAN_AS_PRIVILEGED; 9987 } 9988 } 9989 } 9990 } 9991 9992 return scanFlags; 9993 } 9994 9995 // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting 9996 // the results / removing app data needs to be moved up a level to the callers of this 9997 // method. Also, we need to solve the problem of potentially creating a new shared user 9998 // setting. That can probably be done later and patch things up after the fact. 9999 @GuardedBy("mInstallLock") 10000 private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg, 10001 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 10002 @Nullable UserHandle user) throws PackageManagerException { 10003 10004 final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 10005 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 10006 if (realPkgName != null) { 10007 ensurePackageRenamed(pkg, renamedPkgName); 10008 } 10009 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 10010 final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName); 10011 final PackageSetting disabledPkgSetting = 10012 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 10013 10014 if (mTransferedPackages.contains(pkg.packageName)) { 10015 Slog.w(TAG, "Package " + pkg.packageName 10016 + " was transferred to another, but its .apk remains"); 10017 } 10018 10019 scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg); 10020 synchronized (mPackages) { 10021 applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage); 10022 assertPackageIsValid(pkg, parseFlags, scanFlags); 10023 10024 SharedUserSetting sharedUserSetting = null; 10025 if (pkg.mSharedUserId != null) { 10026 // SIDE EFFECTS; may potentially allocate a new shared user 10027 sharedUserSetting = mSettings.getSharedUserLPw( 10028 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 10029 if (DEBUG_PACKAGE_SCANNING) { 10030 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10031 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 10032 + " (uid=" + sharedUserSetting.userId + "):" 10033 + " packages=" + sharedUserSetting.packages); 10034 } 10035 } 10036 10037 boolean scanSucceeded = false; 10038 try { 10039 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting, 10040 disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags, 10041 (pkg == mPlatformPackage), user); 10042 final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime); 10043 if (result.success) { 10044 commitScanResultsLocked(request, result); 10045 } 10046 scanSucceeded = true; 10047 } finally { 10048 if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 10049 // DELETE_DATA_ON_FAILURES is only used by frozen paths 10050 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 10051 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 10052 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 10053 } 10054 } 10055 } 10056 return pkg; 10057 } 10058 10059 /** 10060 * Commits the package scan and modifies system state. 10061 * <p><em>WARNING:</em> The method may throw an excpetion in the middle 10062 * of committing the package, leaving the system in an inconsistent state. 10063 * This needs to be fixed so, once we get to this point, no errors are 10064 * possible and the system is not left in an inconsistent state. 10065 */ 10066 @GuardedBy("mPackages") 10067 private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result) 10068 throws PackageManagerException { 10069 final PackageParser.Package pkg = request.pkg; 10070 final @ParseFlags int parseFlags = request.parseFlags; 10071 final @ScanFlags int scanFlags = request.scanFlags; 10072 final PackageSetting oldPkgSetting = request.oldPkgSetting; 10073 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10074 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10075 final UserHandle user = request.user; 10076 final String realPkgName = request.realPkgName; 10077 final PackageSetting pkgSetting = result.pkgSetting; 10078 final List<String> changedAbiCodePath = result.changedAbiCodePath; 10079 final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting); 10080 10081 if (newPkgSettingCreated) { 10082 if (originalPkgSetting != null) { 10083 mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name); 10084 } 10085 // THROWS: when we can't allocate a user id. add call to check if there's 10086 // enough space to ensure we won't throw; otherwise, don't modify state 10087 mSettings.addUserToSettingLPw(pkgSetting); 10088 10089 if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) { 10090 mTransferedPackages.add(originalPkgSetting.name); 10091 } 10092 } 10093 // TODO(toddke): Consider a method specifically for modifying the Package object 10094 // post scan; or, moving this stuff out of the Package object since it has nothing 10095 // to do with the package on disk. 10096 // We need to have this here because addUserToSettingLPw() is sometimes responsible 10097 // for creating the application ID. If we did this earlier, we would be saving the 10098 // correct ID. 10099 pkg.applicationInfo.uid = pkgSetting.appId; 10100 10101 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 10102 10103 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) { 10104 mTransferedPackages.add(pkg.packageName); 10105 } 10106 10107 // THROWS: when requested libraries that can't be found. it only changes 10108 // the state of the passed in pkg object, so, move to the top of the method 10109 // and allow it to abort 10110 if ((scanFlags & SCAN_BOOTING) == 0 10111 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10112 // Check all shared libraries and map to their actual file path. 10113 // We only do this here for apps not on a system dir, because those 10114 // are the only ones that can fail an install due to this. We 10115 // will take care of the system apps by updating all of their 10116 // library paths after the scan is done. Also during the initial 10117 // scan don't update any libs as we do this wholesale after all 10118 // apps are scanned to avoid dependency based scanning. 10119 updateSharedLibrariesLPr(pkg, null); 10120 } 10121 10122 // All versions of a static shared library are referenced with the same 10123 // package name. Internally, we use a synthetic package name to allow 10124 // multiple versions of the same shared library to be installed. So, 10125 // we need to generate the synthetic package name of the latest shared 10126 // library in order to compare signatures. 10127 PackageSetting signatureCheckPs = pkgSetting; 10128 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10129 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 10130 if (libraryEntry != null) { 10131 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 10132 } 10133 } 10134 10135 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10136 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 10137 if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 10138 // We just determined the app is signed correctly, so bring 10139 // over the latest parsed certs. 10140 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10141 } else { 10142 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10143 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10144 "Package " + pkg.packageName + " upgrade keys do not match the " 10145 + "previously installed version"); 10146 } else { 10147 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10148 String msg = "System package " + pkg.packageName 10149 + " signature changed; retaining data."; 10150 reportSettingsProblem(Log.WARN, msg); 10151 } 10152 } 10153 } else { 10154 try { 10155 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 10156 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 10157 final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting, 10158 pkg.mSigningDetails, compareCompat, compareRecover); 10159 // The new KeySets will be re-added later in the scanning process. 10160 if (compatMatch) { 10161 synchronized (mPackages) { 10162 ksms.removeAppKeySetDataLPw(pkg.packageName); 10163 } 10164 } 10165 // We just determined the app is signed correctly, so bring 10166 // over the latest parsed certs. 10167 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10168 10169 10170 // if this is is a sharedUser, check to see if the new package is signed by a newer 10171 // signing certificate than the existing one, and if so, copy over the new details 10172 if (signatureCheckPs.sharedUser != null 10173 && pkg.mSigningDetails.hasAncestor( 10174 signatureCheckPs.sharedUser.signatures.mSigningDetails)) { 10175 signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails; 10176 } 10177 } catch (PackageManagerException e) { 10178 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10179 throw e; 10180 } 10181 // The signature has changed, but this package is in the system 10182 // image... let's recover! 10183 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10184 // However... if this package is part of a shared user, but it 10185 // doesn't match the signature of the shared user, let's fail. 10186 // What this means is that you can't change the signatures 10187 // associated with an overall shared user, which doesn't seem all 10188 // that unreasonable. 10189 if (signatureCheckPs.sharedUser != null) { 10190 if (compareSignatures( 10191 signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures, 10192 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) { 10193 throw new PackageManagerException( 10194 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10195 "Signature mismatch for shared user: " 10196 + pkgSetting.sharedUser); 10197 } 10198 } 10199 // File a report about this. 10200 String msg = "System package " + pkg.packageName 10201 + " signature changed; retaining data."; 10202 reportSettingsProblem(Log.WARN, msg); 10203 } catch (IllegalArgumentException e) { 10204 10205 // should never happen: certs matched when checking, but not when comparing 10206 // old to new for sharedUser 10207 throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10208 "Signing certificates comparison made on incomparable signing details" 10209 + " but somehow passed verifySignatures!"); 10210 } 10211 } 10212 10213 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 10214 // This package wants to adopt ownership of permissions from 10215 // another package. 10216 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 10217 final String origName = pkg.mAdoptPermissions.get(i); 10218 final PackageSetting orig = mSettings.getPackageLPr(origName); 10219 if (orig != null) { 10220 if (verifyPackageUpdateLPr(orig, pkg)) { 10221 Slog.i(TAG, "Adopting permissions from " + origName + " to " 10222 + pkg.packageName); 10223 mSettings.mPermissions.transferPermissions(origName, pkg.packageName); 10224 } 10225 } 10226 } 10227 } 10228 10229 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 10230 for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) { 10231 final String codePathString = changedAbiCodePath.get(i); 10232 try { 10233 mInstaller.rmdex(codePathString, 10234 getDexCodeInstructionSet(getPreferredInstructionSet())); 10235 } catch (InstallerException ignored) { 10236 } 10237 } 10238 } 10239 10240 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10241 if (oldPkgSetting != null) { 10242 synchronized (mPackages) { 10243 mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting); 10244 } 10245 } 10246 } else { 10247 final int userId = user == null ? 0 : user.getIdentifier(); 10248 // Modify state for the given package setting 10249 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 10250 (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 10251 if (pkgSetting.getInstantApp(userId)) { 10252 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 10253 } 10254 } 10255 } 10256 10257 /** 10258 * Returns the "real" name of the package. 10259 * <p>This may differ from the package's actual name if the application has already 10260 * been installed under one of this package's original names. 10261 */ 10262 private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg, 10263 @Nullable String renamedPkgName) { 10264 if (isPackageRenamed(pkg, renamedPkgName)) { 10265 return pkg.mRealPackage; 10266 } 10267 return null; 10268 } 10269 10270 /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */ 10271 private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg, 10272 @Nullable String renamedPkgName) { 10273 return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName); 10274 } 10275 10276 /** 10277 * Returns the original package setting. 10278 * <p>A package can migrate its name during an update. In this scenario, a package 10279 * designates a set of names that it considers as one of its original names. 10280 * <p>An original package must be signed identically and it must have the same 10281 * shared user [if any]. 10282 */ 10283 @GuardedBy("mPackages") 10284 private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg, 10285 @Nullable String renamedPkgName) { 10286 if (!isPackageRenamed(pkg, renamedPkgName)) { 10287 return null; 10288 } 10289 for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) { 10290 final PackageSetting originalPs = 10291 mSettings.getPackageLPr(pkg.mOriginalPackages.get(i)); 10292 if (originalPs != null) { 10293 // the package is already installed under its original name... 10294 // but, should we use it? 10295 if (!verifyPackageUpdateLPr(originalPs, pkg)) { 10296 // the new package is incompatible with the original 10297 continue; 10298 } else if (originalPs.sharedUser != null) { 10299 if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) { 10300 // the shared user id is incompatible with the original 10301 Slog.w(TAG, "Unable to migrate data from " + originalPs.name 10302 + " to " + pkg.packageName + ": old uid " 10303 + originalPs.sharedUser.name 10304 + " differs from " + pkg.mSharedUserId); 10305 continue; 10306 } 10307 // TODO: Add case when shared user id is added [b/28144775] 10308 } else { 10309 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 10310 + pkg.packageName + " to old name " + originalPs.name); 10311 } 10312 return originalPs; 10313 } 10314 } 10315 return null; 10316 } 10317 10318 /** 10319 * Renames the package if it was installed under a different name. 10320 * <p>When we've already installed the package under an original name, update 10321 * the new package so we can continue to have the old name. 10322 */ 10323 private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg, 10324 @NonNull String renamedPackageName) { 10325 if (pkg.mOriginalPackages == null 10326 || !pkg.mOriginalPackages.contains(renamedPackageName) 10327 || pkg.packageName.equals(renamedPackageName)) { 10328 return; 10329 } 10330 pkg.setPackageName(renamedPackageName); 10331 } 10332 10333 /** 10334 * Just scans the package without any side effects. 10335 * <p>Not entirely true at the moment. There is still one side effect -- this 10336 * method potentially modifies a live {@link PackageSetting} object representing 10337 * the package being scanned. This will be resolved in the future. 10338 * 10339 * @param request Information about the package to be scanned 10340 * @param isUnderFactoryTest Whether or not the device is under factory test 10341 * @param currentTime The current time, in millis 10342 * @return The results of the scan 10343 */ 10344 @GuardedBy("mInstallLock") 10345 private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request, 10346 boolean isUnderFactoryTest, long currentTime) 10347 throws PackageManagerException { 10348 final PackageParser.Package pkg = request.pkg; 10349 PackageSetting pkgSetting = request.pkgSetting; 10350 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10351 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10352 final @ParseFlags int parseFlags = request.parseFlags; 10353 final @ScanFlags int scanFlags = request.scanFlags; 10354 final String realPkgName = request.realPkgName; 10355 final SharedUserSetting sharedUserSetting = request.sharedUserSetting; 10356 final UserHandle user = request.user; 10357 final boolean isPlatformPackage = request.isPlatformPackage; 10358 10359 List<String> changedAbiCodePath = null; 10360 10361 if (DEBUG_PACKAGE_SCANNING) { 10362 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10363 Log.d(TAG, "Scanning package " + pkg.packageName); 10364 } 10365 10366 if (Build.IS_DEBUGGABLE && 10367 pkg.isPrivileged() && 10368 SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) { 10369 PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg); 10370 } 10371 10372 // Initialize package source and resource directories 10373 final File scanFile = new File(pkg.codePath); 10374 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 10375 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 10376 10377 // We keep references to the derived CPU Abis from settings in oder to reuse 10378 // them in the case where we're not upgrading or booting for the first time. 10379 String primaryCpuAbiFromSettings = null; 10380 String secondaryCpuAbiFromSettings = null; 10381 boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0; 10382 10383 if (!needToDeriveAbi) { 10384 if (pkgSetting != null) { 10385 primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString; 10386 secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString; 10387 } else { 10388 // Re-scanning a system package after uninstalling updates; need to derive ABI 10389 needToDeriveAbi = true; 10390 } 10391 } 10392 10393 if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) { 10394 PackageManagerService.reportSettingsProblem(Log.WARN, 10395 "Package " + pkg.packageName + " shared user changed from " 10396 + (pkgSetting.sharedUser != null 10397 ? pkgSetting.sharedUser.name : "<nothing>") 10398 + " to " 10399 + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>") 10400 + "; replacing with new"); 10401 pkgSetting = null; 10402 } 10403 10404 String[] usesStaticLibraries = null; 10405 if (pkg.usesStaticLibraries != null) { 10406 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 10407 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 10408 } 10409 final boolean createNewPackage = (pkgSetting == null); 10410 if (createNewPackage) { 10411 final String parentPackageName = (pkg.parentPackage != null) 10412 ? pkg.parentPackage.packageName : null; 10413 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10414 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0; 10415 // REMOVE SharedUserSetting from method; update in a separate call 10416 pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting, 10417 disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile, 10418 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 10419 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10420 pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10421 user, true /*allowInstall*/, instantApp, virtualPreload, 10422 parentPackageName, pkg.getChildPackageNames(), 10423 UserManagerService.getInstance(), usesStaticLibraries, 10424 pkg.usesStaticLibrariesVersions); 10425 } else { 10426 // REMOVE SharedUserSetting from method; update in a separate call. 10427 // 10428 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 10429 // secondaryCpuAbi are not known at this point so we always update them 10430 // to null here, only to reset them at a later point. 10431 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting, 10432 destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir, 10433 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10434 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10435 pkg.getChildPackageNames(), UserManagerService.getInstance(), 10436 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 10437 } 10438 if (createNewPackage && originalPkgSetting != null) { 10439 // This is the initial transition from the original package, so, 10440 // fix up the new package's name now. We must do this after looking 10441 // up the package under its new name, so getPackageLP takes care of 10442 // fiddling things correctly. 10443 pkg.setPackageName(originalPkgSetting.name); 10444 10445 // File a report about this. 10446 String msg = "New package " + pkgSetting.realName 10447 + " renamed to replace old package " + pkgSetting.name; 10448 reportSettingsProblem(Log.WARN, msg); 10449 } 10450 10451 final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier()); 10452 // for existing packages, change the install state; but, only if it's explicitly specified 10453 if (!createNewPackage) { 10454 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10455 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 10456 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 10457 } 10458 10459 if (disabledPkgSetting != null) { 10460 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10461 } 10462 10463 // Apps which share a sharedUserId must be placed in the same selinux domain. If this 10464 // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its 10465 // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be 10466 // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the 10467 // least restrictive selinux domain. 10468 // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion 10469 // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This 10470 // ensures that all packages continue to run in the same selinux domain. 10471 final int targetSdkVersion = 10472 ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ? 10473 sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion; 10474 // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync. 10475 // They currently can be if the sharedUser apps are signed with the platform key. 10476 final boolean isPrivileged = (sharedUserSetting != null) ? 10477 sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged(); 10478 10479 pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged, 10480 pkg.applicationInfo.targetSandboxVersion, targetSdkVersion); 10481 pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState( 10482 userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId)); 10483 10484 pkg.mExtras = pkgSetting; 10485 pkg.applicationInfo.processName = fixProcessName( 10486 pkg.applicationInfo.packageName, 10487 pkg.applicationInfo.processName); 10488 10489 if (!isPlatformPackage) { 10490 // Get all of our default paths setup 10491 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 10492 } 10493 10494 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 10495 10496 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 10497 if (needToDeriveAbi) { 10498 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 10499 final boolean extractNativeLibs = !pkg.isLibrary(); 10500 derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs); 10501 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10502 10503 // Some system apps still use directory structure for native libraries 10504 // in which case we might end up not detecting abi solely based on apk 10505 // structure. Try to detect abi based on directory structure. 10506 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 10507 pkg.applicationInfo.primaryCpuAbi == null) { 10508 setBundledAppAbisAndRoots(pkg, pkgSetting); 10509 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10510 } 10511 } else { 10512 // This is not a first boot or an upgrade, don't bother deriving the 10513 // ABI during the scan. Instead, trust the value that was stored in the 10514 // package setting. 10515 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 10516 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 10517 10518 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10519 10520 if (DEBUG_ABI_SELECTION) { 10521 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 10522 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 10523 pkg.applicationInfo.secondaryCpuAbi); 10524 } 10525 } 10526 } else { 10527 if ((scanFlags & SCAN_MOVE) != 0) { 10528 // We haven't run dex-opt for this move (since we've moved the compiled output too) 10529 // but we already have this packages package info in the PackageSetting. We just 10530 // use that and derive the native library path based on the new codepath. 10531 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 10532 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 10533 } 10534 10535 // Set native library paths again. For moves, the path will be updated based on the 10536 // ABIs we've determined above. For non-moves, the path will be updated based on the 10537 // ABIs we determined during compilation, but the path will depend on the final 10538 // package path (after the rename away from the stage path). 10539 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10540 } 10541 10542 // This is a special case for the "system" package, where the ABI is 10543 // dictated by the zygote configuration (and init.rc). We should keep track 10544 // of this ABI so that we can deal with "normal" applications that run under 10545 // the same UID correctly. 10546 if (isPlatformPackage) { 10547 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 10548 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 10549 } 10550 10551 // If there's a mismatch between the abi-override in the package setting 10552 // and the abiOverride specified for the install. Warn about this because we 10553 // would've already compiled the app without taking the package setting into 10554 // account. 10555 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 10556 if (cpuAbiOverride == null && pkg.packageName != null) { 10557 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 10558 " for package " + pkg.packageName); 10559 } 10560 } 10561 10562 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10563 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10564 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 10565 10566 // Copy the derived override back to the parsed package, so that we can 10567 // update the package settings accordingly. 10568 pkg.cpuAbiOverride = cpuAbiOverride; 10569 10570 if (DEBUG_ABI_SELECTION) { 10571 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName 10572 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 10573 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 10574 } 10575 10576 // Push the derived path down into PackageSettings so we know what to 10577 // clean up at uninstall time. 10578 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 10579 10580 if (DEBUG_ABI_SELECTION) { 10581 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 10582 " primary=" + pkg.applicationInfo.primaryCpuAbi + 10583 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 10584 } 10585 10586 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 10587 // We don't do this here during boot because we can do it all 10588 // at once after scanning all existing packages. 10589 // 10590 // We also do this *before* we perform dexopt on this package, so that 10591 // we can avoid redundant dexopts, and also to make sure we've got the 10592 // code and package path correct. 10593 changedAbiCodePath = 10594 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 10595 } 10596 10597 if (isUnderFactoryTest && pkg.requestedPermissions.contains( 10598 android.Manifest.permission.FACTORY_TEST)) { 10599 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 10600 } 10601 10602 if (isSystemApp(pkg)) { 10603 pkgSetting.isOrphaned = true; 10604 } 10605 10606 // Take care of first install / last update times. 10607 final long scanFileTime = getLastModifiedTime(pkg); 10608 if (currentTime != 0) { 10609 if (pkgSetting.firstInstallTime == 0) { 10610 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 10611 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 10612 pkgSetting.lastUpdateTime = currentTime; 10613 } 10614 } else if (pkgSetting.firstInstallTime == 0) { 10615 // We need *something*. Take time time stamp of the file. 10616 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 10617 } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 10618 if (scanFileTime != pkgSetting.timeStamp) { 10619 // A package on the system image has changed; consider this 10620 // to be an update. 10621 pkgSetting.lastUpdateTime = scanFileTime; 10622 } 10623 } 10624 pkgSetting.setTimeStamp(scanFileTime); 10625 10626 pkgSetting.pkg = pkg; 10627 pkgSetting.pkgFlags = pkg.applicationInfo.flags; 10628 if (pkg.getLongVersionCode() != pkgSetting.versionCode) { 10629 pkgSetting.versionCode = pkg.getLongVersionCode(); 10630 } 10631 // Update volume if needed 10632 final String volumeUuid = pkg.applicationInfo.volumeUuid; 10633 if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) { 10634 Slog.i(PackageManagerService.TAG, 10635 "Update" + (pkgSetting.isSystem() ? " system" : "") 10636 + " package " + pkg.packageName 10637 + " volume from " + pkgSetting.volumeUuid 10638 + " to " + volumeUuid); 10639 pkgSetting.volumeUuid = volumeUuid; 10640 } 10641 10642 return new ScanResult(true, pkgSetting, changedAbiCodePath); 10643 } 10644 10645 /** 10646 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 10647 */ 10648 private static boolean apkHasCode(String fileName) { 10649 StrictJarFile jarFile = null; 10650 try { 10651 jarFile = new StrictJarFile(fileName, 10652 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 10653 return jarFile.findEntry("classes.dex") != null; 10654 } catch (IOException ignore) { 10655 } finally { 10656 try { 10657 if (jarFile != null) { 10658 jarFile.close(); 10659 } 10660 } catch (IOException ignore) {} 10661 } 10662 return false; 10663 } 10664 10665 /** 10666 * Enforces code policy for the package. This ensures that if an APK has 10667 * declared hasCode="true" in its manifest that the APK actually contains 10668 * code. 10669 * 10670 * @throws PackageManagerException If bytecode could not be found when it should exist 10671 */ 10672 private static void assertCodePolicy(PackageParser.Package pkg) 10673 throws PackageManagerException { 10674 final boolean shouldHaveCode = 10675 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 10676 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 10677 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10678 "Package " + pkg.baseCodePath + " code is missing"); 10679 } 10680 10681 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 10682 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 10683 final boolean splitShouldHaveCode = 10684 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 10685 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 10686 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10687 "Package " + pkg.splitCodePaths[i] + " code is missing"); 10688 } 10689 } 10690 } 10691 } 10692 10693 /** 10694 * Applies policy to the parsed package based upon the given policy flags. 10695 * Ensures the package is in a good state. 10696 * <p> 10697 * Implementation detail: This method must NOT have any side effect. It would 10698 * ideally be static, but, it requires locks to read system state. 10699 */ 10700 private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10701 final @ScanFlags int scanFlags, PackageParser.Package platformPkg) { 10702 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 10703 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 10704 if (pkg.applicationInfo.isDirectBootAware()) { 10705 // we're direct boot aware; set for all components 10706 for (PackageParser.Service s : pkg.services) { 10707 s.info.encryptionAware = s.info.directBootAware = true; 10708 } 10709 for (PackageParser.Provider p : pkg.providers) { 10710 p.info.encryptionAware = p.info.directBootAware = true; 10711 } 10712 for (PackageParser.Activity a : pkg.activities) { 10713 a.info.encryptionAware = a.info.directBootAware = true; 10714 } 10715 for (PackageParser.Activity r : pkg.receivers) { 10716 r.info.encryptionAware = r.info.directBootAware = true; 10717 } 10718 } 10719 if (compressedFileExists(pkg.codePath)) { 10720 pkg.isStub = true; 10721 } 10722 } else { 10723 // non system apps can't be flagged as core 10724 pkg.coreApp = false; 10725 // clear flags not applicable to regular apps 10726 pkg.applicationInfo.flags &= 10727 ~ApplicationInfo.FLAG_PERSISTENT; 10728 pkg.applicationInfo.privateFlags &= 10729 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10730 pkg.applicationInfo.privateFlags &= 10731 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10732 // cap permission priorities 10733 if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) { 10734 for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) { 10735 pkg.permissionGroups.get(i).info.priority = 0; 10736 } 10737 } 10738 } 10739 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10740 // clear protected broadcasts 10741 pkg.protectedBroadcasts = null; 10742 // ignore export request for single user receivers 10743 if (pkg.receivers != null) { 10744 for (int i = pkg.receivers.size() - 1; i >= 0; --i) { 10745 final PackageParser.Activity receiver = pkg.receivers.get(i); 10746 if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 10747 receiver.info.exported = false; 10748 } 10749 } 10750 } 10751 // ignore export request for single user services 10752 if (pkg.services != null) { 10753 for (int i = pkg.services.size() - 1; i >= 0; --i) { 10754 final PackageParser.Service service = pkg.services.get(i); 10755 if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 10756 service.info.exported = false; 10757 } 10758 } 10759 } 10760 // ignore export request for single user providers 10761 if (pkg.providers != null) { 10762 for (int i = pkg.providers.size() - 1; i >= 0; --i) { 10763 final PackageParser.Provider provider = pkg.providers.get(i); 10764 if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) { 10765 provider.info.exported = false; 10766 } 10767 } 10768 } 10769 } 10770 10771 if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) { 10772 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10773 } 10774 10775 if ((scanFlags & SCAN_AS_OEM) != 0) { 10776 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 10777 } 10778 10779 if ((scanFlags & SCAN_AS_VENDOR) != 0) { 10780 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR; 10781 } 10782 10783 if ((scanFlags & SCAN_AS_PRODUCT) != 0) { 10784 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT; 10785 } 10786 10787 // Check if the package is signed with the same key as the platform package. 10788 if (PLATFORM_PACKAGE_NAME.equals(pkg.packageName) || 10789 (platformPkg != null && compareSignatures( 10790 platformPkg.mSigningDetails.signatures, 10791 pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH)) { 10792 pkg.applicationInfo.privateFlags |= 10793 ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY; 10794 } 10795 10796 if (!isSystemApp(pkg)) { 10797 // Only system apps can use these features. 10798 pkg.mOriginalPackages = null; 10799 pkg.mRealPackage = null; 10800 pkg.mAdoptPermissions = null; 10801 } 10802 } 10803 10804 private static @NonNull <T> T assertNotNull(@Nullable T object, String message) 10805 throws PackageManagerException { 10806 if (object == null) { 10807 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message); 10808 } 10809 return object; 10810 } 10811 10812 /** 10813 * Asserts the parsed package is valid according to the given policy. If the 10814 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10815 * <p> 10816 * Implementation detail: This method must NOT have any side effects. It would 10817 * ideally be static, but, it requires locks to read system state. 10818 * 10819 * @throws PackageManagerException If the package fails any of the validation checks 10820 */ 10821 private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10822 final @ScanFlags int scanFlags) 10823 throws PackageManagerException { 10824 if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10825 assertCodePolicy(pkg); 10826 } 10827 10828 if (pkg.applicationInfo.getCodePath() == null || 10829 pkg.applicationInfo.getResourcePath() == null) { 10830 // Bail out. The resource and code paths haven't been set. 10831 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10832 "Code and resource paths haven't been set correctly"); 10833 } 10834 10835 // Make sure we're not adding any bogus keyset info 10836 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10837 ksms.assertScannedPackageValid(pkg); 10838 10839 synchronized (mPackages) { 10840 // The special "android" package can only be defined once 10841 if (pkg.packageName.equals("android")) { 10842 if (mAndroidApplication != null) { 10843 Slog.w(TAG, "*************************************************"); 10844 Slog.w(TAG, "Core android package being redefined. Skipping."); 10845 Slog.w(TAG, " codePath=" + pkg.codePath); 10846 Slog.w(TAG, "*************************************************"); 10847 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10848 "Core android package being redefined. Skipping."); 10849 } 10850 } 10851 10852 // A package name must be unique; don't allow duplicates 10853 if (mPackages.containsKey(pkg.packageName)) { 10854 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10855 "Application package " + pkg.packageName 10856 + " already installed. Skipping duplicate."); 10857 } 10858 10859 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10860 // Static libs have a synthetic package name containing the version 10861 // but we still want the base name to be unique. 10862 if (mPackages.containsKey(pkg.manifestPackageName)) { 10863 throw new PackageManagerException( 10864 "Duplicate static shared lib provider package"); 10865 } 10866 10867 // Static shared libraries should have at least O target SDK 10868 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10869 throw new PackageManagerException( 10870 "Packages declaring static-shared libs must target O SDK or higher"); 10871 } 10872 10873 // Package declaring static a shared lib cannot be instant apps 10874 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10875 throw new PackageManagerException( 10876 "Packages declaring static-shared libs cannot be instant apps"); 10877 } 10878 10879 // Package declaring static a shared lib cannot be renamed since the package 10880 // name is synthetic and apps can't code around package manager internals. 10881 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10882 throw new PackageManagerException( 10883 "Packages declaring static-shared libs cannot be renamed"); 10884 } 10885 10886 // Package declaring static a shared lib cannot declare child packages 10887 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10888 throw new PackageManagerException( 10889 "Packages declaring static-shared libs cannot have child packages"); 10890 } 10891 10892 // Package declaring static a shared lib cannot declare dynamic libs 10893 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10894 throw new PackageManagerException( 10895 "Packages declaring static-shared libs cannot declare dynamic libs"); 10896 } 10897 10898 // Package declaring static a shared lib cannot declare shared users 10899 if (pkg.mSharedUserId != null) { 10900 throw new PackageManagerException( 10901 "Packages declaring static-shared libs cannot declare shared users"); 10902 } 10903 10904 // Static shared libs cannot declare activities 10905 if (!pkg.activities.isEmpty()) { 10906 throw new PackageManagerException( 10907 "Static shared libs cannot declare activities"); 10908 } 10909 10910 // Static shared libs cannot declare services 10911 if (!pkg.services.isEmpty()) { 10912 throw new PackageManagerException( 10913 "Static shared libs cannot declare services"); 10914 } 10915 10916 // Static shared libs cannot declare providers 10917 if (!pkg.providers.isEmpty()) { 10918 throw new PackageManagerException( 10919 "Static shared libs cannot declare content providers"); 10920 } 10921 10922 // Static shared libs cannot declare receivers 10923 if (!pkg.receivers.isEmpty()) { 10924 throw new PackageManagerException( 10925 "Static shared libs cannot declare broadcast receivers"); 10926 } 10927 10928 // Static shared libs cannot declare permission groups 10929 if (!pkg.permissionGroups.isEmpty()) { 10930 throw new PackageManagerException( 10931 "Static shared libs cannot declare permission groups"); 10932 } 10933 10934 // Static shared libs cannot declare permissions 10935 if (!pkg.permissions.isEmpty()) { 10936 throw new PackageManagerException( 10937 "Static shared libs cannot declare permissions"); 10938 } 10939 10940 // Static shared libs cannot declare protected broadcasts 10941 if (pkg.protectedBroadcasts != null) { 10942 throw new PackageManagerException( 10943 "Static shared libs cannot declare protected broadcasts"); 10944 } 10945 10946 // Static shared libs cannot be overlay targets 10947 if (pkg.mOverlayTarget != null) { 10948 throw new PackageManagerException( 10949 "Static shared libs cannot be overlay targets"); 10950 } 10951 10952 // The version codes must be ordered as lib versions 10953 long minVersionCode = Long.MIN_VALUE; 10954 long maxVersionCode = Long.MAX_VALUE; 10955 10956 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10957 pkg.staticSharedLibName); 10958 if (versionedLib != null) { 10959 final int versionCount = versionedLib.size(); 10960 for (int i = 0; i < versionCount; i++) { 10961 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10962 final long libVersionCode = libInfo.getDeclaringPackage() 10963 .getLongVersionCode(); 10964 if (libInfo.getLongVersion() < pkg.staticSharedLibVersion) { 10965 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10966 } else if (libInfo.getLongVersion() > pkg.staticSharedLibVersion) { 10967 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10968 } else { 10969 minVersionCode = maxVersionCode = libVersionCode; 10970 break; 10971 } 10972 } 10973 } 10974 if (pkg.getLongVersionCode() < minVersionCode 10975 || pkg.getLongVersionCode() > maxVersionCode) { 10976 throw new PackageManagerException("Static shared" 10977 + " lib version codes must be ordered as lib versions"); 10978 } 10979 } 10980 10981 // Only privileged apps and updated privileged apps can add child packages. 10982 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10983 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10984 throw new PackageManagerException("Only privileged apps can add child " 10985 + "packages. Ignoring package " + pkg.packageName); 10986 } 10987 final int childCount = pkg.childPackages.size(); 10988 for (int i = 0; i < childCount; i++) { 10989 PackageParser.Package childPkg = pkg.childPackages.get(i); 10990 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10991 childPkg.packageName)) { 10992 throw new PackageManagerException("Can't override child of " 10993 + "another disabled app. Ignoring package " + pkg.packageName); 10994 } 10995 } 10996 } 10997 10998 // If we're only installing presumed-existing packages, require that the 10999 // scanned APK is both already known and at the path previously established 11000 // for it. Previously unknown packages we pick up normally, but if we have an 11001 // a priori expectation about this package's install presence, enforce it. 11002 // With a singular exception for new system packages. When an OTA contains 11003 // a new system package, we allow the codepath to change from a system location 11004 // to the user-installed location. If we don't allow this change, any newer, 11005 // user-installed version of the application will be ignored. 11006 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 11007 if (mExpectingBetter.containsKey(pkg.packageName)) { 11008 logCriticalInfo(Log.WARN, 11009 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 11010 } else { 11011 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 11012 if (known != null) { 11013 if (DEBUG_PACKAGE_SCANNING) { 11014 Log.d(TAG, "Examining " + pkg.codePath 11015 + " and requiring known paths " + known.codePathString 11016 + " & " + known.resourcePathString); 11017 } 11018 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 11019 || !pkg.applicationInfo.getResourcePath().equals( 11020 known.resourcePathString)) { 11021 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 11022 "Application package " + pkg.packageName 11023 + " found at " + pkg.applicationInfo.getCodePath() 11024 + " but expected at " + known.codePathString 11025 + "; ignoring."); 11026 } 11027 } else { 11028 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11029 "Application package " + pkg.packageName 11030 + " not found; ignoring."); 11031 } 11032 } 11033 } 11034 11035 // Verify that this new package doesn't have any content providers 11036 // that conflict with existing packages. Only do this if the 11037 // package isn't already installed, since we don't want to break 11038 // things that are installed. 11039 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 11040 final int N = pkg.providers.size(); 11041 int i; 11042 for (i=0; i<N; i++) { 11043 PackageParser.Provider p = pkg.providers.get(i); 11044 if (p.info.authority != null) { 11045 String names[] = p.info.authority.split(";"); 11046 for (int j = 0; j < names.length; j++) { 11047 if (mProvidersByAuthority.containsKey(names[j])) { 11048 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11049 final String otherPackageName = 11050 ((other != null && other.getComponentName() != null) ? 11051 other.getComponentName().getPackageName() : "?"); 11052 throw new PackageManagerException( 11053 INSTALL_FAILED_CONFLICTING_PROVIDER, 11054 "Can't install because provider name " + names[j] 11055 + " (in package " + pkg.applicationInfo.packageName 11056 + ") is already used by " + otherPackageName); 11057 } 11058 } 11059 } 11060 } 11061 } 11062 11063 // Verify that packages sharing a user with a privileged app are marked as privileged. 11064 if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) { 11065 SharedUserSetting sharedUserSetting = null; 11066 try { 11067 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 11068 } catch (PackageManagerException ignore) {} 11069 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 11070 // Exempt SharedUsers signed with the platform key. 11071 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 11072 if ((platformPkgSetting.signatures.mSigningDetails 11073 != PackageParser.SigningDetails.UNKNOWN) 11074 && (compareSignatures( 11075 platformPkgSetting.signatures.mSigningDetails.signatures, 11076 pkg.mSigningDetails.signatures) 11077 != PackageManager.SIGNATURE_MATCH)) { 11078 throw new PackageManagerException("Apps that share a user with a " + 11079 "privileged app must themselves be marked as privileged. " + 11080 pkg.packageName + " shares privileged user " + 11081 pkg.mSharedUserId + "."); 11082 } 11083 } 11084 } 11085 11086 // Apply policies specific for runtime resource overlays (RROs). 11087 if (pkg.mOverlayTarget != null) { 11088 // System overlays have some restrictions on their use of the 'static' state. 11089 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 11090 // We are scanning a system overlay. This can be the first scan of the 11091 // system/vendor/oem partition, or an update to the system overlay. 11092 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 11093 // This must be an update to a system overlay. 11094 final PackageSetting previousPkg = assertNotNull( 11095 mSettings.getPackageLPr(pkg.packageName), 11096 "previous package state not present"); 11097 11098 // Static overlays cannot be updated. 11099 if (previousPkg.pkg.mOverlayIsStatic) { 11100 throw new PackageManagerException("Overlay " + pkg.packageName + 11101 " is static and cannot be upgraded."); 11102 // Non-static overlays cannot be converted to static overlays. 11103 } else if (pkg.mOverlayIsStatic) { 11104 throw new PackageManagerException("Overlay " + pkg.packageName + 11105 " cannot be upgraded into a static overlay."); 11106 } 11107 } 11108 } else { 11109 // The overlay is a non-system overlay. Non-system overlays cannot be static. 11110 if (pkg.mOverlayIsStatic) { 11111 throw new PackageManagerException("Overlay " + pkg.packageName + 11112 " is static but not pre-installed."); 11113 } 11114 11115 // The only case where we allow installation of a non-system overlay is when 11116 // its signature is signed with the platform certificate. 11117 PackageSetting platformPkgSetting = mSettings.getPackageLPr("android"); 11118 if ((platformPkgSetting.signatures.mSigningDetails 11119 != PackageParser.SigningDetails.UNKNOWN) 11120 && (compareSignatures( 11121 platformPkgSetting.signatures.mSigningDetails.signatures, 11122 pkg.mSigningDetails.signatures) 11123 != PackageManager.SIGNATURE_MATCH)) { 11124 throw new PackageManagerException("Overlay " + pkg.packageName + 11125 " must be signed with the platform certificate."); 11126 } 11127 } 11128 } 11129 } 11130 } 11131 11132 private boolean addSharedLibraryLPw(String path, String apk, String name, long version, 11133 int type, String declaringPackageName, long declaringVersionCode) { 11134 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11135 if (versionedLib == null) { 11136 versionedLib = new LongSparseArray<>(); 11137 mSharedLibraries.put(name, versionedLib); 11138 if (type == SharedLibraryInfo.TYPE_STATIC) { 11139 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 11140 } 11141 } else if (versionedLib.indexOfKey(version) >= 0) { 11142 return false; 11143 } 11144 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 11145 version, type, declaringPackageName, declaringVersionCode); 11146 versionedLib.put(version, libEntry); 11147 return true; 11148 } 11149 11150 private boolean removeSharedLibraryLPw(String name, long version) { 11151 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11152 if (versionedLib == null) { 11153 return false; 11154 } 11155 final int libIdx = versionedLib.indexOfKey(version); 11156 if (libIdx < 0) { 11157 return false; 11158 } 11159 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 11160 versionedLib.remove(version); 11161 if (versionedLib.size() <= 0) { 11162 mSharedLibraries.remove(name); 11163 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 11164 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 11165 .getPackageName()); 11166 } 11167 } 11168 return true; 11169 } 11170 11171 /** 11172 * Adds a scanned package to the system. When this method is finished, the package will 11173 * be available for query, resolution, etc... 11174 */ 11175 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 11176 UserHandle user, final @ScanFlags int scanFlags, boolean chatty) { 11177 final String pkgName = pkg.packageName; 11178 if (mCustomResolverComponentName != null && 11179 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 11180 setUpCustomResolverActivity(pkg); 11181 } 11182 11183 if (pkg.packageName.equals("android")) { 11184 synchronized (mPackages) { 11185 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 11186 // Set up information for our fall-back user intent resolution activity. 11187 mPlatformPackage = pkg; 11188 pkg.mVersionCode = mSdkVersion; 11189 pkg.mVersionCodeMajor = 0; 11190 mAndroidApplication = pkg.applicationInfo; 11191 if (!mResolverReplaced) { 11192 mResolveActivity.applicationInfo = mAndroidApplication; 11193 mResolveActivity.name = ResolverActivity.class.getName(); 11194 mResolveActivity.packageName = mAndroidApplication.packageName; 11195 mResolveActivity.processName = "system:ui"; 11196 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11197 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 11198 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 11199 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 11200 mResolveActivity.exported = true; 11201 mResolveActivity.enabled = true; 11202 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 11203 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 11204 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 11205 | ActivityInfo.CONFIG_SCREEN_LAYOUT 11206 | ActivityInfo.CONFIG_ORIENTATION 11207 | ActivityInfo.CONFIG_KEYBOARD 11208 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 11209 mResolveInfo.activityInfo = mResolveActivity; 11210 mResolveInfo.priority = 0; 11211 mResolveInfo.preferredOrder = 0; 11212 mResolveInfo.match = 0; 11213 mResolveComponentName = new ComponentName( 11214 mAndroidApplication.packageName, mResolveActivity.name); 11215 } 11216 } 11217 } 11218 } 11219 11220 ArrayList<PackageParser.Package> clientLibPkgs = null; 11221 // writer 11222 synchronized (mPackages) { 11223 boolean hasStaticSharedLibs = false; 11224 11225 // Any app can add new static shared libraries 11226 if (pkg.staticSharedLibName != null) { 11227 // Static shared libs don't allow renaming as they have synthetic package 11228 // names to allow install of multiple versions, so use name from manifest. 11229 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 11230 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 11231 pkg.manifestPackageName, pkg.getLongVersionCode())) { 11232 hasStaticSharedLibs = true; 11233 } else { 11234 Slog.w(TAG, "Package " + pkg.packageName + " library " 11235 + pkg.staticSharedLibName + " already exists; skipping"); 11236 } 11237 // Static shared libs cannot be updated once installed since they 11238 // use synthetic package name which includes the version code, so 11239 // not need to update other packages's shared lib dependencies. 11240 } 11241 11242 if (!hasStaticSharedLibs 11243 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11244 // Only system apps can add new dynamic shared libraries. 11245 if (pkg.libraryNames != null) { 11246 for (int i = 0; i < pkg.libraryNames.size(); i++) { 11247 String name = pkg.libraryNames.get(i); 11248 boolean allowed = false; 11249 if (pkg.isUpdatedSystemApp()) { 11250 // New library entries can only be added through the 11251 // system image. This is important to get rid of a lot 11252 // of nasty edge cases: for example if we allowed a non- 11253 // system update of the app to add a library, then uninstalling 11254 // the update would make the library go away, and assumptions 11255 // we made such as through app install filtering would now 11256 // have allowed apps on the device which aren't compatible 11257 // with it. Better to just have the restriction here, be 11258 // conservative, and create many fewer cases that can negatively 11259 // impact the user experience. 11260 final PackageSetting sysPs = mSettings 11261 .getDisabledSystemPkgLPr(pkg.packageName); 11262 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 11263 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 11264 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 11265 allowed = true; 11266 break; 11267 } 11268 } 11269 } 11270 } else { 11271 allowed = true; 11272 } 11273 if (allowed) { 11274 if (!addSharedLibraryLPw(null, pkg.packageName, name, 11275 SharedLibraryInfo.VERSION_UNDEFINED, 11276 SharedLibraryInfo.TYPE_DYNAMIC, 11277 pkg.packageName, pkg.getLongVersionCode())) { 11278 Slog.w(TAG, "Package " + pkg.packageName + " library " 11279 + name + " already exists; skipping"); 11280 } 11281 } else { 11282 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 11283 + name + " that is not declared on system image; skipping"); 11284 } 11285 } 11286 11287 if ((scanFlags & SCAN_BOOTING) == 0) { 11288 // If we are not booting, we need to update any applications 11289 // that are clients of our shared library. If we are booting, 11290 // this will all be done once the scan is complete. 11291 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 11292 } 11293 } 11294 } 11295 } 11296 11297 if ((scanFlags & SCAN_BOOTING) != 0) { 11298 // No apps can run during boot scan, so they don't need to be frozen 11299 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 11300 // Caller asked to not kill app, so it's probably not frozen 11301 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 11302 // Caller asked us to ignore frozen check for some reason; they 11303 // probably didn't know the package name 11304 } else { 11305 // We're doing major surgery on this package, so it better be frozen 11306 // right now to keep it from launching 11307 checkPackageFrozen(pkgName); 11308 } 11309 11310 // Also need to kill any apps that are dependent on the library. 11311 if (clientLibPkgs != null) { 11312 for (int i=0; i<clientLibPkgs.size(); i++) { 11313 PackageParser.Package clientPkg = clientLibPkgs.get(i); 11314 killApplication(clientPkg.applicationInfo.packageName, 11315 clientPkg.applicationInfo.uid, "update lib"); 11316 } 11317 } 11318 11319 // writer 11320 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 11321 11322 synchronized (mPackages) { 11323 // We don't expect installation to fail beyond this point 11324 11325 // Add the new setting to mSettings 11326 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 11327 // Add the new setting to mPackages 11328 mPackages.put(pkg.applicationInfo.packageName, pkg); 11329 // Make sure we don't accidentally delete its data. 11330 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 11331 while (iter.hasNext()) { 11332 PackageCleanItem item = iter.next(); 11333 if (pkgName.equals(item.packageName)) { 11334 iter.remove(); 11335 } 11336 } 11337 11338 // Add the package's KeySets to the global KeySetManagerService 11339 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11340 ksms.addScannedPackageLPw(pkg); 11341 11342 int N = pkg.providers.size(); 11343 StringBuilder r = null; 11344 int i; 11345 for (i=0; i<N; i++) { 11346 PackageParser.Provider p = pkg.providers.get(i); 11347 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 11348 p.info.processName); 11349 mProviders.addProvider(p); 11350 p.syncable = p.info.isSyncable; 11351 if (p.info.authority != null) { 11352 String names[] = p.info.authority.split(";"); 11353 p.info.authority = null; 11354 for (int j = 0; j < names.length; j++) { 11355 if (j == 1 && p.syncable) { 11356 // We only want the first authority for a provider to possibly be 11357 // syncable, so if we already added this provider using a different 11358 // authority clear the syncable flag. We copy the provider before 11359 // changing it because the mProviders object contains a reference 11360 // to a provider that we don't want to change. 11361 // Only do this for the second authority since the resulting provider 11362 // object can be the same for all future authorities for this provider. 11363 p = new PackageParser.Provider(p); 11364 p.syncable = false; 11365 } 11366 if (!mProvidersByAuthority.containsKey(names[j])) { 11367 mProvidersByAuthority.put(names[j], p); 11368 if (p.info.authority == null) { 11369 p.info.authority = names[j]; 11370 } else { 11371 p.info.authority = p.info.authority + ";" + names[j]; 11372 } 11373 if (DEBUG_PACKAGE_SCANNING) { 11374 if (chatty) 11375 Log.d(TAG, "Registered content provider: " + names[j] 11376 + ", className = " + p.info.name + ", isSyncable = " 11377 + p.info.isSyncable); 11378 } 11379 } else { 11380 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11381 Slog.w(TAG, "Skipping provider name " + names[j] + 11382 " (in package " + pkg.applicationInfo.packageName + 11383 "): name already used by " 11384 + ((other != null && other.getComponentName() != null) 11385 ? other.getComponentName().getPackageName() : "?")); 11386 } 11387 } 11388 } 11389 if (chatty) { 11390 if (r == null) { 11391 r = new StringBuilder(256); 11392 } else { 11393 r.append(' '); 11394 } 11395 r.append(p.info.name); 11396 } 11397 } 11398 if (r != null) { 11399 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 11400 } 11401 11402 N = pkg.services.size(); 11403 r = null; 11404 for (i=0; i<N; i++) { 11405 PackageParser.Service s = pkg.services.get(i); 11406 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 11407 s.info.processName); 11408 mServices.addService(s); 11409 if (chatty) { 11410 if (r == null) { 11411 r = new StringBuilder(256); 11412 } else { 11413 r.append(' '); 11414 } 11415 r.append(s.info.name); 11416 } 11417 } 11418 if (r != null) { 11419 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 11420 } 11421 11422 N = pkg.receivers.size(); 11423 r = null; 11424 for (i=0; i<N; i++) { 11425 PackageParser.Activity a = pkg.receivers.get(i); 11426 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11427 a.info.processName); 11428 mReceivers.addActivity(a, "receiver"); 11429 if (chatty) { 11430 if (r == null) { 11431 r = new StringBuilder(256); 11432 } else { 11433 r.append(' '); 11434 } 11435 r.append(a.info.name); 11436 } 11437 } 11438 if (r != null) { 11439 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 11440 } 11441 11442 N = pkg.activities.size(); 11443 r = null; 11444 for (i=0; i<N; i++) { 11445 PackageParser.Activity a = pkg.activities.get(i); 11446 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11447 a.info.processName); 11448 mActivities.addActivity(a, "activity"); 11449 if (chatty) { 11450 if (r == null) { 11451 r = new StringBuilder(256); 11452 } else { 11453 r.append(' '); 11454 } 11455 r.append(a.info.name); 11456 } 11457 } 11458 if (r != null) { 11459 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11460 } 11461 11462 // Don't allow ephemeral applications to define new permissions groups. 11463 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11464 Slog.w(TAG, "Permission groups from package " + pkg.packageName 11465 + " ignored: instant apps cannot define new permission groups."); 11466 } else { 11467 mPermissionManager.addAllPermissionGroups(pkg, chatty); 11468 } 11469 11470 // Don't allow ephemeral applications to define new permissions. 11471 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11472 Slog.w(TAG, "Permissions from package " + pkg.packageName 11473 + " ignored: instant apps cannot define new permissions."); 11474 } else { 11475 mPermissionManager.addAllPermissions(pkg, chatty); 11476 } 11477 11478 N = pkg.instrumentation.size(); 11479 r = null; 11480 for (i=0; i<N; i++) { 11481 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11482 a.info.packageName = pkg.applicationInfo.packageName; 11483 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11484 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11485 a.info.splitNames = pkg.splitNames; 11486 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11487 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11488 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11489 a.info.dataDir = pkg.applicationInfo.dataDir; 11490 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11491 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11492 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11493 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11494 mInstrumentation.put(a.getComponentName(), a); 11495 if (chatty) { 11496 if (r == null) { 11497 r = new StringBuilder(256); 11498 } else { 11499 r.append(' '); 11500 } 11501 r.append(a.info.name); 11502 } 11503 } 11504 if (r != null) { 11505 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11506 } 11507 11508 if (pkg.protectedBroadcasts != null) { 11509 N = pkg.protectedBroadcasts.size(); 11510 synchronized (mProtectedBroadcasts) { 11511 for (i = 0; i < N; i++) { 11512 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 11513 } 11514 } 11515 } 11516 } 11517 11518 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11519 } 11520 11521 /** 11522 * Derive the ABI of a non-system package located at {@code scanFile}. This information 11523 * is derived purely on the basis of the contents of {@code scanFile} and 11524 * {@code cpuAbiOverride}. 11525 * 11526 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 11527 */ 11528 private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride, 11529 boolean extractLibs) 11530 throws PackageManagerException { 11531 // Give ourselves some initial paths; we'll come back for another 11532 // pass once we've determined ABI below. 11533 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11534 11535 // We would never need to extract libs for forward-locked and external packages, 11536 // since the container service will do it for us. We shouldn't attempt to 11537 // extract libs from system app when it was not updated. 11538 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 11539 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 11540 extractLibs = false; 11541 } 11542 11543 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 11544 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 11545 11546 NativeLibraryHelper.Handle handle = null; 11547 try { 11548 handle = NativeLibraryHelper.Handle.create(pkg); 11549 // TODO(multiArch): This can be null for apps that didn't go through the 11550 // usual installation process. We can calculate it again, like we 11551 // do during install time. 11552 // 11553 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 11554 // unnecessary. 11555 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 11556 11557 // Null out the abis so that they can be recalculated. 11558 pkg.applicationInfo.primaryCpuAbi = null; 11559 pkg.applicationInfo.secondaryCpuAbi = null; 11560 if (isMultiArch(pkg.applicationInfo)) { 11561 // Warn if we've set an abiOverride for multi-lib packages.. 11562 // By definition, we need to copy both 32 and 64 bit libraries for 11563 // such packages. 11564 if (pkg.cpuAbiOverride != null 11565 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 11566 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 11567 } 11568 11569 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 11570 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 11571 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 11572 if (extractLibs) { 11573 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11574 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11575 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 11576 useIsaSpecificSubdirs); 11577 } else { 11578 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11579 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 11580 } 11581 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11582 } 11583 11584 // Shared library native code should be in the APK zip aligned 11585 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 11586 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11587 "Shared library native lib extraction not supported"); 11588 } 11589 11590 maybeThrowExceptionForMultiArchCopy( 11591 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 11592 11593 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 11594 if (extractLibs) { 11595 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11596 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11597 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 11598 useIsaSpecificSubdirs); 11599 } else { 11600 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11601 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 11602 } 11603 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11604 } 11605 11606 maybeThrowExceptionForMultiArchCopy( 11607 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 11608 11609 if (abi64 >= 0) { 11610 // Shared library native libs should be in the APK zip aligned 11611 if (extractLibs && pkg.isLibrary()) { 11612 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11613 "Shared library native lib extraction not supported"); 11614 } 11615 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11616 } 11617 11618 if (abi32 >= 0) { 11619 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11620 if (abi64 >= 0) { 11621 if (pkg.use32bitAbi) { 11622 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11623 pkg.applicationInfo.primaryCpuAbi = abi; 11624 } else { 11625 pkg.applicationInfo.secondaryCpuAbi = abi; 11626 } 11627 } else { 11628 pkg.applicationInfo.primaryCpuAbi = abi; 11629 } 11630 } 11631 } else { 11632 String[] abiList = (cpuAbiOverride != null) ? 11633 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11634 11635 // Enable gross and lame hacks for apps that are built with old 11636 // SDK tools. We must scan their APKs for renderscript bitcode and 11637 // not launch them if it's present. Don't bother checking on devices 11638 // that don't have 64 bit support. 11639 boolean needsRenderScriptOverride = false; 11640 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11641 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11642 abiList = Build.SUPPORTED_32_BIT_ABIS; 11643 needsRenderScriptOverride = true; 11644 } 11645 11646 final int copyRet; 11647 if (extractLibs) { 11648 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11649 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11650 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11651 } else { 11652 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11653 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11654 } 11655 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11656 11657 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11658 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11659 "Error unpackaging native libs for app, errorCode=" + copyRet); 11660 } 11661 11662 if (copyRet >= 0) { 11663 // Shared libraries that have native libs must be multi-architecture 11664 if (pkg.isLibrary()) { 11665 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11666 "Shared library with native libs must be multiarch"); 11667 } 11668 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11669 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11670 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11671 } else if (needsRenderScriptOverride) { 11672 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11673 } 11674 } 11675 } catch (IOException ioe) { 11676 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11677 } finally { 11678 IoUtils.closeQuietly(handle); 11679 } 11680 11681 // Now that we've calculated the ABIs and determined if it's an internal app, 11682 // we will go ahead and populate the nativeLibraryPath. 11683 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11684 } 11685 11686 /** 11687 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11688 * i.e, so that all packages can be run inside a single process if required. 11689 * 11690 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11691 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11692 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11693 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11694 * updating a package that belongs to a shared user. 11695 * 11696 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11697 * adds unnecessary complexity. 11698 */ 11699 private static @Nullable List<String> adjustCpuAbisForSharedUserLPw( 11700 Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) { 11701 List<String> changedAbiCodePath = null; 11702 String requiredInstructionSet = null; 11703 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11704 requiredInstructionSet = VMRuntime.getInstructionSet( 11705 scannedPackage.applicationInfo.primaryCpuAbi); 11706 } 11707 11708 PackageSetting requirer = null; 11709 for (PackageSetting ps : packagesForUser) { 11710 // If packagesForUser contains scannedPackage, we skip it. This will happen 11711 // when scannedPackage is an update of an existing package. Without this check, 11712 // we will never be able to change the ABI of any package belonging to a shared 11713 // user, even if it's compatible with other packages. 11714 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11715 if (ps.primaryCpuAbiString == null) { 11716 continue; 11717 } 11718 11719 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11720 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11721 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11722 // this but there's not much we can do. 11723 String errorMessage = "Instruction set mismatch, " 11724 + ((requirer == null) ? "[caller]" : requirer) 11725 + " requires " + requiredInstructionSet + " whereas " + ps 11726 + " requires " + instructionSet; 11727 Slog.w(TAG, errorMessage); 11728 } 11729 11730 if (requiredInstructionSet == null) { 11731 requiredInstructionSet = instructionSet; 11732 requirer = ps; 11733 } 11734 } 11735 } 11736 11737 if (requiredInstructionSet != null) { 11738 String adjustedAbi; 11739 if (requirer != null) { 11740 // requirer != null implies that either scannedPackage was null or that scannedPackage 11741 // did not require an ABI, in which case we have to adjust scannedPackage to match 11742 // the ABI of the set (which is the same as requirer's ABI) 11743 adjustedAbi = requirer.primaryCpuAbiString; 11744 if (scannedPackage != null) { 11745 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11746 } 11747 } else { 11748 // requirer == null implies that we're updating all ABIs in the set to 11749 // match scannedPackage. 11750 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11751 } 11752 11753 for (PackageSetting ps : packagesForUser) { 11754 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11755 if (ps.primaryCpuAbiString != null) { 11756 continue; 11757 } 11758 11759 ps.primaryCpuAbiString = adjustedAbi; 11760 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11761 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11762 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11763 if (DEBUG_ABI_SELECTION) { 11764 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11765 + " (requirer=" 11766 + (requirer != null ? requirer.pkg : "null") 11767 + ", scannedPackage=" 11768 + (scannedPackage != null ? scannedPackage : "null") 11769 + ")"); 11770 } 11771 if (changedAbiCodePath == null) { 11772 changedAbiCodePath = new ArrayList<>(); 11773 } 11774 changedAbiCodePath.add(ps.codePathString); 11775 } 11776 } 11777 } 11778 } 11779 return changedAbiCodePath; 11780 } 11781 11782 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11783 synchronized (mPackages) { 11784 mResolverReplaced = true; 11785 // Set up information for custom user intent resolution activity. 11786 mResolveActivity.applicationInfo = pkg.applicationInfo; 11787 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11788 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11789 mResolveActivity.processName = pkg.applicationInfo.packageName; 11790 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11791 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11792 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11793 mResolveActivity.theme = 0; 11794 mResolveActivity.exported = true; 11795 mResolveActivity.enabled = true; 11796 mResolveInfo.activityInfo = mResolveActivity; 11797 mResolveInfo.priority = 0; 11798 mResolveInfo.preferredOrder = 0; 11799 mResolveInfo.match = 0; 11800 mResolveComponentName = mCustomResolverComponentName; 11801 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11802 mResolveComponentName); 11803 } 11804 } 11805 11806 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11807 if (installerActivity == null) { 11808 if (DEBUG_INSTANT) { 11809 Slog.d(TAG, "Clear ephemeral installer activity"); 11810 } 11811 mInstantAppInstallerActivity = null; 11812 return; 11813 } 11814 11815 if (DEBUG_INSTANT) { 11816 Slog.d(TAG, "Set ephemeral installer activity: " 11817 + installerActivity.getComponentName()); 11818 } 11819 // Set up information for ephemeral installer activity 11820 mInstantAppInstallerActivity = installerActivity; 11821 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11822 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11823 mInstantAppInstallerActivity.exported = true; 11824 mInstantAppInstallerActivity.enabled = true; 11825 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11826 mInstantAppInstallerInfo.priority = 1; 11827 mInstantAppInstallerInfo.preferredOrder = 1; 11828 mInstantAppInstallerInfo.isDefault = true; 11829 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11830 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11831 } 11832 11833 private static String calculateBundledApkRoot(final String codePathString) { 11834 final File codePath = new File(codePathString); 11835 final File codeRoot; 11836 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11837 codeRoot = Environment.getRootDirectory(); 11838 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11839 codeRoot = Environment.getOemDirectory(); 11840 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11841 codeRoot = Environment.getVendorDirectory(); 11842 } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) { 11843 codeRoot = Environment.getOdmDirectory(); 11844 } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) { 11845 codeRoot = Environment.getProductDirectory(); 11846 } else { 11847 // Unrecognized code path; take its top real segment as the apk root: 11848 // e.g. /something/app/blah.apk => /something 11849 try { 11850 File f = codePath.getCanonicalFile(); 11851 File parent = f.getParentFile(); // non-null because codePath is a file 11852 File tmp; 11853 while ((tmp = parent.getParentFile()) != null) { 11854 f = parent; 11855 parent = tmp; 11856 } 11857 codeRoot = f; 11858 Slog.w(TAG, "Unrecognized code path " 11859 + codePath + " - using " + codeRoot); 11860 } catch (IOException e) { 11861 // Can't canonicalize the code path -- shenanigans? 11862 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11863 return Environment.getRootDirectory().getPath(); 11864 } 11865 } 11866 return codeRoot.getPath(); 11867 } 11868 11869 /** 11870 * Derive and set the location of native libraries for the given package, 11871 * which varies depending on where and how the package was installed. 11872 */ 11873 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11874 final ApplicationInfo info = pkg.applicationInfo; 11875 final String codePath = pkg.codePath; 11876 final File codeFile = new File(codePath); 11877 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11878 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11879 11880 info.nativeLibraryRootDir = null; 11881 info.nativeLibraryRootRequiresIsa = false; 11882 info.nativeLibraryDir = null; 11883 info.secondaryNativeLibraryDir = null; 11884 11885 if (isApkFile(codeFile)) { 11886 // Monolithic install 11887 if (bundledApp) { 11888 // If "/system/lib64/apkname" exists, assume that is the per-package 11889 // native library directory to use; otherwise use "/system/lib/apkname". 11890 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11891 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11892 getPrimaryInstructionSet(info)); 11893 11894 // This is a bundled system app so choose the path based on the ABI. 11895 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11896 // is just the default path. 11897 final String apkName = deriveCodePathName(codePath); 11898 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11899 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11900 apkName).getAbsolutePath(); 11901 11902 if (info.secondaryCpuAbi != null) { 11903 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11904 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11905 secondaryLibDir, apkName).getAbsolutePath(); 11906 } 11907 } else if (asecApp) { 11908 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11909 .getAbsolutePath(); 11910 } else { 11911 final String apkName = deriveCodePathName(codePath); 11912 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11913 .getAbsolutePath(); 11914 } 11915 11916 info.nativeLibraryRootRequiresIsa = false; 11917 info.nativeLibraryDir = info.nativeLibraryRootDir; 11918 } else { 11919 // Cluster install 11920 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11921 info.nativeLibraryRootRequiresIsa = true; 11922 11923 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11924 getPrimaryInstructionSet(info)).getAbsolutePath(); 11925 11926 if (info.secondaryCpuAbi != null) { 11927 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11928 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11929 } 11930 } 11931 } 11932 11933 /** 11934 * Calculate the abis and roots for a bundled app. These can uniquely 11935 * be determined from the contents of the system partition, i.e whether 11936 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11937 * of this information, and instead assume that the system was built 11938 * sensibly. 11939 */ 11940 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11941 PackageSetting pkgSetting) { 11942 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11943 11944 // If "/system/lib64/apkname" exists, assume that is the per-package 11945 // native library directory to use; otherwise use "/system/lib/apkname". 11946 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11947 setBundledAppAbi(pkg, apkRoot, apkName); 11948 // pkgSetting might be null during rescan following uninstall of updates 11949 // to a bundled app, so accommodate that possibility. The settings in 11950 // that case will be established later from the parsed package. 11951 // 11952 // If the settings aren't null, sync them up with what we've just derived. 11953 // note that apkRoot isn't stored in the package settings. 11954 if (pkgSetting != null) { 11955 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11956 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11957 } 11958 } 11959 11960 /** 11961 * Deduces the ABI of a bundled app and sets the relevant fields on the 11962 * parsed pkg object. 11963 * 11964 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11965 * under which system libraries are installed. 11966 * @param apkName the name of the installed package. 11967 */ 11968 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11969 final File codeFile = new File(pkg.codePath); 11970 11971 final boolean has64BitLibs; 11972 final boolean has32BitLibs; 11973 if (isApkFile(codeFile)) { 11974 // Monolithic install 11975 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11976 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11977 } else { 11978 // Cluster install 11979 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11980 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11981 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11982 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11983 has64BitLibs = (new File(rootDir, isa)).exists(); 11984 } else { 11985 has64BitLibs = false; 11986 } 11987 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11988 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11989 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11990 has32BitLibs = (new File(rootDir, isa)).exists(); 11991 } else { 11992 has32BitLibs = false; 11993 } 11994 } 11995 11996 if (has64BitLibs && !has32BitLibs) { 11997 // The package has 64 bit libs, but not 32 bit libs. Its primary 11998 // ABI should be 64 bit. We can safely assume here that the bundled 11999 // native libraries correspond to the most preferred ABI in the list. 12000 12001 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 12002 pkg.applicationInfo.secondaryCpuAbi = null; 12003 } else if (has32BitLibs && !has64BitLibs) { 12004 // The package has 32 bit libs but not 64 bit libs. Its primary 12005 // ABI should be 32 bit. 12006 12007 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 12008 pkg.applicationInfo.secondaryCpuAbi = null; 12009 } else if (has32BitLibs && has64BitLibs) { 12010 // The application has both 64 and 32 bit bundled libraries. We check 12011 // here that the app declares multiArch support, and warn if it doesn't. 12012 // 12013 // We will be lenient here and record both ABIs. The primary will be the 12014 // ABI that's higher on the list, i.e, a device that's configured to prefer 12015 // 64 bit apps will see a 64 bit primary ABI, 12016 12017 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 12018 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 12019 } 12020 12021 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 12022 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 12023 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 12024 } else { 12025 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 12026 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 12027 } 12028 } else { 12029 pkg.applicationInfo.primaryCpuAbi = null; 12030 pkg.applicationInfo.secondaryCpuAbi = null; 12031 } 12032 } 12033 12034 private void killApplication(String pkgName, int appId, String reason) { 12035 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 12036 } 12037 12038 private void killApplication(String pkgName, int appId, int userId, String reason) { 12039 // Request the ActivityManager to kill the process(only for existing packages) 12040 // so that we do not end up in a confused state while the user is still using the older 12041 // version of the application while the new one gets installed. 12042 final long token = Binder.clearCallingIdentity(); 12043 try { 12044 IActivityManager am = ActivityManager.getService(); 12045 if (am != null) { 12046 try { 12047 am.killApplication(pkgName, appId, userId, reason); 12048 } catch (RemoteException e) { 12049 } 12050 } 12051 } finally { 12052 Binder.restoreCallingIdentity(token); 12053 } 12054 } 12055 12056 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 12057 // Remove the parent package setting 12058 PackageSetting ps = (PackageSetting) pkg.mExtras; 12059 if (ps != null) { 12060 removePackageLI(ps, chatty); 12061 } 12062 // Remove the child package setting 12063 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12064 for (int i = 0; i < childCount; i++) { 12065 PackageParser.Package childPkg = pkg.childPackages.get(i); 12066 ps = (PackageSetting) childPkg.mExtras; 12067 if (ps != null) { 12068 removePackageLI(ps, chatty); 12069 } 12070 } 12071 } 12072 12073 void removePackageLI(PackageSetting ps, boolean chatty) { 12074 if (DEBUG_INSTALL) { 12075 if (chatty) 12076 Log.d(TAG, "Removing package " + ps.name); 12077 } 12078 12079 // writer 12080 synchronized (mPackages) { 12081 mPackages.remove(ps.name); 12082 final PackageParser.Package pkg = ps.pkg; 12083 if (pkg != null) { 12084 cleanPackageDataStructuresLILPw(pkg, chatty); 12085 } 12086 } 12087 } 12088 12089 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 12090 if (DEBUG_INSTALL) { 12091 if (chatty) 12092 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 12093 } 12094 12095 // writer 12096 synchronized (mPackages) { 12097 // Remove the parent package 12098 mPackages.remove(pkg.applicationInfo.packageName); 12099 cleanPackageDataStructuresLILPw(pkg, chatty); 12100 12101 // Remove the child packages 12102 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12103 for (int i = 0; i < childCount; i++) { 12104 PackageParser.Package childPkg = pkg.childPackages.get(i); 12105 mPackages.remove(childPkg.applicationInfo.packageName); 12106 cleanPackageDataStructuresLILPw(childPkg, chatty); 12107 } 12108 } 12109 } 12110 12111 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 12112 int N = pkg.providers.size(); 12113 StringBuilder r = null; 12114 int i; 12115 for (i=0; i<N; i++) { 12116 PackageParser.Provider p = pkg.providers.get(i); 12117 mProviders.removeProvider(p); 12118 if (p.info.authority == null) { 12119 12120 /* There was another ContentProvider with this authority when 12121 * this app was installed so this authority is null, 12122 * Ignore it as we don't have to unregister the provider. 12123 */ 12124 continue; 12125 } 12126 String names[] = p.info.authority.split(";"); 12127 for (int j = 0; j < names.length; j++) { 12128 if (mProvidersByAuthority.get(names[j]) == p) { 12129 mProvidersByAuthority.remove(names[j]); 12130 if (DEBUG_REMOVE) { 12131 if (chatty) 12132 Log.d(TAG, "Unregistered content provider: " + names[j] 12133 + ", className = " + p.info.name + ", isSyncable = " 12134 + p.info.isSyncable); 12135 } 12136 } 12137 } 12138 if (DEBUG_REMOVE && chatty) { 12139 if (r == null) { 12140 r = new StringBuilder(256); 12141 } else { 12142 r.append(' '); 12143 } 12144 r.append(p.info.name); 12145 } 12146 } 12147 if (r != null) { 12148 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 12149 } 12150 12151 N = pkg.services.size(); 12152 r = null; 12153 for (i=0; i<N; i++) { 12154 PackageParser.Service s = pkg.services.get(i); 12155 mServices.removeService(s); 12156 if (chatty) { 12157 if (r == null) { 12158 r = new StringBuilder(256); 12159 } else { 12160 r.append(' '); 12161 } 12162 r.append(s.info.name); 12163 } 12164 } 12165 if (r != null) { 12166 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 12167 } 12168 12169 N = pkg.receivers.size(); 12170 r = null; 12171 for (i=0; i<N; i++) { 12172 PackageParser.Activity a = pkg.receivers.get(i); 12173 mReceivers.removeActivity(a, "receiver"); 12174 if (DEBUG_REMOVE && chatty) { 12175 if (r == null) { 12176 r = new StringBuilder(256); 12177 } else { 12178 r.append(' '); 12179 } 12180 r.append(a.info.name); 12181 } 12182 } 12183 if (r != null) { 12184 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 12185 } 12186 12187 N = pkg.activities.size(); 12188 r = null; 12189 for (i=0; i<N; i++) { 12190 PackageParser.Activity a = pkg.activities.get(i); 12191 mActivities.removeActivity(a, "activity"); 12192 if (DEBUG_REMOVE && chatty) { 12193 if (r == null) { 12194 r = new StringBuilder(256); 12195 } else { 12196 r.append(' '); 12197 } 12198 r.append(a.info.name); 12199 } 12200 } 12201 if (r != null) { 12202 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 12203 } 12204 12205 mPermissionManager.removeAllPermissions(pkg, chatty); 12206 12207 N = pkg.instrumentation.size(); 12208 r = null; 12209 for (i=0; i<N; i++) { 12210 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 12211 mInstrumentation.remove(a.getComponentName()); 12212 if (DEBUG_REMOVE && chatty) { 12213 if (r == null) { 12214 r = new StringBuilder(256); 12215 } else { 12216 r.append(' '); 12217 } 12218 r.append(a.info.name); 12219 } 12220 } 12221 if (r != null) { 12222 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 12223 } 12224 12225 r = null; 12226 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 12227 // Only system apps can hold shared libraries. 12228 if (pkg.libraryNames != null) { 12229 for (i = 0; i < pkg.libraryNames.size(); i++) { 12230 String name = pkg.libraryNames.get(i); 12231 if (removeSharedLibraryLPw(name, 0)) { 12232 if (DEBUG_REMOVE && chatty) { 12233 if (r == null) { 12234 r = new StringBuilder(256); 12235 } else { 12236 r.append(' '); 12237 } 12238 r.append(name); 12239 } 12240 } 12241 } 12242 } 12243 } 12244 12245 r = null; 12246 12247 // Any package can hold static shared libraries. 12248 if (pkg.staticSharedLibName != null) { 12249 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 12250 if (DEBUG_REMOVE && chatty) { 12251 if (r == null) { 12252 r = new StringBuilder(256); 12253 } else { 12254 r.append(' '); 12255 } 12256 r.append(pkg.staticSharedLibName); 12257 } 12258 } 12259 } 12260 12261 if (r != null) { 12262 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 12263 } 12264 } 12265 12266 12267 final class ActivityIntentResolver 12268 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 12269 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12270 boolean defaultOnly, int userId) { 12271 if (!sUserManager.exists(userId)) return null; 12272 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 12273 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12274 } 12275 12276 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12277 int userId) { 12278 if (!sUserManager.exists(userId)) return null; 12279 mFlags = flags; 12280 return super.queryIntent(intent, resolvedType, 12281 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12282 userId); 12283 } 12284 12285 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12286 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 12287 if (!sUserManager.exists(userId)) return null; 12288 if (packageActivities == null) { 12289 return null; 12290 } 12291 mFlags = flags; 12292 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12293 final int N = packageActivities.size(); 12294 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 12295 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 12296 12297 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 12298 for (int i = 0; i < N; ++i) { 12299 intentFilters = packageActivities.get(i).intents; 12300 if (intentFilters != null && intentFilters.size() > 0) { 12301 PackageParser.ActivityIntentInfo[] array = 12302 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 12303 intentFilters.toArray(array); 12304 listCut.add(array); 12305 } 12306 } 12307 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12308 } 12309 12310 /** 12311 * Finds a privileged activity that matches the specified activity names. 12312 */ 12313 private PackageParser.Activity findMatchingActivity( 12314 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 12315 for (PackageParser.Activity sysActivity : activityList) { 12316 if (sysActivity.info.name.equals(activityInfo.name)) { 12317 return sysActivity; 12318 } 12319 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 12320 return sysActivity; 12321 } 12322 if (sysActivity.info.targetActivity != null) { 12323 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 12324 return sysActivity; 12325 } 12326 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 12327 return sysActivity; 12328 } 12329 } 12330 } 12331 return null; 12332 } 12333 12334 public class IterGenerator<E> { 12335 public Iterator<E> generate(ActivityIntentInfo info) { 12336 return null; 12337 } 12338 } 12339 12340 public class ActionIterGenerator extends IterGenerator<String> { 12341 @Override 12342 public Iterator<String> generate(ActivityIntentInfo info) { 12343 return info.actionsIterator(); 12344 } 12345 } 12346 12347 public class CategoriesIterGenerator extends IterGenerator<String> { 12348 @Override 12349 public Iterator<String> generate(ActivityIntentInfo info) { 12350 return info.categoriesIterator(); 12351 } 12352 } 12353 12354 public class SchemesIterGenerator extends IterGenerator<String> { 12355 @Override 12356 public Iterator<String> generate(ActivityIntentInfo info) { 12357 return info.schemesIterator(); 12358 } 12359 } 12360 12361 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 12362 @Override 12363 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 12364 return info.authoritiesIterator(); 12365 } 12366 } 12367 12368 /** 12369 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12370 * MODIFIED. Do not pass in a list that should not be changed. 12371 */ 12372 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12373 IterGenerator<T> generator, Iterator<T> searchIterator) { 12374 // loop through the set of actions; every one must be found in the intent filter 12375 while (searchIterator.hasNext()) { 12376 // we must have at least one filter in the list to consider a match 12377 if (intentList.size() == 0) { 12378 break; 12379 } 12380 12381 final T searchAction = searchIterator.next(); 12382 12383 // loop through the set of intent filters 12384 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12385 while (intentIter.hasNext()) { 12386 final ActivityIntentInfo intentInfo = intentIter.next(); 12387 boolean selectionFound = false; 12388 12389 // loop through the intent filter's selection criteria; at least one 12390 // of them must match the searched criteria 12391 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12392 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12393 final T intentSelection = intentSelectionIter.next(); 12394 if (intentSelection != null && intentSelection.equals(searchAction)) { 12395 selectionFound = true; 12396 break; 12397 } 12398 } 12399 12400 // the selection criteria wasn't found in this filter's set; this filter 12401 // is not a potential match 12402 if (!selectionFound) { 12403 intentIter.remove(); 12404 } 12405 } 12406 } 12407 } 12408 12409 private boolean isProtectedAction(ActivityIntentInfo filter) { 12410 final Iterator<String> actionsIter = filter.actionsIterator(); 12411 while (actionsIter != null && actionsIter.hasNext()) { 12412 final String filterAction = actionsIter.next(); 12413 if (PROTECTED_ACTIONS.contains(filterAction)) { 12414 return true; 12415 } 12416 } 12417 return false; 12418 } 12419 12420 /** 12421 * Adjusts the priority of the given intent filter according to policy. 12422 * <p> 12423 * <ul> 12424 * <li>The priority for non privileged applications is capped to '0'</li> 12425 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12426 * <li>The priority for unbundled updates to privileged applications is capped to the 12427 * priority defined on the system partition</li> 12428 * </ul> 12429 * <p> 12430 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12431 * allowed to obtain any priority on any action. 12432 */ 12433 private void adjustPriority( 12434 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12435 // nothing to do; priority is fine as-is 12436 if (intent.getPriority() <= 0) { 12437 return; 12438 } 12439 12440 final ActivityInfo activityInfo = intent.activity.info; 12441 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12442 12443 final boolean privilegedApp = 12444 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12445 if (!privilegedApp) { 12446 // non-privileged applications can never define a priority >0 12447 if (DEBUG_FILTERS) { 12448 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 12449 + " package: " + applicationInfo.packageName 12450 + " activity: " + intent.activity.className 12451 + " origPrio: " + intent.getPriority()); 12452 } 12453 intent.setPriority(0); 12454 return; 12455 } 12456 12457 if (systemActivities == null) { 12458 // the system package is not disabled; we're parsing the system partition 12459 if (isProtectedAction(intent)) { 12460 if (mDeferProtectedFilters) { 12461 // We can't deal with these just yet. No component should ever obtain a 12462 // >0 priority for a protected actions, with ONE exception -- the setup 12463 // wizard. The setup wizard, however, cannot be known until we're able to 12464 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12465 // until all intent filters have been processed. Chicken, meet egg. 12466 // Let the filter temporarily have a high priority and rectify the 12467 // priorities after all system packages have been scanned. 12468 mProtectedFilters.add(intent); 12469 if (DEBUG_FILTERS) { 12470 Slog.i(TAG, "Protected action; save for later;" 12471 + " package: " + applicationInfo.packageName 12472 + " activity: " + intent.activity.className 12473 + " origPrio: " + intent.getPriority()); 12474 } 12475 return; 12476 } else { 12477 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12478 Slog.i(TAG, "No setup wizard;" 12479 + " All protected intents capped to priority 0"); 12480 } 12481 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12482 if (DEBUG_FILTERS) { 12483 Slog.i(TAG, "Found setup wizard;" 12484 + " allow priority " + intent.getPriority() + ";" 12485 + " package: " + intent.activity.info.packageName 12486 + " activity: " + intent.activity.className 12487 + " priority: " + intent.getPriority()); 12488 } 12489 // setup wizard gets whatever it wants 12490 return; 12491 } 12492 if (DEBUG_FILTERS) { 12493 Slog.i(TAG, "Protected action; cap priority to 0;" 12494 + " package: " + intent.activity.info.packageName 12495 + " activity: " + intent.activity.className 12496 + " origPrio: " + intent.getPriority()); 12497 } 12498 intent.setPriority(0); 12499 return; 12500 } 12501 } 12502 // privileged apps on the system image get whatever priority they request 12503 return; 12504 } 12505 12506 // privileged app unbundled update ... try to find the same activity 12507 final PackageParser.Activity foundActivity = 12508 findMatchingActivity(systemActivities, activityInfo); 12509 if (foundActivity == null) { 12510 // this is a new activity; it cannot obtain >0 priority 12511 if (DEBUG_FILTERS) { 12512 Slog.i(TAG, "New activity; cap priority to 0;" 12513 + " package: " + applicationInfo.packageName 12514 + " activity: " + intent.activity.className 12515 + " origPrio: " + intent.getPriority()); 12516 } 12517 intent.setPriority(0); 12518 return; 12519 } 12520 12521 // found activity, now check for filter equivalence 12522 12523 // a shallow copy is enough; we modify the list, not its contents 12524 final List<ActivityIntentInfo> intentListCopy = 12525 new ArrayList<>(foundActivity.intents); 12526 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12527 12528 // find matching action subsets 12529 final Iterator<String> actionsIterator = intent.actionsIterator(); 12530 if (actionsIterator != null) { 12531 getIntentListSubset( 12532 intentListCopy, new ActionIterGenerator(), actionsIterator); 12533 if (intentListCopy.size() == 0) { 12534 // no more intents to match; we're not equivalent 12535 if (DEBUG_FILTERS) { 12536 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12537 + " package: " + applicationInfo.packageName 12538 + " activity: " + intent.activity.className 12539 + " origPrio: " + intent.getPriority()); 12540 } 12541 intent.setPriority(0); 12542 return; 12543 } 12544 } 12545 12546 // find matching category subsets 12547 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12548 if (categoriesIterator != null) { 12549 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12550 categoriesIterator); 12551 if (intentListCopy.size() == 0) { 12552 // no more intents to match; we're not equivalent 12553 if (DEBUG_FILTERS) { 12554 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12555 + " package: " + applicationInfo.packageName 12556 + " activity: " + intent.activity.className 12557 + " origPrio: " + intent.getPriority()); 12558 } 12559 intent.setPriority(0); 12560 return; 12561 } 12562 } 12563 12564 // find matching schemes subsets 12565 final Iterator<String> schemesIterator = intent.schemesIterator(); 12566 if (schemesIterator != null) { 12567 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12568 schemesIterator); 12569 if (intentListCopy.size() == 0) { 12570 // no more intents to match; we're not equivalent 12571 if (DEBUG_FILTERS) { 12572 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12573 + " package: " + applicationInfo.packageName 12574 + " activity: " + intent.activity.className 12575 + " origPrio: " + intent.getPriority()); 12576 } 12577 intent.setPriority(0); 12578 return; 12579 } 12580 } 12581 12582 // find matching authorities subsets 12583 final Iterator<IntentFilter.AuthorityEntry> 12584 authoritiesIterator = intent.authoritiesIterator(); 12585 if (authoritiesIterator != null) { 12586 getIntentListSubset(intentListCopy, 12587 new AuthoritiesIterGenerator(), 12588 authoritiesIterator); 12589 if (intentListCopy.size() == 0) { 12590 // no more intents to match; we're not equivalent 12591 if (DEBUG_FILTERS) { 12592 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12593 + " package: " + applicationInfo.packageName 12594 + " activity: " + intent.activity.className 12595 + " origPrio: " + intent.getPriority()); 12596 } 12597 intent.setPriority(0); 12598 return; 12599 } 12600 } 12601 12602 // we found matching filter(s); app gets the max priority of all intents 12603 int cappedPriority = 0; 12604 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12605 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12606 } 12607 if (intent.getPriority() > cappedPriority) { 12608 if (DEBUG_FILTERS) { 12609 Slog.i(TAG, "Found matching filter(s);" 12610 + " cap priority to " + cappedPriority + ";" 12611 + " package: " + applicationInfo.packageName 12612 + " activity: " + intent.activity.className 12613 + " origPrio: " + intent.getPriority()); 12614 } 12615 intent.setPriority(cappedPriority); 12616 return; 12617 } 12618 // all this for nothing; the requested priority was <= what was on the system 12619 } 12620 12621 public final void addActivity(PackageParser.Activity a, String type) { 12622 mActivities.put(a.getComponentName(), a); 12623 if (DEBUG_SHOW_INFO) 12624 Log.v( 12625 TAG, " " + type + " " + 12626 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12627 if (DEBUG_SHOW_INFO) 12628 Log.v(TAG, " Class=" + a.info.name); 12629 final int NI = a.intents.size(); 12630 for (int j=0; j<NI; j++) { 12631 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12632 if ("activity".equals(type)) { 12633 final PackageSetting ps = 12634 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12635 final List<PackageParser.Activity> systemActivities = 12636 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12637 adjustPriority(systemActivities, intent); 12638 } 12639 if (DEBUG_SHOW_INFO) { 12640 Log.v(TAG, " IntentFilter:"); 12641 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12642 } 12643 if (!intent.debugCheck()) { 12644 Log.w(TAG, "==> For Activity " + a.info.name); 12645 } 12646 addFilter(intent); 12647 } 12648 } 12649 12650 public final void removeActivity(PackageParser.Activity a, String type) { 12651 mActivities.remove(a.getComponentName()); 12652 if (DEBUG_SHOW_INFO) { 12653 Log.v(TAG, " " + type + " " 12654 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12655 : a.info.name) + ":"); 12656 Log.v(TAG, " Class=" + a.info.name); 12657 } 12658 final int NI = a.intents.size(); 12659 for (int j=0; j<NI; j++) { 12660 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12661 if (DEBUG_SHOW_INFO) { 12662 Log.v(TAG, " IntentFilter:"); 12663 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12664 } 12665 removeFilter(intent); 12666 } 12667 } 12668 12669 @Override 12670 protected boolean allowFilterResult( 12671 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12672 ActivityInfo filterAi = filter.activity.info; 12673 for (int i=dest.size()-1; i>=0; i--) { 12674 ActivityInfo destAi = dest.get(i).activityInfo; 12675 if (destAi.name == filterAi.name 12676 && destAi.packageName == filterAi.packageName) { 12677 return false; 12678 } 12679 } 12680 return true; 12681 } 12682 12683 @Override 12684 protected ActivityIntentInfo[] newArray(int size) { 12685 return new ActivityIntentInfo[size]; 12686 } 12687 12688 @Override 12689 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12690 if (!sUserManager.exists(userId)) return true; 12691 PackageParser.Package p = filter.activity.owner; 12692 if (p != null) { 12693 PackageSetting ps = (PackageSetting)p.mExtras; 12694 if (ps != null) { 12695 // System apps are never considered stopped for purposes of 12696 // filtering, because there may be no way for the user to 12697 // actually re-launch them. 12698 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12699 && ps.getStopped(userId); 12700 } 12701 } 12702 return false; 12703 } 12704 12705 @Override 12706 protected boolean isPackageForFilter(String packageName, 12707 PackageParser.ActivityIntentInfo info) { 12708 return packageName.equals(info.activity.owner.packageName); 12709 } 12710 12711 @Override 12712 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12713 int match, int userId) { 12714 if (!sUserManager.exists(userId)) return null; 12715 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12716 return null; 12717 } 12718 final PackageParser.Activity activity = info.activity; 12719 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12720 if (ps == null) { 12721 return null; 12722 } 12723 final PackageUserState userState = ps.readUserState(userId); 12724 ActivityInfo ai = 12725 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 12726 if (ai == null) { 12727 return null; 12728 } 12729 final boolean matchExplicitlyVisibleOnly = 12730 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12731 final boolean matchVisibleToInstantApp = 12732 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12733 final boolean componentVisible = 12734 matchVisibleToInstantApp 12735 && info.isVisibleToInstantApp() 12736 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12737 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12738 // throw out filters that aren't visible to ephemeral apps 12739 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12740 return null; 12741 } 12742 // throw out instant app filters if we're not explicitly requesting them 12743 if (!matchInstantApp && userState.instantApp) { 12744 return null; 12745 } 12746 // throw out instant app filters if updates are available; will trigger 12747 // instant app resolution 12748 if (userState.instantApp && ps.isUpdateAvailable()) { 12749 return null; 12750 } 12751 final ResolveInfo res = new ResolveInfo(); 12752 res.activityInfo = ai; 12753 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12754 res.filter = info; 12755 } 12756 if (info != null) { 12757 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12758 } 12759 res.priority = info.getPriority(); 12760 res.preferredOrder = activity.owner.mPreferredOrder; 12761 //System.out.println("Result: " + res.activityInfo.className + 12762 // " = " + res.priority); 12763 res.match = match; 12764 res.isDefault = info.hasDefault; 12765 res.labelRes = info.labelRes; 12766 res.nonLocalizedLabel = info.nonLocalizedLabel; 12767 if (userNeedsBadging(userId)) { 12768 res.noResourceId = true; 12769 } else { 12770 res.icon = info.icon; 12771 } 12772 res.iconResourceId = info.icon; 12773 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12774 res.isInstantAppAvailable = userState.instantApp; 12775 return res; 12776 } 12777 12778 @Override 12779 protected void sortResults(List<ResolveInfo> results) { 12780 Collections.sort(results, mResolvePrioritySorter); 12781 } 12782 12783 @Override 12784 protected void dumpFilter(PrintWriter out, String prefix, 12785 PackageParser.ActivityIntentInfo filter) { 12786 out.print(prefix); out.print( 12787 Integer.toHexString(System.identityHashCode(filter.activity))); 12788 out.print(' '); 12789 filter.activity.printComponentShortName(out); 12790 out.print(" filter "); 12791 out.println(Integer.toHexString(System.identityHashCode(filter))); 12792 } 12793 12794 @Override 12795 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12796 return filter.activity; 12797 } 12798 12799 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12800 PackageParser.Activity activity = (PackageParser.Activity)label; 12801 out.print(prefix); out.print( 12802 Integer.toHexString(System.identityHashCode(activity))); 12803 out.print(' '); 12804 activity.printComponentShortName(out); 12805 if (count > 1) { 12806 out.print(" ("); out.print(count); out.print(" filters)"); 12807 } 12808 out.println(); 12809 } 12810 12811 // Keys are String (activity class name), values are Activity. 12812 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12813 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12814 private int mFlags; 12815 } 12816 12817 private final class ServiceIntentResolver 12818 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12819 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12820 boolean defaultOnly, int userId) { 12821 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12822 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12823 } 12824 12825 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12826 int userId) { 12827 if (!sUserManager.exists(userId)) return null; 12828 mFlags = flags; 12829 return super.queryIntent(intent, resolvedType, 12830 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12831 userId); 12832 } 12833 12834 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12835 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12836 if (!sUserManager.exists(userId)) return null; 12837 if (packageServices == null) { 12838 return null; 12839 } 12840 mFlags = flags; 12841 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12842 final int N = packageServices.size(); 12843 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12844 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12845 12846 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12847 for (int i = 0; i < N; ++i) { 12848 intentFilters = packageServices.get(i).intents; 12849 if (intentFilters != null && intentFilters.size() > 0) { 12850 PackageParser.ServiceIntentInfo[] array = 12851 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12852 intentFilters.toArray(array); 12853 listCut.add(array); 12854 } 12855 } 12856 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12857 } 12858 12859 public final void addService(PackageParser.Service s) { 12860 mServices.put(s.getComponentName(), s); 12861 if (DEBUG_SHOW_INFO) { 12862 Log.v(TAG, " " 12863 + (s.info.nonLocalizedLabel != null 12864 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12865 Log.v(TAG, " Class=" + s.info.name); 12866 } 12867 final int NI = s.intents.size(); 12868 int j; 12869 for (j=0; j<NI; j++) { 12870 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12871 if (DEBUG_SHOW_INFO) { 12872 Log.v(TAG, " IntentFilter:"); 12873 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12874 } 12875 if (!intent.debugCheck()) { 12876 Log.w(TAG, "==> For Service " + s.info.name); 12877 } 12878 addFilter(intent); 12879 } 12880 } 12881 12882 public final void removeService(PackageParser.Service s) { 12883 mServices.remove(s.getComponentName()); 12884 if (DEBUG_SHOW_INFO) { 12885 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12886 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12887 Log.v(TAG, " Class=" + s.info.name); 12888 } 12889 final int NI = s.intents.size(); 12890 int j; 12891 for (j=0; j<NI; j++) { 12892 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12893 if (DEBUG_SHOW_INFO) { 12894 Log.v(TAG, " IntentFilter:"); 12895 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12896 } 12897 removeFilter(intent); 12898 } 12899 } 12900 12901 @Override 12902 protected boolean allowFilterResult( 12903 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12904 ServiceInfo filterSi = filter.service.info; 12905 for (int i=dest.size()-1; i>=0; i--) { 12906 ServiceInfo destAi = dest.get(i).serviceInfo; 12907 if (destAi.name == filterSi.name 12908 && destAi.packageName == filterSi.packageName) { 12909 return false; 12910 } 12911 } 12912 return true; 12913 } 12914 12915 @Override 12916 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12917 return new PackageParser.ServiceIntentInfo[size]; 12918 } 12919 12920 @Override 12921 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12922 if (!sUserManager.exists(userId)) return true; 12923 PackageParser.Package p = filter.service.owner; 12924 if (p != null) { 12925 PackageSetting ps = (PackageSetting)p.mExtras; 12926 if (ps != null) { 12927 // System apps are never considered stopped for purposes of 12928 // filtering, because there may be no way for the user to 12929 // actually re-launch them. 12930 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12931 && ps.getStopped(userId); 12932 } 12933 } 12934 return false; 12935 } 12936 12937 @Override 12938 protected boolean isPackageForFilter(String packageName, 12939 PackageParser.ServiceIntentInfo info) { 12940 return packageName.equals(info.service.owner.packageName); 12941 } 12942 12943 @Override 12944 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12945 int match, int userId) { 12946 if (!sUserManager.exists(userId)) return null; 12947 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12948 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12949 return null; 12950 } 12951 final PackageParser.Service service = info.service; 12952 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12953 if (ps == null) { 12954 return null; 12955 } 12956 final PackageUserState userState = ps.readUserState(userId); 12957 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12958 userState, userId); 12959 if (si == null) { 12960 return null; 12961 } 12962 final boolean matchVisibleToInstantApp = 12963 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12964 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12965 // throw out filters that aren't visible to ephemeral apps 12966 if (matchVisibleToInstantApp 12967 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12968 return null; 12969 } 12970 // throw out ephemeral filters if we're not explicitly requesting them 12971 if (!isInstantApp && userState.instantApp) { 12972 return null; 12973 } 12974 // throw out instant app filters if updates are available; will trigger 12975 // instant app resolution 12976 if (userState.instantApp && ps.isUpdateAvailable()) { 12977 return null; 12978 } 12979 final ResolveInfo res = new ResolveInfo(); 12980 res.serviceInfo = si; 12981 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12982 res.filter = filter; 12983 } 12984 res.priority = info.getPriority(); 12985 res.preferredOrder = service.owner.mPreferredOrder; 12986 res.match = match; 12987 res.isDefault = info.hasDefault; 12988 res.labelRes = info.labelRes; 12989 res.nonLocalizedLabel = info.nonLocalizedLabel; 12990 res.icon = info.icon; 12991 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12992 return res; 12993 } 12994 12995 @Override 12996 protected void sortResults(List<ResolveInfo> results) { 12997 Collections.sort(results, mResolvePrioritySorter); 12998 } 12999 13000 @Override 13001 protected void dumpFilter(PrintWriter out, String prefix, 13002 PackageParser.ServiceIntentInfo filter) { 13003 out.print(prefix); out.print( 13004 Integer.toHexString(System.identityHashCode(filter.service))); 13005 out.print(' '); 13006 filter.service.printComponentShortName(out); 13007 out.print(" filter "); 13008 out.print(Integer.toHexString(System.identityHashCode(filter))); 13009 if (filter.service.info.permission != null) { 13010 out.print(" permission "); out.println(filter.service.info.permission); 13011 } else { 13012 out.println(); 13013 } 13014 } 13015 13016 @Override 13017 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 13018 return filter.service; 13019 } 13020 13021 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13022 PackageParser.Service service = (PackageParser.Service)label; 13023 out.print(prefix); out.print( 13024 Integer.toHexString(System.identityHashCode(service))); 13025 out.print(' '); 13026 service.printComponentShortName(out); 13027 if (count > 1) { 13028 out.print(" ("); out.print(count); out.print(" filters)"); 13029 } 13030 out.println(); 13031 } 13032 13033// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 13034// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 13035// final List<ResolveInfo> retList = Lists.newArrayList(); 13036// while (i.hasNext()) { 13037// final ResolveInfo resolveInfo = (ResolveInfo) i; 13038// if (isEnabledLP(resolveInfo.serviceInfo)) { 13039// retList.add(resolveInfo); 13040// } 13041// } 13042// return retList; 13043// } 13044 13045 // Keys are String (activity class name), values are Activity. 13046 private final ArrayMap<ComponentName, PackageParser.Service> mServices 13047 = new ArrayMap<ComponentName, PackageParser.Service>(); 13048 private int mFlags; 13049 } 13050 13051 private final class ProviderIntentResolver 13052 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 13053 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 13054 boolean defaultOnly, int userId) { 13055 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 13056 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 13057 } 13058 13059 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 13060 int userId) { 13061 if (!sUserManager.exists(userId)) 13062 return null; 13063 mFlags = flags; 13064 return super.queryIntent(intent, resolvedType, 13065 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 13066 userId); 13067 } 13068 13069 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 13070 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 13071 if (!sUserManager.exists(userId)) 13072 return null; 13073 if (packageProviders == null) { 13074 return null; 13075 } 13076 mFlags = flags; 13077 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 13078 final int N = packageProviders.size(); 13079 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 13080 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 13081 13082 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 13083 for (int i = 0; i < N; ++i) { 13084 intentFilters = packageProviders.get(i).intents; 13085 if (intentFilters != null && intentFilters.size() > 0) { 13086 PackageParser.ProviderIntentInfo[] array = 13087 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 13088 intentFilters.toArray(array); 13089 listCut.add(array); 13090 } 13091 } 13092 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 13093 } 13094 13095 public final void addProvider(PackageParser.Provider p) { 13096 if (mProviders.containsKey(p.getComponentName())) { 13097 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 13098 return; 13099 } 13100 13101 mProviders.put(p.getComponentName(), p); 13102 if (DEBUG_SHOW_INFO) { 13103 Log.v(TAG, " " 13104 + (p.info.nonLocalizedLabel != null 13105 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13106 Log.v(TAG, " Class=" + p.info.name); 13107 } 13108 final int NI = p.intents.size(); 13109 int j; 13110 for (j = 0; j < NI; j++) { 13111 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13112 if (DEBUG_SHOW_INFO) { 13113 Log.v(TAG, " IntentFilter:"); 13114 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13115 } 13116 if (!intent.debugCheck()) { 13117 Log.w(TAG, "==> For Provider " + p.info.name); 13118 } 13119 addFilter(intent); 13120 } 13121 } 13122 13123 public final void removeProvider(PackageParser.Provider p) { 13124 mProviders.remove(p.getComponentName()); 13125 if (DEBUG_SHOW_INFO) { 13126 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 13127 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13128 Log.v(TAG, " Class=" + p.info.name); 13129 } 13130 final int NI = p.intents.size(); 13131 int j; 13132 for (j = 0; j < NI; j++) { 13133 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13134 if (DEBUG_SHOW_INFO) { 13135 Log.v(TAG, " IntentFilter:"); 13136 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13137 } 13138 removeFilter(intent); 13139 } 13140 } 13141 13142 @Override 13143 protected boolean allowFilterResult( 13144 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 13145 ProviderInfo filterPi = filter.provider.info; 13146 for (int i = dest.size() - 1; i >= 0; i--) { 13147 ProviderInfo destPi = dest.get(i).providerInfo; 13148 if (destPi.name == filterPi.name 13149 && destPi.packageName == filterPi.packageName) { 13150 return false; 13151 } 13152 } 13153 return true; 13154 } 13155 13156 @Override 13157 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 13158 return new PackageParser.ProviderIntentInfo[size]; 13159 } 13160 13161 @Override 13162 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 13163 if (!sUserManager.exists(userId)) 13164 return true; 13165 PackageParser.Package p = filter.provider.owner; 13166 if (p != null) { 13167 PackageSetting ps = (PackageSetting) p.mExtras; 13168 if (ps != null) { 13169 // System apps are never considered stopped for purposes of 13170 // filtering, because there may be no way for the user to 13171 // actually re-launch them. 13172 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 13173 && ps.getStopped(userId); 13174 } 13175 } 13176 return false; 13177 } 13178 13179 @Override 13180 protected boolean isPackageForFilter(String packageName, 13181 PackageParser.ProviderIntentInfo info) { 13182 return packageName.equals(info.provider.owner.packageName); 13183 } 13184 13185 @Override 13186 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 13187 int match, int userId) { 13188 if (!sUserManager.exists(userId)) 13189 return null; 13190 final PackageParser.ProviderIntentInfo info = filter; 13191 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 13192 return null; 13193 } 13194 final PackageParser.Provider provider = info.provider; 13195 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 13196 if (ps == null) { 13197 return null; 13198 } 13199 final PackageUserState userState = ps.readUserState(userId); 13200 final boolean matchVisibleToInstantApp = 13201 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13202 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13203 // throw out filters that aren't visible to instant applications 13204 if (matchVisibleToInstantApp 13205 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 13206 return null; 13207 } 13208 // throw out instant application filters if we're not explicitly requesting them 13209 if (!isInstantApp && userState.instantApp) { 13210 return null; 13211 } 13212 // throw out instant application filters if updates are available; will trigger 13213 // instant application resolution 13214 if (userState.instantApp && ps.isUpdateAvailable()) { 13215 return null; 13216 } 13217 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 13218 userState, userId); 13219 if (pi == null) { 13220 return null; 13221 } 13222 final ResolveInfo res = new ResolveInfo(); 13223 res.providerInfo = pi; 13224 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 13225 res.filter = filter; 13226 } 13227 res.priority = info.getPriority(); 13228 res.preferredOrder = provider.owner.mPreferredOrder; 13229 res.match = match; 13230 res.isDefault = info.hasDefault; 13231 res.labelRes = info.labelRes; 13232 res.nonLocalizedLabel = info.nonLocalizedLabel; 13233 res.icon = info.icon; 13234 res.system = res.providerInfo.applicationInfo.isSystemApp(); 13235 return res; 13236 } 13237 13238 @Override 13239 protected void sortResults(List<ResolveInfo> results) { 13240 Collections.sort(results, mResolvePrioritySorter); 13241 } 13242 13243 @Override 13244 protected void dumpFilter(PrintWriter out, String prefix, 13245 PackageParser.ProviderIntentInfo filter) { 13246 out.print(prefix); 13247 out.print( 13248 Integer.toHexString(System.identityHashCode(filter.provider))); 13249 out.print(' '); 13250 filter.provider.printComponentShortName(out); 13251 out.print(" filter "); 13252 out.println(Integer.toHexString(System.identityHashCode(filter))); 13253 } 13254 13255 @Override 13256 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 13257 return filter.provider; 13258 } 13259 13260 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13261 PackageParser.Provider provider = (PackageParser.Provider)label; 13262 out.print(prefix); out.print( 13263 Integer.toHexString(System.identityHashCode(provider))); 13264 out.print(' '); 13265 provider.printComponentShortName(out); 13266 if (count > 1) { 13267 out.print(" ("); out.print(count); out.print(" filters)"); 13268 } 13269 out.println(); 13270 } 13271 13272 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 13273 = new ArrayMap<ComponentName, PackageParser.Provider>(); 13274 private int mFlags; 13275 } 13276 13277 static final class InstantAppIntentResolver 13278 extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter, 13279 AuxiliaryResolveInfo.AuxiliaryFilter> { 13280 /** 13281 * The result that has the highest defined order. Ordering applies on a 13282 * per-package basis. Mapping is from package name to Pair of order and 13283 * EphemeralResolveInfo. 13284 * <p> 13285 * NOTE: This is implemented as a field variable for convenience and efficiency. 13286 * By having a field variable, we're able to track filter ordering as soon as 13287 * a non-zero order is defined. Otherwise, multiple loops across the result set 13288 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 13289 * this needs to be contained entirely within {@link #filterResults}. 13290 */ 13291 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 13292 13293 @Override 13294 protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) { 13295 return new AuxiliaryResolveInfo.AuxiliaryFilter[size]; 13296 } 13297 13298 @Override 13299 protected boolean isPackageForFilter(String packageName, 13300 AuxiliaryResolveInfo.AuxiliaryFilter responseObj) { 13301 return true; 13302 } 13303 13304 @Override 13305 protected AuxiliaryResolveInfo.AuxiliaryFilter newResult( 13306 AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) { 13307 if (!sUserManager.exists(userId)) { 13308 return null; 13309 } 13310 final String packageName = responseObj.resolveInfo.getPackageName(); 13311 final Integer order = responseObj.getOrder(); 13312 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 13313 mOrderResult.get(packageName); 13314 // ordering is enabled and this item's order isn't high enough 13315 if (lastOrderResult != null && lastOrderResult.first >= order) { 13316 return null; 13317 } 13318 final InstantAppResolveInfo res = responseObj.resolveInfo; 13319 if (order > 0) { 13320 // non-zero order, enable ordering 13321 mOrderResult.put(packageName, new Pair<>(order, res)); 13322 } 13323 return responseObj; 13324 } 13325 13326 @Override 13327 protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) { 13328 // only do work if ordering is enabled [most of the time it won't be] 13329 if (mOrderResult.size() == 0) { 13330 return; 13331 } 13332 int resultSize = results.size(); 13333 for (int i = 0; i < resultSize; i++) { 13334 final InstantAppResolveInfo info = results.get(i).resolveInfo; 13335 final String packageName = info.getPackageName(); 13336 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 13337 if (savedInfo == null) { 13338 // package doesn't having ordering 13339 continue; 13340 } 13341 if (savedInfo.second == info) { 13342 // circled back to the highest ordered item; remove from order list 13343 mOrderResult.remove(packageName); 13344 if (mOrderResult.size() == 0) { 13345 // no more ordered items 13346 break; 13347 } 13348 continue; 13349 } 13350 // item has a worse order, remove it from the result list 13351 results.remove(i); 13352 resultSize--; 13353 i--; 13354 } 13355 } 13356 } 13357 13358 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 13359 new Comparator<ResolveInfo>() { 13360 public int compare(ResolveInfo r1, ResolveInfo r2) { 13361 int v1 = r1.priority; 13362 int v2 = r2.priority; 13363 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 13364 if (v1 != v2) { 13365 return (v1 > v2) ? -1 : 1; 13366 } 13367 v1 = r1.preferredOrder; 13368 v2 = r2.preferredOrder; 13369 if (v1 != v2) { 13370 return (v1 > v2) ? -1 : 1; 13371 } 13372 if (r1.isDefault != r2.isDefault) { 13373 return r1.isDefault ? -1 : 1; 13374 } 13375 v1 = r1.match; 13376 v2 = r2.match; 13377 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13378 if (v1 != v2) { 13379 return (v1 > v2) ? -1 : 1; 13380 } 13381 if (r1.system != r2.system) { 13382 return r1.system ? -1 : 1; 13383 } 13384 if (r1.activityInfo != null) { 13385 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13386 } 13387 if (r1.serviceInfo != null) { 13388 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13389 } 13390 if (r1.providerInfo != null) { 13391 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13392 } 13393 return 0; 13394 } 13395 }; 13396 13397 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13398 new Comparator<ProviderInfo>() { 13399 public int compare(ProviderInfo p1, ProviderInfo p2) { 13400 final int v1 = p1.initOrder; 13401 final int v2 = p2.initOrder; 13402 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13403 } 13404 }; 13405 13406 @Override 13407 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13408 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13409 final int[] userIds, int[] instantUserIds) { 13410 mHandler.post(new Runnable() { 13411 @Override 13412 public void run() { 13413 try { 13414 final IActivityManager am = ActivityManager.getService(); 13415 if (am == null) return; 13416 final int[] resolvedUserIds; 13417 if (userIds == null) { 13418 resolvedUserIds = am.getRunningUserIds(); 13419 } else { 13420 resolvedUserIds = userIds; 13421 } 13422 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13423 resolvedUserIds, false); 13424 if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) { 13425 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13426 instantUserIds, true); 13427 } 13428 } catch (RemoteException ex) { 13429 } 13430 } 13431 }); 13432 } 13433 13434 @Override 13435 public void notifyPackageAdded(String packageName) { 13436 final PackageListObserver[] observers; 13437 synchronized (mPackages) { 13438 if (mPackageListObservers.size() == 0) { 13439 return; 13440 } 13441 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13442 } 13443 for (int i = observers.length - 1; i >= 0; --i) { 13444 observers[i].onPackageAdded(packageName); 13445 } 13446 } 13447 13448 @Override 13449 public void notifyPackageRemoved(String packageName) { 13450 final PackageListObserver[] observers; 13451 synchronized (mPackages) { 13452 if (mPackageListObservers.size() == 0) { 13453 return; 13454 } 13455 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13456 } 13457 for (int i = observers.length - 1; i >= 0; --i) { 13458 observers[i].onPackageRemoved(packageName); 13459 } 13460 } 13461 13462 /** 13463 * Sends a broadcast for the given action. 13464 * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with 13465 * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows 13466 * the system and applications allowed to see instant applications to receive package 13467 * lifecycle events for instant applications. 13468 */ 13469 private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras, 13470 int flags, String targetPkg, IIntentReceiver finishedReceiver, 13471 int[] userIds, boolean isInstantApp) 13472 throws RemoteException { 13473 for (int id : userIds) { 13474 final Intent intent = new Intent(action, 13475 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13476 final String[] requiredPermissions = 13477 isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null; 13478 if (extras != null) { 13479 intent.putExtras(extras); 13480 } 13481 if (targetPkg != null) { 13482 intent.setPackage(targetPkg); 13483 } 13484 // Modify the UID when posting to other users 13485 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13486 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13487 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13488 intent.putExtra(Intent.EXTRA_UID, uid); 13489 } 13490 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13491 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13492 if (DEBUG_BROADCASTS) { 13493 RuntimeException here = new RuntimeException("here"); 13494 here.fillInStackTrace(); 13495 Slog.d(TAG, "Sending to user " + id + ": " 13496 + intent.toShortString(false, true, false, false) 13497 + " " + intent.getExtras(), here); 13498 } 13499 am.broadcastIntent(null, intent, null, finishedReceiver, 13500 0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE, 13501 null, finishedReceiver != null, false, id); 13502 } 13503 } 13504 13505 /** 13506 * Check if the external storage media is available. This is true if there 13507 * is a mounted external storage medium or if the external storage is 13508 * emulated. 13509 */ 13510 private boolean isExternalMediaAvailable() { 13511 return mMediaMounted || Environment.isExternalStorageEmulated(); 13512 } 13513 13514 @Override 13515 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13516 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 13517 return null; 13518 } 13519 if (!isExternalMediaAvailable()) { 13520 // If the external storage is no longer mounted at this point, 13521 // the caller may not have been able to delete all of this 13522 // packages files and can not delete any more. Bail. 13523 return null; 13524 } 13525 synchronized (mPackages) { 13526 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13527 if (lastPackage != null) { 13528 pkgs.remove(lastPackage); 13529 } 13530 if (pkgs.size() > 0) { 13531 return pkgs.get(0); 13532 } 13533 } 13534 return null; 13535 } 13536 13537 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13538 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13539 userId, andCode ? 1 : 0, packageName); 13540 if (mSystemReady) { 13541 msg.sendToTarget(); 13542 } else { 13543 if (mPostSystemReadyMessages == null) { 13544 mPostSystemReadyMessages = new ArrayList<>(); 13545 } 13546 mPostSystemReadyMessages.add(msg); 13547 } 13548 } 13549 13550 void startCleaningPackages() { 13551 // reader 13552 if (!isExternalMediaAvailable()) { 13553 return; 13554 } 13555 synchronized (mPackages) { 13556 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13557 return; 13558 } 13559 } 13560 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13561 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13562 IActivityManager am = ActivityManager.getService(); 13563 if (am != null) { 13564 int dcsUid = -1; 13565 synchronized (mPackages) { 13566 if (!mDefaultContainerWhitelisted) { 13567 mDefaultContainerWhitelisted = true; 13568 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13569 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13570 } 13571 } 13572 try { 13573 if (dcsUid > 0) { 13574 am.backgroundWhitelistUid(dcsUid); 13575 } 13576 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13577 UserHandle.USER_SYSTEM); 13578 } catch (RemoteException e) { 13579 } 13580 } 13581 } 13582 13583 /** 13584 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13585 * it is acting on behalf on an enterprise or the user). 13586 * 13587 * Note that the ordering of the conditionals in this method is important. The checks we perform 13588 * are as follows, in this order: 13589 * 13590 * 1) If the install is being performed by a system app, we can trust the app to have set the 13591 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13592 * what it is. 13593 * 2) If the install is being performed by a device or profile owner app, the install reason 13594 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13595 * set the install reason correctly. If the app targets an older SDK version where install 13596 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13597 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13598 * 3) In all other cases, the install is being performed by a regular app that is neither part 13599 * of the system nor a device or profile owner. We have no reason to believe that this app is 13600 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13601 * set to enterprise policy and if so, change it to unknown instead. 13602 */ 13603 private int fixUpInstallReason(String installerPackageName, int installerUid, 13604 int installReason) { 13605 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13606 == PERMISSION_GRANTED) { 13607 // If the install is being performed by a system app, we trust that app to have set the 13608 // install reason correctly. 13609 return installReason; 13610 } 13611 13612 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13613 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13614 if (dpm != null) { 13615 ComponentName owner = null; 13616 try { 13617 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13618 if (owner == null) { 13619 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13620 } 13621 } catch (RemoteException e) { 13622 } 13623 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13624 // If the install is being performed by a device or profile owner, the install 13625 // reason should be enterprise policy. 13626 return PackageManager.INSTALL_REASON_POLICY; 13627 } 13628 } 13629 13630 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13631 // If the install is being performed by a regular app (i.e. neither system app nor 13632 // device or profile owner), we have no reason to believe that the app is acting on 13633 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13634 // change it to unknown instead. 13635 return PackageManager.INSTALL_REASON_UNKNOWN; 13636 } 13637 13638 // If the install is being performed by a regular app and the install reason was set to any 13639 // value but enterprise policy, leave the install reason unchanged. 13640 return installReason; 13641 } 13642 13643 /** 13644 * Attempts to bind to the default container service explicitly instead of doing so lazily on 13645 * install commit. 13646 */ 13647 void earlyBindToDefContainer() { 13648 mHandler.sendMessage(mHandler.obtainMessage(DEF_CONTAINER_BIND)); 13649 } 13650 13651 void installStage(String packageName, File stagedDir, 13652 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13653 String installerPackageName, int installerUid, UserHandle user, 13654 PackageParser.SigningDetails signingDetails) { 13655 if (DEBUG_INSTANT) { 13656 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13657 Slog.d(TAG, "Ephemeral install of " + packageName); 13658 } 13659 } 13660 final VerificationInfo verificationInfo = new VerificationInfo( 13661 sessionParams.originatingUri, sessionParams.referrerUri, 13662 sessionParams.originatingUid, installerUid); 13663 13664 final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir); 13665 13666 final Message msg = mHandler.obtainMessage(INIT_COPY); 13667 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13668 sessionParams.installReason); 13669 final InstallParams params = new InstallParams(origin, null, observer, 13670 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13671 verificationInfo, user, sessionParams.abiOverride, 13672 sessionParams.grantedRuntimePermissions, signingDetails, installReason); 13673 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13674 msg.obj = params; 13675 13676 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13677 System.identityHashCode(msg.obj)); 13678 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13679 System.identityHashCode(msg.obj)); 13680 13681 mHandler.sendMessage(msg); 13682 } 13683 13684 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13685 int userId) { 13686 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13687 final boolean isInstantApp = pkgSetting.getInstantApp(userId); 13688 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 13689 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 13690 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 13691 false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds); 13692 13693 // Send a session commit broadcast 13694 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 13695 info.installReason = pkgSetting.getInstallReason(userId); 13696 info.appPackageName = packageName; 13697 sendSessionCommitBroadcast(info, userId); 13698 } 13699 13700 @Override 13701 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 13702 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) { 13703 if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) { 13704 return; 13705 } 13706 Bundle extras = new Bundle(1); 13707 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13708 final int uid = UserHandle.getUid( 13709 (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId); 13710 extras.putInt(Intent.EXTRA_UID, uid); 13711 13712 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13713 packageName, extras, 0, null, null, userIds, instantUserIds); 13714 if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) { 13715 mHandler.post(() -> { 13716 for (int userId : userIds) { 13717 sendBootCompletedBroadcastToSystemApp( 13718 packageName, includeStopped, userId); 13719 } 13720 } 13721 ); 13722 } 13723 } 13724 13725 /** 13726 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13727 * automatically without needing an explicit launch. 13728 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13729 */ 13730 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 13731 int userId) { 13732 // If user is not running, the app didn't miss any broadcast 13733 if (!mUserManagerInternal.isUserRunning(userId)) { 13734 return; 13735 } 13736 final IActivityManager am = ActivityManager.getService(); 13737 try { 13738 // Deliver LOCKED_BOOT_COMPLETED first 13739 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13740 .setPackage(packageName); 13741 if (includeStopped) { 13742 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13743 } 13744 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13745 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13746 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13747 13748 // Deliver BOOT_COMPLETED only if user is unlocked 13749 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13750 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13751 if (includeStopped) { 13752 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13753 } 13754 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13755 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13756 } 13757 } catch (RemoteException e) { 13758 throw e.rethrowFromSystemServer(); 13759 } 13760 } 13761 13762 @Override 13763 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13764 int userId) { 13765 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13766 PackageSetting pkgSetting; 13767 final int callingUid = Binder.getCallingUid(); 13768 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13769 true /* requireFullPermission */, true /* checkShell */, 13770 "setApplicationHiddenSetting for user " + userId); 13771 13772 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13773 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13774 return false; 13775 } 13776 13777 long callingId = Binder.clearCallingIdentity(); 13778 try { 13779 boolean sendAdded = false; 13780 boolean sendRemoved = false; 13781 // writer 13782 synchronized (mPackages) { 13783 pkgSetting = mSettings.mPackages.get(packageName); 13784 if (pkgSetting == null) { 13785 return false; 13786 } 13787 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13788 return false; 13789 } 13790 // Do not allow "android" is being disabled 13791 if ("android".equals(packageName)) { 13792 Slog.w(TAG, "Cannot hide package: android"); 13793 return false; 13794 } 13795 // Cannot hide static shared libs as they are considered 13796 // a part of the using app (emulating static linking). Also 13797 // static libs are installed always on internal storage. 13798 PackageParser.Package pkg = mPackages.get(packageName); 13799 if (pkg != null && pkg.staticSharedLibName != null) { 13800 Slog.w(TAG, "Cannot hide package: " + packageName 13801 + " providing static shared library: " 13802 + pkg.staticSharedLibName); 13803 return false; 13804 } 13805 // Only allow protected packages to hide themselves. 13806 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 13807 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13808 Slog.w(TAG, "Not hiding protected package: " + packageName); 13809 return false; 13810 } 13811 13812 if (pkgSetting.getHidden(userId) != hidden) { 13813 pkgSetting.setHidden(hidden, userId); 13814 mSettings.writePackageRestrictionsLPr(userId); 13815 if (hidden) { 13816 sendRemoved = true; 13817 } else { 13818 sendAdded = true; 13819 } 13820 } 13821 } 13822 if (sendAdded) { 13823 sendPackageAddedForUser(packageName, pkgSetting, userId); 13824 return true; 13825 } 13826 if (sendRemoved) { 13827 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13828 "hiding pkg"); 13829 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13830 return true; 13831 } 13832 } finally { 13833 Binder.restoreCallingIdentity(callingId); 13834 } 13835 return false; 13836 } 13837 13838 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13839 int userId) { 13840 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13841 info.removedPackage = packageName; 13842 info.installerPackageName = pkgSetting.installerPackageName; 13843 info.removedUsers = new int[] {userId}; 13844 info.broadcastUsers = new int[] {userId}; 13845 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13846 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13847 } 13848 13849 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended, 13850 PersistableBundle launcherExtras) { 13851 if (pkgList.length > 0) { 13852 Bundle extras = new Bundle(1); 13853 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13854 if (launcherExtras != null) { 13855 extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS, 13856 new Bundle(launcherExtras.deepCopy())); 13857 } 13858 sendPackageBroadcast( 13859 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13860 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13861 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13862 new int[] {userId}, null); 13863 } 13864 } 13865 13866 /** 13867 * Returns true if application is not found or there was an error. Otherwise it returns 13868 * the hidden state of the package for the given user. 13869 */ 13870 @Override 13871 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13872 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13873 final int callingUid = Binder.getCallingUid(); 13874 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13875 true /* requireFullPermission */, false /* checkShell */, 13876 "getApplicationHidden for user " + userId); 13877 PackageSetting ps; 13878 long callingId = Binder.clearCallingIdentity(); 13879 try { 13880 // writer 13881 synchronized (mPackages) { 13882 ps = mSettings.mPackages.get(packageName); 13883 if (ps == null) { 13884 return true; 13885 } 13886 if (filterAppAccessLPr(ps, callingUid, userId)) { 13887 return true; 13888 } 13889 return ps.getHidden(userId); 13890 } 13891 } finally { 13892 Binder.restoreCallingIdentity(callingId); 13893 } 13894 } 13895 13896 /** 13897 * @hide 13898 */ 13899 @Override 13900 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13901 int installReason) { 13902 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13903 null); 13904 PackageSetting pkgSetting; 13905 final int callingUid = Binder.getCallingUid(); 13906 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13907 true /* requireFullPermission */, true /* checkShell */, 13908 "installExistingPackage for user " + userId); 13909 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13910 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13911 } 13912 13913 long callingId = Binder.clearCallingIdentity(); 13914 try { 13915 boolean installed = false; 13916 final boolean instantApp = 13917 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13918 final boolean fullApp = 13919 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13920 13921 // writer 13922 synchronized (mPackages) { 13923 pkgSetting = mSettings.mPackages.get(packageName); 13924 if (pkgSetting == null) { 13925 return PackageManager.INSTALL_FAILED_INVALID_URI; 13926 } 13927 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 13928 // only allow the existing package to be used if it's installed as a full 13929 // application for at least one user 13930 boolean installAllowed = false; 13931 for (int checkUserId : sUserManager.getUserIds()) { 13932 installAllowed = !pkgSetting.getInstantApp(checkUserId); 13933 if (installAllowed) { 13934 break; 13935 } 13936 } 13937 if (!installAllowed) { 13938 return PackageManager.INSTALL_FAILED_INVALID_URI; 13939 } 13940 } 13941 if (!pkgSetting.getInstalled(userId)) { 13942 pkgSetting.setInstalled(true, userId); 13943 pkgSetting.setHidden(false, userId); 13944 pkgSetting.setInstallReason(installReason, userId); 13945 mSettings.writePackageRestrictionsLPr(userId); 13946 mSettings.writeKernelMappingLPr(pkgSetting); 13947 installed = true; 13948 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13949 // upgrade app from instant to full; we don't allow app downgrade 13950 installed = true; 13951 } 13952 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13953 } 13954 13955 if (installed) { 13956 if (pkgSetting.pkg != null) { 13957 synchronized (mInstallLock) { 13958 // We don't need to freeze for a brand new install 13959 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13960 } 13961 } 13962 sendPackageAddedForUser(packageName, pkgSetting, userId); 13963 synchronized (mPackages) { 13964 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 13965 } 13966 } 13967 } finally { 13968 Binder.restoreCallingIdentity(callingId); 13969 } 13970 13971 return PackageManager.INSTALL_SUCCEEDED; 13972 } 13973 13974 static void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13975 boolean instantApp, boolean fullApp) { 13976 // no state specified; do nothing 13977 if (!instantApp && !fullApp) { 13978 return; 13979 } 13980 if (userId != UserHandle.USER_ALL) { 13981 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13982 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13983 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13984 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13985 } 13986 } else { 13987 for (int currentUserId : sUserManager.getUserIds()) { 13988 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13989 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13990 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13991 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13992 } 13993 } 13994 } 13995 } 13996 13997 boolean isUserRestricted(int userId, String restrictionKey) { 13998 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13999 if (restrictions.getBoolean(restrictionKey, false)) { 14000 Log.w(TAG, "User is restricted: " + restrictionKey); 14001 return true; 14002 } 14003 return false; 14004 } 14005 14006 @Override 14007 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 14008 PersistableBundle appExtras, PersistableBundle launcherExtras, String dialogMessage, 14009 String callingPackage, int userId) { 14010 try { 14011 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null); 14012 } catch (SecurityException e) { 14013 mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS, 14014 "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or " 14015 + Manifest.permission.MANAGE_USERS); 14016 } 14017 final int callingUid = Binder.getCallingUid(); 14018 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 14019 true /* requireFullPermission */, true /* checkShell */, 14020 "setPackagesSuspended for user " + userId); 14021 if (callingUid != Process.ROOT_UID && 14022 !UserHandle.isSameApp(getPackageUid(callingPackage, 0, userId), callingUid)) { 14023 throw new IllegalArgumentException("CallingPackage " + callingPackage + " does not" 14024 + " belong to calling app id " + UserHandle.getAppId(callingUid)); 14025 } 14026 14027 if (ArrayUtils.isEmpty(packageNames)) { 14028 return packageNames; 14029 } 14030 14031 final List<String> changedPackagesList = new ArrayList<>(packageNames.length); 14032 final List<String> unactionedPackages = new ArrayList<>(packageNames.length); 14033 final long callingId = Binder.clearCallingIdentity(); 14034 try { 14035 synchronized (mPackages) { 14036 for (int i = 0; i < packageNames.length; i++) { 14037 final String packageName = packageNames[i]; 14038 if (callingPackage.equals(packageName)) { 14039 Slog.w(TAG, "Calling package: " + callingPackage + " trying to " 14040 + (suspended ? "" : "un") + "suspend itself. Ignoring"); 14041 unactionedPackages.add(packageName); 14042 continue; 14043 } 14044 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 14045 if (pkgSetting == null 14046 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 14047 Slog.w(TAG, "Could not find package setting for package: " + packageName 14048 + ". Skipping suspending/un-suspending."); 14049 unactionedPackages.add(packageName); 14050 continue; 14051 } 14052 if (!canSuspendPackageForUserLocked(packageName, userId)) { 14053 unactionedPackages.add(packageName); 14054 continue; 14055 } 14056 pkgSetting.setSuspended(suspended, callingPackage, dialogMessage, appExtras, 14057 launcherExtras, userId); 14058 changedPackagesList.add(packageName); 14059 } 14060 } 14061 } finally { 14062 Binder.restoreCallingIdentity(callingId); 14063 } 14064 if (!changedPackagesList.isEmpty()) { 14065 final String[] changedPackages = changedPackagesList.toArray( 14066 new String[changedPackagesList.size()]); 14067 sendPackagesSuspendedForUser(changedPackages, userId, suspended, launcherExtras); 14068 sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId); 14069 synchronized (mPackages) { 14070 scheduleWritePackageRestrictionsLocked(userId); 14071 } 14072 } 14073 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 14074 } 14075 14076 @Override 14077 public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) { 14078 final int callingUid = Binder.getCallingUid(); 14079 if (getPackageUid(packageName, 0, userId) != callingUid) { 14080 throw new SecurityException("Calling package " + packageName 14081 + " does not belong to calling uid " + callingUid); 14082 } 14083 synchronized (mPackages) { 14084 final PackageSetting ps = mSettings.mPackages.get(packageName); 14085 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 14086 throw new IllegalArgumentException("Unknown target package: " + packageName); 14087 } 14088 final PackageUserState packageUserState = ps.readUserState(userId); 14089 if (packageUserState.suspended) { 14090 return packageUserState.suspendedAppExtras; 14091 } 14092 return null; 14093 } 14094 } 14095 14096 private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended, 14097 PersistableBundle appExtras, int userId) { 14098 final String action; 14099 final Bundle intentExtras = new Bundle(); 14100 if (suspended) { 14101 action = Intent.ACTION_MY_PACKAGE_SUSPENDED; 14102 if (appExtras != null) { 14103 final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy()); 14104 intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras); 14105 } 14106 } else { 14107 action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED; 14108 } 14109 mHandler.post(new Runnable() { 14110 @Override 14111 public void run() { 14112 try { 14113 final IActivityManager am = ActivityManager.getService(); 14114 if (am == null) { 14115 Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ " 14116 + (suspended ? "" : "UN") + "SUSPENDED broadcasts"); 14117 return; 14118 } 14119 final int[] targetUserIds = new int[] {userId}; 14120 for (String packageName : affectedPackages) { 14121 doSendBroadcast(am, action, null, intentExtras, 14122 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null, 14123 targetUserIds, false); 14124 } 14125 } catch (RemoteException ex) { 14126 // Shouldn't happen as AMS is in the same process. 14127 } 14128 } 14129 }); 14130 } 14131 14132 @Override 14133 public boolean isPackageSuspendedForUser(String packageName, int userId) { 14134 final int callingUid = Binder.getCallingUid(); 14135 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 14136 true /* requireFullPermission */, false /* checkShell */, 14137 "isPackageSuspendedForUser for user " + userId); 14138 synchronized (mPackages) { 14139 final PackageSetting ps = mSettings.mPackages.get(packageName); 14140 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 14141 throw new IllegalArgumentException("Unknown target package: " + packageName); 14142 } 14143 return ps.getSuspended(userId); 14144 } 14145 } 14146 14147 void onSuspendingPackageRemoved(String packageName, int removedForUser) { 14148 final int[] userIds = (removedForUser == UserHandle.USER_ALL) ? sUserManager.getUserIds() 14149 : new int[] {removedForUser}; 14150 for (int userId : userIds) { 14151 List<String> affectedPackages = new ArrayList<>(); 14152 synchronized (mPackages) { 14153 for (PackageSetting ps : mSettings.mPackages.values()) { 14154 final PackageUserState pus = ps.readUserState(userId); 14155 if (pus.suspended && packageName.equals(pus.suspendingPackage)) { 14156 ps.setSuspended(false, null, null, null, null, userId); 14157 affectedPackages.add(ps.name); 14158 } 14159 } 14160 } 14161 if (!affectedPackages.isEmpty()) { 14162 final String[] packageArray = affectedPackages.toArray( 14163 new String[affectedPackages.size()]); 14164 sendMyPackageSuspendedOrUnsuspended(packageArray, false, null, userId); 14165 sendPackagesSuspendedForUser(packageArray, userId, false, null); 14166 } 14167 } 14168 } 14169 14170 @GuardedBy("mPackages") 14171 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 14172 if (isPackageDeviceAdmin(packageName, userId)) { 14173 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14174 + "\": has an active device admin"); 14175 return false; 14176 } 14177 14178 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 14179 if (packageName.equals(activeLauncherPackageName)) { 14180 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14181 + "\": contains the active launcher"); 14182 return false; 14183 } 14184 14185 if (packageName.equals(mRequiredInstallerPackage)) { 14186 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14187 + "\": required for package installation"); 14188 return false; 14189 } 14190 14191 if (packageName.equals(mRequiredUninstallerPackage)) { 14192 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14193 + "\": required for package uninstallation"); 14194 return false; 14195 } 14196 14197 if (packageName.equals(mRequiredVerifierPackage)) { 14198 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14199 + "\": required for package verification"); 14200 return false; 14201 } 14202 14203 if (packageName.equals(getDefaultDialerPackageName(userId))) { 14204 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14205 + "\": is the default dialer"); 14206 return false; 14207 } 14208 14209 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 14210 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14211 + "\": protected package"); 14212 return false; 14213 } 14214 14215 // Cannot suspend static shared libs as they are considered 14216 // a part of the using app (emulating static linking). Also 14217 // static libs are installed always on internal storage. 14218 PackageParser.Package pkg = mPackages.get(packageName); 14219 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 14220 Slog.w(TAG, "Cannot suspend package: " + packageName 14221 + " providing static shared library: " 14222 + pkg.staticSharedLibName); 14223 return false; 14224 } 14225 14226 if (PLATFORM_PACKAGE_NAME.equals(packageName)) { 14227 Slog.w(TAG, "Cannot suspend package: " + packageName); 14228 return false; 14229 } 14230 14231 return true; 14232 } 14233 14234 private String getActiveLauncherPackageName(int userId) { 14235 Intent intent = new Intent(Intent.ACTION_MAIN); 14236 intent.addCategory(Intent.CATEGORY_HOME); 14237 ResolveInfo resolveInfo = resolveIntent( 14238 intent, 14239 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 14240 PackageManager.MATCH_DEFAULT_ONLY, 14241 userId); 14242 14243 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 14244 } 14245 14246 private String getDefaultDialerPackageName(int userId) { 14247 synchronized (mPackages) { 14248 return mSettings.getDefaultDialerPackageNameLPw(userId); 14249 } 14250 } 14251 14252 @Override 14253 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 14254 mContext.enforceCallingOrSelfPermission( 14255 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14256 "Only package verification agents can verify applications"); 14257 14258 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14259 final PackageVerificationResponse response = new PackageVerificationResponse( 14260 verificationCode, Binder.getCallingUid()); 14261 msg.arg1 = id; 14262 msg.obj = response; 14263 mHandler.sendMessage(msg); 14264 } 14265 14266 @Override 14267 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 14268 long millisecondsToDelay) { 14269 mContext.enforceCallingOrSelfPermission( 14270 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14271 "Only package verification agents can extend verification timeouts"); 14272 14273 final PackageVerificationState state = mPendingVerification.get(id); 14274 final PackageVerificationResponse response = new PackageVerificationResponse( 14275 verificationCodeAtTimeout, Binder.getCallingUid()); 14276 14277 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 14278 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 14279 } 14280 if (millisecondsToDelay < 0) { 14281 millisecondsToDelay = 0; 14282 } 14283 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 14284 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 14285 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 14286 } 14287 14288 if ((state != null) && !state.timeoutExtended()) { 14289 state.extendTimeout(); 14290 14291 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14292 msg.arg1 = id; 14293 msg.obj = response; 14294 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 14295 } 14296 } 14297 14298 private void broadcastPackageVerified(int verificationId, Uri packageUri, 14299 int verificationCode, UserHandle user) { 14300 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 14301 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 14302 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14303 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14304 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 14305 14306 mContext.sendBroadcastAsUser(intent, user, 14307 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 14308 } 14309 14310 private ComponentName matchComponentForVerifier(String packageName, 14311 List<ResolveInfo> receivers) { 14312 ActivityInfo targetReceiver = null; 14313 14314 final int NR = receivers.size(); 14315 for (int i = 0; i < NR; i++) { 14316 final ResolveInfo info = receivers.get(i); 14317 if (info.activityInfo == null) { 14318 continue; 14319 } 14320 14321 if (packageName.equals(info.activityInfo.packageName)) { 14322 targetReceiver = info.activityInfo; 14323 break; 14324 } 14325 } 14326 14327 if (targetReceiver == null) { 14328 return null; 14329 } 14330 14331 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 14332 } 14333 14334 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 14335 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 14336 if (pkgInfo.verifiers.length == 0) { 14337 return null; 14338 } 14339 14340 final int N = pkgInfo.verifiers.length; 14341 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 14342 for (int i = 0; i < N; i++) { 14343 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 14344 14345 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 14346 receivers); 14347 if (comp == null) { 14348 continue; 14349 } 14350 14351 final int verifierUid = getUidForVerifier(verifierInfo); 14352 if (verifierUid == -1) { 14353 continue; 14354 } 14355 14356 if (DEBUG_VERIFY) { 14357 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 14358 + " with the correct signature"); 14359 } 14360 sufficientVerifiers.add(comp); 14361 verificationState.addSufficientVerifier(verifierUid); 14362 } 14363 14364 return sufficientVerifiers; 14365 } 14366 14367 private int getUidForVerifier(VerifierInfo verifierInfo) { 14368 synchronized (mPackages) { 14369 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 14370 if (pkg == null) { 14371 return -1; 14372 } else if (pkg.mSigningDetails.signatures.length != 1) { 14373 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14374 + " has more than one signature; ignoring"); 14375 return -1; 14376 } 14377 14378 /* 14379 * If the public key of the package's signature does not match 14380 * our expected public key, then this is a different package and 14381 * we should skip. 14382 */ 14383 14384 final byte[] expectedPublicKey; 14385 try { 14386 final Signature verifierSig = pkg.mSigningDetails.signatures[0]; 14387 final PublicKey publicKey = verifierSig.getPublicKey(); 14388 expectedPublicKey = publicKey.getEncoded(); 14389 } catch (CertificateException e) { 14390 return -1; 14391 } 14392 14393 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 14394 14395 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 14396 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14397 + " does not have the expected public key; ignoring"); 14398 return -1; 14399 } 14400 14401 return pkg.applicationInfo.uid; 14402 } 14403 } 14404 14405 @Override 14406 public void finishPackageInstall(int token, boolean didLaunch) { 14407 enforceSystemOrRoot("Only the system is allowed to finish installs"); 14408 14409 if (DEBUG_INSTALL) { 14410 Slog.v(TAG, "BM finishing package install for " + token); 14411 } 14412 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14413 14414 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 14415 mHandler.sendMessage(msg); 14416 } 14417 14418 /** 14419 * Get the verification agent timeout. Used for both the APK verifier and the 14420 * intent filter verifier. 14421 * 14422 * @return verification timeout in milliseconds 14423 */ 14424 private long getVerificationTimeout() { 14425 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 14426 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 14427 DEFAULT_VERIFICATION_TIMEOUT); 14428 } 14429 14430 /** 14431 * Get the default verification agent response code. 14432 * 14433 * @return default verification response code 14434 */ 14435 private int getDefaultVerificationResponse(UserHandle user) { 14436 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 14437 return PackageManager.VERIFICATION_REJECT; 14438 } 14439 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14440 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 14441 DEFAULT_VERIFICATION_RESPONSE); 14442 } 14443 14444 /** 14445 * Check whether or not package verification has been enabled. 14446 * 14447 * @return true if verification should be performed 14448 */ 14449 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 14450 if (!DEFAULT_VERIFY_ENABLE) { 14451 return false; 14452 } 14453 14454 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14455 14456 // Check if installing from ADB 14457 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14458 // Do not run verification in a test harness environment 14459 if (ActivityManager.isRunningInTestHarness()) { 14460 return false; 14461 } 14462 if (ensureVerifyAppsEnabled) { 14463 return true; 14464 } 14465 // Check if the developer does not want package verification for ADB installs 14466 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14467 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14468 return false; 14469 } 14470 } else { 14471 // only when not installed from ADB, skip verification for instant apps when 14472 // the installer and verifier are the same. 14473 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14474 if (mInstantAppInstallerActivity != null 14475 && mInstantAppInstallerActivity.packageName.equals( 14476 mRequiredVerifierPackage)) { 14477 try { 14478 mContext.getSystemService(AppOpsManager.class) 14479 .checkPackage(installerUid, mRequiredVerifierPackage); 14480 if (DEBUG_VERIFY) { 14481 Slog.i(TAG, "disable verification for instant app"); 14482 } 14483 return false; 14484 } catch (SecurityException ignore) { } 14485 } 14486 } 14487 } 14488 14489 if (ensureVerifyAppsEnabled) { 14490 return true; 14491 } 14492 14493 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14494 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14495 } 14496 14497 @Override 14498 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14499 throws RemoteException { 14500 mContext.enforceCallingOrSelfPermission( 14501 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14502 "Only intentfilter verification agents can verify applications"); 14503 14504 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14505 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14506 Binder.getCallingUid(), verificationCode, failedDomains); 14507 msg.arg1 = id; 14508 msg.obj = response; 14509 mHandler.sendMessage(msg); 14510 } 14511 14512 @Override 14513 public int getIntentVerificationStatus(String packageName, int userId) { 14514 final int callingUid = Binder.getCallingUid(); 14515 if (UserHandle.getUserId(callingUid) != userId) { 14516 mContext.enforceCallingOrSelfPermission( 14517 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14518 "getIntentVerificationStatus" + userId); 14519 } 14520 if (getInstantAppPackageName(callingUid) != null) { 14521 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14522 } 14523 synchronized (mPackages) { 14524 final PackageSetting ps = mSettings.mPackages.get(packageName); 14525 if (ps == null 14526 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14527 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14528 } 14529 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14530 } 14531 } 14532 14533 @Override 14534 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14535 mContext.enforceCallingOrSelfPermission( 14536 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14537 14538 boolean result = false; 14539 synchronized (mPackages) { 14540 final PackageSetting ps = mSettings.mPackages.get(packageName); 14541 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14542 return false; 14543 } 14544 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14545 } 14546 if (result) { 14547 scheduleWritePackageRestrictionsLocked(userId); 14548 } 14549 return result; 14550 } 14551 14552 @Override 14553 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14554 String packageName) { 14555 final int callingUid = Binder.getCallingUid(); 14556 if (getInstantAppPackageName(callingUid) != null) { 14557 return ParceledListSlice.emptyList(); 14558 } 14559 synchronized (mPackages) { 14560 final PackageSetting ps = mSettings.mPackages.get(packageName); 14561 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14562 return ParceledListSlice.emptyList(); 14563 } 14564 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14565 } 14566 } 14567 14568 @Override 14569 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14570 if (TextUtils.isEmpty(packageName)) { 14571 return ParceledListSlice.emptyList(); 14572 } 14573 final int callingUid = Binder.getCallingUid(); 14574 final int callingUserId = UserHandle.getUserId(callingUid); 14575 synchronized (mPackages) { 14576 PackageParser.Package pkg = mPackages.get(packageName); 14577 if (pkg == null || pkg.activities == null) { 14578 return ParceledListSlice.emptyList(); 14579 } 14580 if (pkg.mExtras == null) { 14581 return ParceledListSlice.emptyList(); 14582 } 14583 final PackageSetting ps = (PackageSetting) pkg.mExtras; 14584 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 14585 return ParceledListSlice.emptyList(); 14586 } 14587 final int count = pkg.activities.size(); 14588 ArrayList<IntentFilter> result = new ArrayList<>(); 14589 for (int n=0; n<count; n++) { 14590 PackageParser.Activity activity = pkg.activities.get(n); 14591 if (activity.intents != null && activity.intents.size() > 0) { 14592 result.addAll(activity.intents); 14593 } 14594 } 14595 return new ParceledListSlice<>(result); 14596 } 14597 } 14598 14599 @Override 14600 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14601 mContext.enforceCallingOrSelfPermission( 14602 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14603 if (UserHandle.getCallingUserId() != userId) { 14604 mContext.enforceCallingOrSelfPermission( 14605 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14606 } 14607 14608 synchronized (mPackages) { 14609 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14610 if (packageName != null) { 14611 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser( 14612 packageName, userId); 14613 } 14614 return result; 14615 } 14616 } 14617 14618 @Override 14619 public String getDefaultBrowserPackageName(int userId) { 14620 if (UserHandle.getCallingUserId() != userId) { 14621 mContext.enforceCallingOrSelfPermission( 14622 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14623 } 14624 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14625 return null; 14626 } 14627 synchronized (mPackages) { 14628 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14629 } 14630 } 14631 14632 /** 14633 * Get the "allow unknown sources" setting. 14634 * 14635 * @return the current "allow unknown sources" setting 14636 */ 14637 private int getUnknownSourcesSettings() { 14638 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14639 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14640 -1); 14641 } 14642 14643 @Override 14644 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14645 final int callingUid = Binder.getCallingUid(); 14646 if (getInstantAppPackageName(callingUid) != null) { 14647 return; 14648 } 14649 // writer 14650 synchronized (mPackages) { 14651 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14652 if (targetPackageSetting == null 14653 || filterAppAccessLPr( 14654 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 14655 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14656 } 14657 14658 PackageSetting installerPackageSetting; 14659 if (installerPackageName != null) { 14660 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14661 if (installerPackageSetting == null) { 14662 throw new IllegalArgumentException("Unknown installer package: " 14663 + installerPackageName); 14664 } 14665 } else { 14666 installerPackageSetting = null; 14667 } 14668 14669 Signature[] callerSignature; 14670 Object obj = mSettings.getUserIdLPr(callingUid); 14671 if (obj != null) { 14672 if (obj instanceof SharedUserSetting) { 14673 callerSignature = 14674 ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 14675 } else if (obj instanceof PackageSetting) { 14676 callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures; 14677 } else { 14678 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 14679 } 14680 } else { 14681 throw new SecurityException("Unknown calling UID: " + callingUid); 14682 } 14683 14684 // Verify: can't set installerPackageName to a package that is 14685 // not signed with the same cert as the caller. 14686 if (installerPackageSetting != null) { 14687 if (compareSignatures(callerSignature, 14688 installerPackageSetting.signatures.mSigningDetails.signatures) 14689 != PackageManager.SIGNATURE_MATCH) { 14690 throw new SecurityException( 14691 "Caller does not have same cert as new installer package " 14692 + installerPackageName); 14693 } 14694 } 14695 14696 // Verify: if target already has an installer package, it must 14697 // be signed with the same cert as the caller. 14698 if (targetPackageSetting.installerPackageName != null) { 14699 PackageSetting setting = mSettings.mPackages.get( 14700 targetPackageSetting.installerPackageName); 14701 // If the currently set package isn't valid, then it's always 14702 // okay to change it. 14703 if (setting != null) { 14704 if (compareSignatures(callerSignature, 14705 setting.signatures.mSigningDetails.signatures) 14706 != PackageManager.SIGNATURE_MATCH) { 14707 throw new SecurityException( 14708 "Caller does not have same cert as old installer package " 14709 + targetPackageSetting.installerPackageName); 14710 } 14711 } 14712 } 14713 14714 // Okay! 14715 targetPackageSetting.installerPackageName = installerPackageName; 14716 if (installerPackageName != null) { 14717 mSettings.mInstallerPackages.add(installerPackageName); 14718 } 14719 scheduleWriteSettingsLocked(); 14720 } 14721 } 14722 14723 @Override 14724 public void setApplicationCategoryHint(String packageName, int categoryHint, 14725 String callerPackageName) { 14726 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14727 throw new SecurityException("Instant applications don't have access to this method"); 14728 } 14729 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14730 callerPackageName); 14731 synchronized (mPackages) { 14732 PackageSetting ps = mSettings.mPackages.get(packageName); 14733 if (ps == null) { 14734 throw new IllegalArgumentException("Unknown target package " + packageName); 14735 } 14736 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14737 throw new IllegalArgumentException("Unknown target package " + packageName); 14738 } 14739 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14740 throw new IllegalArgumentException("Calling package " + callerPackageName 14741 + " is not installer for " + packageName); 14742 } 14743 14744 if (ps.categoryHint != categoryHint) { 14745 ps.categoryHint = categoryHint; 14746 scheduleWriteSettingsLocked(); 14747 } 14748 } 14749 } 14750 14751 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14752 // Queue up an async operation since the package installation may take a little while. 14753 mHandler.post(new Runnable() { 14754 public void run() { 14755 mHandler.removeCallbacks(this); 14756 // Result object to be returned 14757 PackageInstalledInfo res = new PackageInstalledInfo(); 14758 res.setReturnCode(currentStatus); 14759 res.uid = -1; 14760 res.pkg = null; 14761 res.removedInfo = null; 14762 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14763 args.doPreInstall(res.returnCode); 14764 synchronized (mInstallLock) { 14765 installPackageTracedLI(args, res); 14766 } 14767 args.doPostInstall(res.returnCode, res.uid); 14768 } 14769 14770 // A restore should be performed at this point if (a) the install 14771 // succeeded, (b) the operation is not an update, and (c) the new 14772 // package has not opted out of backup participation. 14773 final boolean update = res.removedInfo != null 14774 && res.removedInfo.removedPackage != null; 14775 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14776 boolean doRestore = !update 14777 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14778 14779 // Set up the post-install work request bookkeeping. This will be used 14780 // and cleaned up by the post-install event handling regardless of whether 14781 // there's a restore pass performed. Token values are >= 1. 14782 int token; 14783 if (mNextInstallToken < 0) mNextInstallToken = 1; 14784 token = mNextInstallToken++; 14785 14786 PostInstallData data = new PostInstallData(args, res); 14787 mRunningInstalls.put(token, data); 14788 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14789 14790 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14791 // Pass responsibility to the Backup Manager. It will perform a 14792 // restore if appropriate, then pass responsibility back to the 14793 // Package Manager to run the post-install observer callbacks 14794 // and broadcasts. 14795 IBackupManager bm = IBackupManager.Stub.asInterface( 14796 ServiceManager.getService(Context.BACKUP_SERVICE)); 14797 if (bm != null) { 14798 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14799 + " to BM for possible restore"); 14800 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14801 try { 14802 // TODO: http://b/22388012 14803 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14804 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14805 } else { 14806 doRestore = false; 14807 } 14808 } catch (RemoteException e) { 14809 // can't happen; the backup manager is local 14810 } catch (Exception e) { 14811 Slog.e(TAG, "Exception trying to enqueue restore", e); 14812 doRestore = false; 14813 } 14814 } else { 14815 Slog.e(TAG, "Backup Manager not found!"); 14816 doRestore = false; 14817 } 14818 } 14819 14820 if (!doRestore) { 14821 // No restore possible, or the Backup Manager was mysteriously not 14822 // available -- just fire the post-install work request directly. 14823 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14824 14825 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14826 14827 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14828 mHandler.sendMessage(msg); 14829 } 14830 } 14831 }); 14832 } 14833 14834 /** 14835 * Callback from PackageSettings whenever an app is first transitioned out of the 14836 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14837 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14838 * here whether the app is the target of an ongoing install, and only send the 14839 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14840 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14841 * handling. 14842 */ 14843 void notifyFirstLaunch(final String packageName, final String installerPackage, 14844 final int userId) { 14845 // Serialize this with the rest of the install-process message chain. In the 14846 // restore-at-install case, this Runnable will necessarily run before the 14847 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14848 // are coherent. In the non-restore case, the app has already completed install 14849 // and been launched through some other means, so it is not in a problematic 14850 // state for observers to see the FIRST_LAUNCH signal. 14851 mHandler.post(new Runnable() { 14852 @Override 14853 public void run() { 14854 for (int i = 0; i < mRunningInstalls.size(); i++) { 14855 final PostInstallData data = mRunningInstalls.valueAt(i); 14856 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14857 continue; 14858 } 14859 if (packageName.equals(data.res.pkg.applicationInfo.packageName)) { 14860 // right package; but is it for the right user? 14861 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14862 if (userId == data.res.newUsers[uIndex]) { 14863 if (DEBUG_BACKUP) { 14864 Slog.i(TAG, "Package " + packageName 14865 + " being restored so deferring FIRST_LAUNCH"); 14866 } 14867 return; 14868 } 14869 } 14870 } 14871 } 14872 // didn't find it, so not being restored 14873 if (DEBUG_BACKUP) { 14874 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH"); 14875 } 14876 final boolean isInstantApp = isInstantApp(packageName, userId); 14877 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 14878 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 14879 sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds); 14880 } 14881 }); 14882 } 14883 14884 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, 14885 int[] userIds, int[] instantUserIds) { 14886 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14887 installerPkg, null, userIds, instantUserIds); 14888 } 14889 14890 private abstract class HandlerParams { 14891 private static final int MAX_RETRIES = 4; 14892 14893 /** 14894 * Number of times startCopy() has been attempted and had a non-fatal 14895 * error. 14896 */ 14897 private int mRetries = 0; 14898 14899 /** User handle for the user requesting the information or installation. */ 14900 private final UserHandle mUser; 14901 String traceMethod; 14902 int traceCookie; 14903 14904 HandlerParams(UserHandle user) { 14905 mUser = user; 14906 } 14907 14908 UserHandle getUser() { 14909 return mUser; 14910 } 14911 14912 HandlerParams setTraceMethod(String traceMethod) { 14913 this.traceMethod = traceMethod; 14914 return this; 14915 } 14916 14917 HandlerParams setTraceCookie(int traceCookie) { 14918 this.traceCookie = traceCookie; 14919 return this; 14920 } 14921 14922 final boolean startCopy() { 14923 boolean res; 14924 try { 14925 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14926 14927 if (++mRetries > MAX_RETRIES) { 14928 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14929 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14930 handleServiceError(); 14931 return false; 14932 } else { 14933 handleStartCopy(); 14934 res = true; 14935 } 14936 } catch (RemoteException e) { 14937 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14938 mHandler.sendEmptyMessage(MCS_RECONNECT); 14939 res = false; 14940 } 14941 handleReturnCode(); 14942 return res; 14943 } 14944 14945 final void serviceError() { 14946 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14947 handleServiceError(); 14948 handleReturnCode(); 14949 } 14950 14951 abstract void handleStartCopy() throws RemoteException; 14952 abstract void handleServiceError(); 14953 abstract void handleReturnCode(); 14954 } 14955 14956 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14957 for (File path : paths) { 14958 try { 14959 mcs.clearDirectory(path.getAbsolutePath()); 14960 } catch (RemoteException e) { 14961 } 14962 } 14963 } 14964 14965 static class OriginInfo { 14966 /** 14967 * Location where install is coming from, before it has been 14968 * copied/renamed into place. This could be a single monolithic APK 14969 * file, or a cluster directory. This location may be untrusted. 14970 */ 14971 final File file; 14972 14973 /** 14974 * Flag indicating that {@link #file} or {@link #cid} has already been 14975 * staged, meaning downstream users don't need to defensively copy the 14976 * contents. 14977 */ 14978 final boolean staged; 14979 14980 /** 14981 * Flag indicating that {@link #file} or {@link #cid} is an already 14982 * installed app that is being moved. 14983 */ 14984 final boolean existing; 14985 14986 final String resolvedPath; 14987 final File resolvedFile; 14988 14989 static OriginInfo fromNothing() { 14990 return new OriginInfo(null, false, false); 14991 } 14992 14993 static OriginInfo fromUntrustedFile(File file) { 14994 return new OriginInfo(file, false, false); 14995 } 14996 14997 static OriginInfo fromExistingFile(File file) { 14998 return new OriginInfo(file, false, true); 14999 } 15000 15001 static OriginInfo fromStagedFile(File file) { 15002 return new OriginInfo(file, true, false); 15003 } 15004 15005 private OriginInfo(File file, boolean staged, boolean existing) { 15006 this.file = file; 15007 this.staged = staged; 15008 this.existing = existing; 15009 15010 if (file != null) { 15011 resolvedPath = file.getAbsolutePath(); 15012 resolvedFile = file; 15013 } else { 15014 resolvedPath = null; 15015 resolvedFile = null; 15016 } 15017 } 15018 } 15019 15020 static class MoveInfo { 15021 final int moveId; 15022 final String fromUuid; 15023 final String toUuid; 15024 final String packageName; 15025 final String dataAppName; 15026 final int appId; 15027 final String seinfo; 15028 final int targetSdkVersion; 15029 15030 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 15031 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 15032 this.moveId = moveId; 15033 this.fromUuid = fromUuid; 15034 this.toUuid = toUuid; 15035 this.packageName = packageName; 15036 this.dataAppName = dataAppName; 15037 this.appId = appId; 15038 this.seinfo = seinfo; 15039 this.targetSdkVersion = targetSdkVersion; 15040 } 15041 } 15042 15043 static class VerificationInfo { 15044 /** A constant used to indicate that a uid value is not present. */ 15045 public static final int NO_UID = -1; 15046 15047 /** URI referencing where the package was downloaded from. */ 15048 final Uri originatingUri; 15049 15050 /** HTTP referrer URI associated with the originatingURI. */ 15051 final Uri referrer; 15052 15053 /** UID of the application that the install request originated from. */ 15054 final int originatingUid; 15055 15056 /** UID of application requesting the install */ 15057 final int installerUid; 15058 15059 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 15060 this.originatingUri = originatingUri; 15061 this.referrer = referrer; 15062 this.originatingUid = originatingUid; 15063 this.installerUid = installerUid; 15064 } 15065 } 15066 15067 class InstallParams extends HandlerParams { 15068 final OriginInfo origin; 15069 final MoveInfo move; 15070 final IPackageInstallObserver2 observer; 15071 int installFlags; 15072 final String installerPackageName; 15073 final String volumeUuid; 15074 private InstallArgs mArgs; 15075 private int mRet; 15076 final String packageAbiOverride; 15077 final String[] grantedRuntimePermissions; 15078 final VerificationInfo verificationInfo; 15079 final PackageParser.SigningDetails signingDetails; 15080 final int installReason; 15081 15082 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15083 int installFlags, String installerPackageName, String volumeUuid, 15084 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 15085 String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) { 15086 super(user); 15087 this.origin = origin; 15088 this.move = move; 15089 this.observer = observer; 15090 this.installFlags = installFlags; 15091 this.installerPackageName = installerPackageName; 15092 this.volumeUuid = volumeUuid; 15093 this.verificationInfo = verificationInfo; 15094 this.packageAbiOverride = packageAbiOverride; 15095 this.grantedRuntimePermissions = grantedPermissions; 15096 this.signingDetails = signingDetails; 15097 this.installReason = installReason; 15098 } 15099 15100 @Override 15101 public String toString() { 15102 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 15103 + " file=" + origin.file + "}"; 15104 } 15105 15106 private int installLocationPolicy(PackageInfoLite pkgLite) { 15107 String packageName = pkgLite.packageName; 15108 int installLocation = pkgLite.installLocation; 15109 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15110 // reader 15111 synchronized (mPackages) { 15112 // Currently installed package which the new package is attempting to replace or 15113 // null if no such package is installed. 15114 PackageParser.Package installedPkg = mPackages.get(packageName); 15115 // Package which currently owns the data which the new package will own if installed. 15116 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 15117 // will be null whereas dataOwnerPkg will contain information about the package 15118 // which was uninstalled while keeping its data. 15119 PackageParser.Package dataOwnerPkg = installedPkg; 15120 if (dataOwnerPkg == null) { 15121 PackageSetting ps = mSettings.mPackages.get(packageName); 15122 if (ps != null) { 15123 dataOwnerPkg = ps.pkg; 15124 } 15125 } 15126 15127 if (dataOwnerPkg != null) { 15128 // If installed, the package will get access to data left on the device by its 15129 // predecessor. As a security measure, this is permited only if this is not a 15130 // version downgrade or if the predecessor package is marked as debuggable and 15131 // a downgrade is explicitly requested. 15132 // 15133 // On debuggable platform builds, downgrades are permitted even for 15134 // non-debuggable packages to make testing easier. Debuggable platform builds do 15135 // not offer security guarantees and thus it's OK to disable some security 15136 // mechanisms to make debugging/testing easier on those builds. However, even on 15137 // debuggable builds downgrades of packages are permitted only if requested via 15138 // installFlags. This is because we aim to keep the behavior of debuggable 15139 // platform builds as close as possible to the behavior of non-debuggable 15140 // platform builds. 15141 final boolean downgradeRequested = 15142 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 15143 final boolean packageDebuggable = 15144 (dataOwnerPkg.applicationInfo.flags 15145 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 15146 final boolean downgradePermitted = 15147 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 15148 if (!downgradePermitted) { 15149 try { 15150 checkDowngrade(dataOwnerPkg, pkgLite); 15151 } catch (PackageManagerException e) { 15152 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 15153 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 15154 } 15155 } 15156 } 15157 15158 if (installedPkg != null) { 15159 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15160 // Check for updated system application. 15161 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15162 if (onSd) { 15163 Slog.w(TAG, "Cannot install update to system app on sdcard"); 15164 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 15165 } 15166 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15167 } else { 15168 if (onSd) { 15169 // Install flag overrides everything. 15170 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15171 } 15172 // If current upgrade specifies particular preference 15173 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 15174 // Application explicitly specified internal. 15175 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15176 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 15177 // App explictly prefers external. Let policy decide 15178 } else { 15179 // Prefer previous location 15180 if (isExternal(installedPkg)) { 15181 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15182 } 15183 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15184 } 15185 } 15186 } else { 15187 // Invalid install. Return error code 15188 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 15189 } 15190 } 15191 } 15192 // All the special cases have been taken care of. 15193 // Return result based on recommended install location. 15194 if (onSd) { 15195 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15196 } 15197 return pkgLite.recommendedInstallLocation; 15198 } 15199 15200 /* 15201 * Invoke remote method to get package information and install 15202 * location values. Override install location based on default 15203 * policy if needed and then create install arguments based 15204 * on the install location. 15205 */ 15206 public void handleStartCopy() throws RemoteException { 15207 int ret = PackageManager.INSTALL_SUCCEEDED; 15208 15209 // If we're already staged, we've firmly committed to an install location 15210 if (origin.staged) { 15211 if (origin.file != null) { 15212 installFlags |= PackageManager.INSTALL_INTERNAL; 15213 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15214 } else { 15215 throw new IllegalStateException("Invalid stage location"); 15216 } 15217 } 15218 15219 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15220 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 15221 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15222 PackageInfoLite pkgLite = null; 15223 15224 if (onInt && onSd) { 15225 // Check if both bits are set. 15226 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 15227 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15228 } else if (onSd && ephemeral) { 15229 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 15230 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15231 } else { 15232 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 15233 packageAbiOverride); 15234 15235 if (DEBUG_INSTANT && ephemeral) { 15236 Slog.v(TAG, "pkgLite for install: " + pkgLite); 15237 } 15238 15239 /* 15240 * If we have too little free space, try to free cache 15241 * before giving up. 15242 */ 15243 if (!origin.staged && pkgLite.recommendedInstallLocation 15244 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15245 // TODO: focus freeing disk space on the target device 15246 final StorageManager storage = StorageManager.from(mContext); 15247 final long lowThreshold = storage.getStorageLowBytes( 15248 Environment.getDataDirectory()); 15249 15250 final long sizeBytes = mContainerService.calculateInstalledSize( 15251 origin.resolvedPath, packageAbiOverride); 15252 15253 try { 15254 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 15255 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 15256 installFlags, packageAbiOverride); 15257 } catch (InstallerException e) { 15258 Slog.w(TAG, "Failed to free cache", e); 15259 } 15260 15261 /* 15262 * The cache free must have deleted the file we 15263 * downloaded to install. 15264 * 15265 * TODO: fix the "freeCache" call to not delete 15266 * the file we care about. 15267 */ 15268 if (pkgLite.recommendedInstallLocation 15269 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15270 pkgLite.recommendedInstallLocation 15271 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 15272 } 15273 } 15274 } 15275 15276 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15277 int loc = pkgLite.recommendedInstallLocation; 15278 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 15279 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15280 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 15281 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 15282 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15283 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15284 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 15285 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 15286 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15287 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 15288 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 15289 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 15290 } else { 15291 // Override with defaults if needed. 15292 loc = installLocationPolicy(pkgLite); 15293 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 15294 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 15295 } else if (!onSd && !onInt) { 15296 // Override install location with flags 15297 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 15298 // Set the flag to install on external media. 15299 installFlags |= PackageManager.INSTALL_EXTERNAL; 15300 installFlags &= ~PackageManager.INSTALL_INTERNAL; 15301 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 15302 if (DEBUG_INSTANT) { 15303 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 15304 } 15305 installFlags |= PackageManager.INSTALL_INSTANT_APP; 15306 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 15307 |PackageManager.INSTALL_INTERNAL); 15308 } else { 15309 // Make sure the flag for installing on external 15310 // media is unset 15311 installFlags |= PackageManager.INSTALL_INTERNAL; 15312 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15313 } 15314 } 15315 } 15316 } 15317 15318 final InstallArgs args = createInstallArgs(this); 15319 mArgs = args; 15320 15321 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15322 // TODO: http://b/22976637 15323 // Apps installed for "all" users use the device owner to verify the app 15324 UserHandle verifierUser = getUser(); 15325 if (verifierUser == UserHandle.ALL) { 15326 verifierUser = UserHandle.SYSTEM; 15327 } 15328 15329 /* 15330 * Determine if we have any installed package verifiers. If we 15331 * do, then we'll defer to them to verify the packages. 15332 */ 15333 final int requiredUid = mRequiredVerifierPackage == null ? -1 15334 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15335 verifierUser.getIdentifier()); 15336 final int installerUid = 15337 verificationInfo == null ? -1 : verificationInfo.installerUid; 15338 if (!origin.existing && requiredUid != -1 15339 && isVerificationEnabled( 15340 verifierUser.getIdentifier(), installFlags, installerUid)) { 15341 final Intent verification = new Intent( 15342 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 15343 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 15344 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 15345 PACKAGE_MIME_TYPE); 15346 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15347 15348 // Query all live verifiers based on current user state 15349 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 15350 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 15351 false /*allowDynamicSplits*/); 15352 15353 if (DEBUG_VERIFY) { 15354 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 15355 + verification.toString() + " with " + pkgLite.verifiers.length 15356 + " optional verifiers"); 15357 } 15358 15359 final int verificationId = mPendingVerificationToken++; 15360 15361 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 15362 15363 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 15364 installerPackageName); 15365 15366 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 15367 installFlags); 15368 15369 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 15370 pkgLite.packageName); 15371 15372 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 15373 pkgLite.versionCode); 15374 15375 verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE, 15376 pkgLite.getLongVersionCode()); 15377 15378 if (verificationInfo != null) { 15379 if (verificationInfo.originatingUri != null) { 15380 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 15381 verificationInfo.originatingUri); 15382 } 15383 if (verificationInfo.referrer != null) { 15384 verification.putExtra(Intent.EXTRA_REFERRER, 15385 verificationInfo.referrer); 15386 } 15387 if (verificationInfo.originatingUid >= 0) { 15388 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 15389 verificationInfo.originatingUid); 15390 } 15391 if (verificationInfo.installerUid >= 0) { 15392 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 15393 verificationInfo.installerUid); 15394 } 15395 } 15396 15397 final PackageVerificationState verificationState = new PackageVerificationState( 15398 requiredUid, args); 15399 15400 mPendingVerification.append(verificationId, verificationState); 15401 15402 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 15403 receivers, verificationState); 15404 15405 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 15406 final long idleDuration = getVerificationTimeout(); 15407 15408 /* 15409 * If any sufficient verifiers were listed in the package 15410 * manifest, attempt to ask them. 15411 */ 15412 if (sufficientVerifiers != null) { 15413 final int N = sufficientVerifiers.size(); 15414 if (N == 0) { 15415 Slog.i(TAG, "Additional verifiers required, but none installed."); 15416 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 15417 } else { 15418 for (int i = 0; i < N; i++) { 15419 final ComponentName verifierComponent = sufficientVerifiers.get(i); 15420 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15421 verifierComponent.getPackageName(), idleDuration, 15422 verifierUser.getIdentifier(), false, "package verifier"); 15423 15424 final Intent sufficientIntent = new Intent(verification); 15425 sufficientIntent.setComponent(verifierComponent); 15426 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 15427 } 15428 } 15429 } 15430 15431 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 15432 mRequiredVerifierPackage, receivers); 15433 if (ret == PackageManager.INSTALL_SUCCEEDED 15434 && mRequiredVerifierPackage != null) { 15435 Trace.asyncTraceBegin( 15436 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 15437 /* 15438 * Send the intent to the required verification agent, 15439 * but only start the verification timeout after the 15440 * target BroadcastReceivers have run. 15441 */ 15442 verification.setComponent(requiredVerifierComponent); 15443 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15444 mRequiredVerifierPackage, idleDuration, 15445 verifierUser.getIdentifier(), false, "package verifier"); 15446 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 15447 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15448 new BroadcastReceiver() { 15449 @Override 15450 public void onReceive(Context context, Intent intent) { 15451 final Message msg = mHandler 15452 .obtainMessage(CHECK_PENDING_VERIFICATION); 15453 msg.arg1 = verificationId; 15454 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15455 } 15456 }, null, 0, null, null); 15457 15458 /* 15459 * We don't want the copy to proceed until verification 15460 * succeeds, so null out this field. 15461 */ 15462 mArgs = null; 15463 } 15464 } else { 15465 /* 15466 * No package verification is enabled, so immediately start 15467 * the remote call to initiate copy using temporary file. 15468 */ 15469 ret = args.copyApk(mContainerService, true); 15470 } 15471 } 15472 15473 mRet = ret; 15474 } 15475 15476 @Override 15477 void handleReturnCode() { 15478 // If mArgs is null, then MCS couldn't be reached. When it 15479 // reconnects, it will try again to install. At that point, this 15480 // will succeed. 15481 if (mArgs != null) { 15482 processPendingInstall(mArgs, mRet); 15483 } 15484 } 15485 15486 @Override 15487 void handleServiceError() { 15488 mArgs = createInstallArgs(this); 15489 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15490 } 15491 } 15492 15493 private InstallArgs createInstallArgs(InstallParams params) { 15494 if (params.move != null) { 15495 return new MoveInstallArgs(params); 15496 } else { 15497 return new FileInstallArgs(params); 15498 } 15499 } 15500 15501 /** 15502 * Create args that describe an existing installed package. Typically used 15503 * when cleaning up old installs, or used as a move source. 15504 */ 15505 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 15506 String resourcePath, String[] instructionSets) { 15507 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15508 } 15509 15510 static abstract class InstallArgs { 15511 /** @see InstallParams#origin */ 15512 final OriginInfo origin; 15513 /** @see InstallParams#move */ 15514 final MoveInfo move; 15515 15516 final IPackageInstallObserver2 observer; 15517 // Always refers to PackageManager flags only 15518 final int installFlags; 15519 final String installerPackageName; 15520 final String volumeUuid; 15521 final UserHandle user; 15522 final String abiOverride; 15523 final String[] installGrantPermissions; 15524 /** If non-null, drop an async trace when the install completes */ 15525 final String traceMethod; 15526 final int traceCookie; 15527 final PackageParser.SigningDetails signingDetails; 15528 final int installReason; 15529 15530 // The list of instruction sets supported by this app. This is currently 15531 // only used during the rmdex() phase to clean up resources. We can get rid of this 15532 // if we move dex files under the common app path. 15533 /* nullable */ String[] instructionSets; 15534 15535 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15536 int installFlags, String installerPackageName, String volumeUuid, 15537 UserHandle user, String[] instructionSets, 15538 String abiOverride, String[] installGrantPermissions, 15539 String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails, 15540 int installReason) { 15541 this.origin = origin; 15542 this.move = move; 15543 this.installFlags = installFlags; 15544 this.observer = observer; 15545 this.installerPackageName = installerPackageName; 15546 this.volumeUuid = volumeUuid; 15547 this.user = user; 15548 this.instructionSets = instructionSets; 15549 this.abiOverride = abiOverride; 15550 this.installGrantPermissions = installGrantPermissions; 15551 this.traceMethod = traceMethod; 15552 this.traceCookie = traceCookie; 15553 this.signingDetails = signingDetails; 15554 this.installReason = installReason; 15555 } 15556 15557 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15558 abstract int doPreInstall(int status); 15559 15560 /** 15561 * Rename package into final resting place. All paths on the given 15562 * scanned package should be updated to reflect the rename. 15563 */ 15564 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15565 abstract int doPostInstall(int status, int uid); 15566 15567 /** @see PackageSettingBase#codePathString */ 15568 abstract String getCodePath(); 15569 /** @see PackageSettingBase#resourcePathString */ 15570 abstract String getResourcePath(); 15571 15572 // Need installer lock especially for dex file removal. 15573 abstract void cleanUpResourcesLI(); 15574 abstract boolean doPostDeleteLI(boolean delete); 15575 15576 /** 15577 * Called before the source arguments are copied. This is used mostly 15578 * for MoveParams when it needs to read the source file to put it in the 15579 * destination. 15580 */ 15581 int doPreCopy() { 15582 return PackageManager.INSTALL_SUCCEEDED; 15583 } 15584 15585 /** 15586 * Called after the source arguments are copied. This is used mostly for 15587 * MoveParams when it needs to read the source file to put it in the 15588 * destination. 15589 */ 15590 int doPostCopy(int uid) { 15591 return PackageManager.INSTALL_SUCCEEDED; 15592 } 15593 15594 protected boolean isFwdLocked() { 15595 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15596 } 15597 15598 protected boolean isExternalAsec() { 15599 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15600 } 15601 15602 protected boolean isEphemeral() { 15603 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15604 } 15605 15606 UserHandle getUser() { 15607 return user; 15608 } 15609 } 15610 15611 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15612 if (!allCodePaths.isEmpty()) { 15613 if (instructionSets == null) { 15614 throw new IllegalStateException("instructionSet == null"); 15615 } 15616 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15617 for (String codePath : allCodePaths) { 15618 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15619 try { 15620 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15621 } catch (InstallerException ignored) { 15622 } 15623 } 15624 } 15625 } 15626 } 15627 15628 /** 15629 * Logic to handle installation of non-ASEC applications, including copying 15630 * and renaming logic. 15631 */ 15632 class FileInstallArgs extends InstallArgs { 15633 private File codeFile; 15634 private File resourceFile; 15635 15636 // Example topology: 15637 // /data/app/com.example/base.apk 15638 // /data/app/com.example/split_foo.apk 15639 // /data/app/com.example/lib/arm/libfoo.so 15640 // /data/app/com.example/lib/arm64/libfoo.so 15641 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15642 15643 /** New install */ 15644 FileInstallArgs(InstallParams params) { 15645 super(params.origin, params.move, params.observer, params.installFlags, 15646 params.installerPackageName, params.volumeUuid, 15647 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15648 params.grantedRuntimePermissions, 15649 params.traceMethod, params.traceCookie, params.signingDetails, 15650 params.installReason); 15651 if (isFwdLocked()) { 15652 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15653 } 15654 } 15655 15656 /** Existing install */ 15657 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15658 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15659 null, null, null, 0, PackageParser.SigningDetails.UNKNOWN, 15660 PackageManager.INSTALL_REASON_UNKNOWN); 15661 this.codeFile = (codePath != null) ? new File(codePath) : null; 15662 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15663 } 15664 15665 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15666 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15667 try { 15668 return doCopyApk(imcs, temp); 15669 } finally { 15670 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15671 } 15672 } 15673 15674 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15675 if (origin.staged) { 15676 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15677 codeFile = origin.file; 15678 resourceFile = origin.file; 15679 return PackageManager.INSTALL_SUCCEEDED; 15680 } 15681 15682 try { 15683 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15684 final File tempDir = 15685 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15686 codeFile = tempDir; 15687 resourceFile = tempDir; 15688 } catch (IOException e) { 15689 Slog.w(TAG, "Failed to create copy file: " + e); 15690 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15691 } 15692 15693 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15694 @Override 15695 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15696 if (!FileUtils.isValidExtFilename(name)) { 15697 throw new IllegalArgumentException("Invalid filename: " + name); 15698 } 15699 try { 15700 final File file = new File(codeFile, name); 15701 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15702 O_RDWR | O_CREAT, 0644); 15703 Os.chmod(file.getAbsolutePath(), 0644); 15704 return new ParcelFileDescriptor(fd); 15705 } catch (ErrnoException e) { 15706 throw new RemoteException("Failed to open: " + e.getMessage()); 15707 } 15708 } 15709 }; 15710 15711 int ret = PackageManager.INSTALL_SUCCEEDED; 15712 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15713 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15714 Slog.e(TAG, "Failed to copy package"); 15715 return ret; 15716 } 15717 15718 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15719 NativeLibraryHelper.Handle handle = null; 15720 try { 15721 handle = NativeLibraryHelper.Handle.create(codeFile); 15722 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15723 abiOverride); 15724 } catch (IOException e) { 15725 Slog.e(TAG, "Copying native libraries failed", e); 15726 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15727 } finally { 15728 IoUtils.closeQuietly(handle); 15729 } 15730 15731 return ret; 15732 } 15733 15734 int doPreInstall(int status) { 15735 if (status != PackageManager.INSTALL_SUCCEEDED) { 15736 cleanUp(); 15737 } 15738 return status; 15739 } 15740 15741 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15742 if (status != PackageManager.INSTALL_SUCCEEDED) { 15743 cleanUp(); 15744 return false; 15745 } 15746 15747 final File targetDir = codeFile.getParentFile(); 15748 final File beforeCodeFile = codeFile; 15749 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15750 15751 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15752 try { 15753 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15754 } catch (ErrnoException e) { 15755 Slog.w(TAG, "Failed to rename", e); 15756 return false; 15757 } 15758 15759 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15760 Slog.w(TAG, "Failed to restorecon"); 15761 return false; 15762 } 15763 15764 // Reflect the rename internally 15765 codeFile = afterCodeFile; 15766 resourceFile = afterCodeFile; 15767 15768 // Reflect the rename in scanned details 15769 try { 15770 pkg.setCodePath(afterCodeFile.getCanonicalPath()); 15771 } catch (IOException e) { 15772 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e); 15773 return false; 15774 } 15775 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15776 afterCodeFile, pkg.baseCodePath)); 15777 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15778 afterCodeFile, pkg.splitCodePaths)); 15779 15780 // Reflect the rename in app info 15781 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15782 pkg.setApplicationInfoCodePath(pkg.codePath); 15783 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15784 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15785 pkg.setApplicationInfoResourcePath(pkg.codePath); 15786 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15787 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15788 15789 return true; 15790 } 15791 15792 int doPostInstall(int status, int uid) { 15793 if (status != PackageManager.INSTALL_SUCCEEDED) { 15794 cleanUp(); 15795 } 15796 return status; 15797 } 15798 15799 @Override 15800 String getCodePath() { 15801 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15802 } 15803 15804 @Override 15805 String getResourcePath() { 15806 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15807 } 15808 15809 private boolean cleanUp() { 15810 if (codeFile == null || !codeFile.exists()) { 15811 return false; 15812 } 15813 15814 removeCodePathLI(codeFile); 15815 15816 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15817 resourceFile.delete(); 15818 } 15819 15820 return true; 15821 } 15822 15823 void cleanUpResourcesLI() { 15824 // Try enumerating all code paths before deleting 15825 List<String> allCodePaths = Collections.EMPTY_LIST; 15826 if (codeFile != null && codeFile.exists()) { 15827 try { 15828 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15829 allCodePaths = pkg.getAllCodePaths(); 15830 } catch (PackageParserException e) { 15831 // Ignored; we tried our best 15832 } 15833 } 15834 15835 cleanUp(); 15836 removeDexFiles(allCodePaths, instructionSets); 15837 } 15838 15839 boolean doPostDeleteLI(boolean delete) { 15840 // XXX err, shouldn't we respect the delete flag? 15841 cleanUpResourcesLI(); 15842 return true; 15843 } 15844 } 15845 15846 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15847 PackageManagerException { 15848 if (copyRet < 0) { 15849 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15850 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15851 throw new PackageManagerException(copyRet, message); 15852 } 15853 } 15854 } 15855 15856 /** 15857 * Extract the StorageManagerService "container ID" from the full code path of an 15858 * .apk. 15859 */ 15860 static String cidFromCodePath(String fullCodePath) { 15861 int eidx = fullCodePath.lastIndexOf("/"); 15862 String subStr1 = fullCodePath.substring(0, eidx); 15863 int sidx = subStr1.lastIndexOf("/"); 15864 return subStr1.substring(sidx+1, eidx); 15865 } 15866 15867 /** 15868 * Logic to handle movement of existing installed applications. 15869 */ 15870 class MoveInstallArgs extends InstallArgs { 15871 private File codeFile; 15872 private File resourceFile; 15873 15874 /** New install */ 15875 MoveInstallArgs(InstallParams params) { 15876 super(params.origin, params.move, params.observer, params.installFlags, 15877 params.installerPackageName, params.volumeUuid, 15878 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15879 params.grantedRuntimePermissions, 15880 params.traceMethod, params.traceCookie, params.signingDetails, 15881 params.installReason); 15882 } 15883 15884 int copyApk(IMediaContainerService imcs, boolean temp) { 15885 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15886 + move.fromUuid + " to " + move.toUuid); 15887 synchronized (mInstaller) { 15888 try { 15889 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15890 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15891 } catch (InstallerException e) { 15892 Slog.w(TAG, "Failed to move app", e); 15893 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15894 } 15895 } 15896 15897 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15898 resourceFile = codeFile; 15899 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15900 15901 return PackageManager.INSTALL_SUCCEEDED; 15902 } 15903 15904 int doPreInstall(int status) { 15905 if (status != PackageManager.INSTALL_SUCCEEDED) { 15906 cleanUp(move.toUuid); 15907 } 15908 return status; 15909 } 15910 15911 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15912 if (status != PackageManager.INSTALL_SUCCEEDED) { 15913 cleanUp(move.toUuid); 15914 return false; 15915 } 15916 15917 // Reflect the move in app info 15918 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15919 pkg.setApplicationInfoCodePath(pkg.codePath); 15920 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15921 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15922 pkg.setApplicationInfoResourcePath(pkg.codePath); 15923 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15924 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15925 15926 return true; 15927 } 15928 15929 int doPostInstall(int status, int uid) { 15930 if (status == PackageManager.INSTALL_SUCCEEDED) { 15931 cleanUp(move.fromUuid); 15932 } else { 15933 cleanUp(move.toUuid); 15934 } 15935 return status; 15936 } 15937 15938 @Override 15939 String getCodePath() { 15940 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15941 } 15942 15943 @Override 15944 String getResourcePath() { 15945 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15946 } 15947 15948 private boolean cleanUp(String volumeUuid) { 15949 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15950 move.dataAppName); 15951 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15952 final int[] userIds = sUserManager.getUserIds(); 15953 synchronized (mInstallLock) { 15954 // Clean up both app data and code 15955 // All package moves are frozen until finished 15956 for (int userId : userIds) { 15957 try { 15958 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15959 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15960 } catch (InstallerException e) { 15961 Slog.w(TAG, String.valueOf(e)); 15962 } 15963 } 15964 removeCodePathLI(codeFile); 15965 } 15966 return true; 15967 } 15968 15969 void cleanUpResourcesLI() { 15970 throw new UnsupportedOperationException(); 15971 } 15972 15973 boolean doPostDeleteLI(boolean delete) { 15974 throw new UnsupportedOperationException(); 15975 } 15976 } 15977 15978 static String getAsecPackageName(String packageCid) { 15979 int idx = packageCid.lastIndexOf("-"); 15980 if (idx == -1) { 15981 return packageCid; 15982 } 15983 return packageCid.substring(0, idx); 15984 } 15985 15986 // Utility method used to create code paths based on package name and available index. 15987 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15988 String idxStr = ""; 15989 int idx = 1; 15990 // Fall back to default value of idx=1 if prefix is not 15991 // part of oldCodePath 15992 if (oldCodePath != null) { 15993 String subStr = oldCodePath; 15994 // Drop the suffix right away 15995 if (suffix != null && subStr.endsWith(suffix)) { 15996 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15997 } 15998 // If oldCodePath already contains prefix find out the 15999 // ending index to either increment or decrement. 16000 int sidx = subStr.lastIndexOf(prefix); 16001 if (sidx != -1) { 16002 subStr = subStr.substring(sidx + prefix.length()); 16003 if (subStr != null) { 16004 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 16005 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 16006 } 16007 try { 16008 idx = Integer.parseInt(subStr); 16009 if (idx <= 1) { 16010 idx++; 16011 } else { 16012 idx--; 16013 } 16014 } catch(NumberFormatException e) { 16015 } 16016 } 16017 } 16018 } 16019 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 16020 return prefix + idxStr; 16021 } 16022 16023 private File getNextCodePath(File targetDir, String packageName) { 16024 File result; 16025 SecureRandom random = new SecureRandom(); 16026 byte[] bytes = new byte[16]; 16027 do { 16028 random.nextBytes(bytes); 16029 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 16030 result = new File(targetDir, packageName + "-" + suffix); 16031 } while (result.exists()); 16032 return result; 16033 } 16034 16035 // Utility method that returns the relative package path with respect 16036 // to the installation directory. Like say for /data/data/com.test-1.apk 16037 // string com.test-1 is returned. 16038 static String deriveCodePathName(String codePath) { 16039 if (codePath == null) { 16040 return null; 16041 } 16042 final File codeFile = new File(codePath); 16043 final String name = codeFile.getName(); 16044 if (codeFile.isDirectory()) { 16045 return name; 16046 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 16047 final int lastDot = name.lastIndexOf('.'); 16048 return name.substring(0, lastDot); 16049 } else { 16050 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 16051 return null; 16052 } 16053 } 16054 16055 static class PackageInstalledInfo { 16056 String name; 16057 int uid; 16058 // The set of users that originally had this package installed. 16059 int[] origUsers; 16060 // The set of users that now have this package installed. 16061 int[] newUsers; 16062 PackageParser.Package pkg; 16063 int returnCode; 16064 String returnMsg; 16065 String installerPackageName; 16066 PackageRemovedInfo removedInfo; 16067 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 16068 16069 public void setError(int code, String msg) { 16070 setReturnCode(code); 16071 setReturnMessage(msg); 16072 Slog.w(TAG, msg); 16073 } 16074 16075 public void setError(String msg, PackageParserException e) { 16076 setReturnCode(e.error); 16077 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 16078 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16079 for (int i = 0; i < childCount; i++) { 16080 addedChildPackages.valueAt(i).setError(msg, e); 16081 } 16082 Slog.w(TAG, msg, e); 16083 } 16084 16085 public void setError(String msg, PackageManagerException e) { 16086 returnCode = e.error; 16087 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 16088 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16089 for (int i = 0; i < childCount; i++) { 16090 addedChildPackages.valueAt(i).setError(msg, e); 16091 } 16092 Slog.w(TAG, msg, e); 16093 } 16094 16095 public void setReturnCode(int returnCode) { 16096 this.returnCode = returnCode; 16097 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16098 for (int i = 0; i < childCount; i++) { 16099 addedChildPackages.valueAt(i).returnCode = returnCode; 16100 } 16101 } 16102 16103 private void setReturnMessage(String returnMsg) { 16104 this.returnMsg = returnMsg; 16105 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16106 for (int i = 0; i < childCount; i++) { 16107 addedChildPackages.valueAt(i).returnMsg = returnMsg; 16108 } 16109 } 16110 16111 // In some error cases we want to convey more info back to the observer 16112 String origPackage; 16113 String origPermission; 16114 } 16115 16116 /* 16117 * Install a non-existing package. 16118 */ 16119 private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 16120 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 16121 String volumeUuid, PackageInstalledInfo res, int installReason) { 16122 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 16123 16124 // Remember this for later, in case we need to rollback this install 16125 String pkgName = pkg.packageName; 16126 16127 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 16128 16129 synchronized(mPackages) { 16130 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 16131 if (renamedPackage != null) { 16132 // A package with the same name is already installed, though 16133 // it has been renamed to an older name. The package we 16134 // are trying to install should be installed as an update to 16135 // the existing one, but that has not been requested, so bail. 16136 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16137 + " without first uninstalling package running as " 16138 + renamedPackage); 16139 return; 16140 } 16141 if (mPackages.containsKey(pkgName)) { 16142 // Don't allow installation over an existing package with the same name. 16143 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16144 + " without first uninstalling."); 16145 return; 16146 } 16147 } 16148 16149 try { 16150 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 16151 System.currentTimeMillis(), user); 16152 16153 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 16154 16155 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16156 prepareAppDataAfterInstallLIF(newPackage); 16157 16158 } else { 16159 // Remove package from internal structures, but keep around any 16160 // data that might have already existed 16161 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 16162 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 16163 } 16164 } catch (PackageManagerException e) { 16165 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16166 } 16167 16168 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16169 } 16170 16171 private static void updateDigest(MessageDigest digest, File file) throws IOException { 16172 try (DigestInputStream digestStream = 16173 new DigestInputStream(new FileInputStream(file), digest)) { 16174 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 16175 } 16176 } 16177 16178 private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 16179 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 16180 PackageInstalledInfo res, int installReason) { 16181 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16182 16183 final PackageParser.Package oldPackage; 16184 final PackageSetting ps; 16185 final String pkgName = pkg.packageName; 16186 final int[] allUsers; 16187 final int[] installedUsers; 16188 16189 synchronized(mPackages) { 16190 oldPackage = mPackages.get(pkgName); 16191 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 16192 16193 // don't allow upgrade to target a release SDK from a pre-release SDK 16194 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 16195 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16196 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 16197 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16198 if (oldTargetsPreRelease 16199 && !newTargetsPreRelease 16200 && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 16201 Slog.w(TAG, "Can't install package targeting released sdk"); 16202 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 16203 return; 16204 } 16205 16206 ps = mSettings.mPackages.get(pkgName); 16207 16208 // verify signatures are valid 16209 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16210 if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) { 16211 if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) { 16212 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16213 "New package not signed by keys specified by upgrade-keysets: " 16214 + pkgName); 16215 return; 16216 } 16217 } else { 16218 16219 // default to original signature matching 16220 if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails, 16221 PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA) 16222 && !oldPackage.mSigningDetails.checkCapability( 16223 pkg.mSigningDetails, 16224 PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) { 16225 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16226 "New package has a different signature: " + pkgName); 16227 return; 16228 } 16229 } 16230 16231 // don't allow a system upgrade unless the upgrade hash matches 16232 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) { 16233 byte[] digestBytes = null; 16234 try { 16235 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 16236 updateDigest(digest, new File(pkg.baseCodePath)); 16237 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 16238 for (String path : pkg.splitCodePaths) { 16239 updateDigest(digest, new File(path)); 16240 } 16241 } 16242 digestBytes = digest.digest(); 16243 } catch (NoSuchAlgorithmException | IOException e) { 16244 res.setError(INSTALL_FAILED_INVALID_APK, 16245 "Could not compute hash: " + pkgName); 16246 return; 16247 } 16248 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 16249 res.setError(INSTALL_FAILED_INVALID_APK, 16250 "New package fails restrict-update check: " + pkgName); 16251 return; 16252 } 16253 // retain upgrade restriction 16254 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 16255 } 16256 16257 // Check for shared user id changes 16258 String invalidPackageName = 16259 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 16260 if (invalidPackageName != null) { 16261 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 16262 "Package " + invalidPackageName + " tried to change user " 16263 + oldPackage.mSharedUserId); 16264 return; 16265 } 16266 16267 // check if the new package supports all of the abis which the old package supports 16268 boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null; 16269 boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null; 16270 if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) { 16271 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16272 "Update to package " + pkgName + " doesn't support multi arch"); 16273 return; 16274 } 16275 16276 // In case of rollback, remember per-user/profile install state 16277 allUsers = sUserManager.getUserIds(); 16278 installedUsers = ps.queryInstalledUsers(allUsers, true); 16279 16280 // don't allow an upgrade from full to ephemeral 16281 if (isInstantApp) { 16282 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 16283 for (int currentUser : allUsers) { 16284 if (!ps.getInstantApp(currentUser)) { 16285 // can't downgrade from full to instant 16286 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16287 + " for user: " + currentUser); 16288 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16289 return; 16290 } 16291 } 16292 } else if (!ps.getInstantApp(user.getIdentifier())) { 16293 // can't downgrade from full to instant 16294 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16295 + " for user: " + user.getIdentifier()); 16296 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16297 return; 16298 } 16299 } 16300 } 16301 16302 // Update what is removed 16303 res.removedInfo = new PackageRemovedInfo(this); 16304 res.removedInfo.uid = oldPackage.applicationInfo.uid; 16305 res.removedInfo.removedPackage = oldPackage.packageName; 16306 res.removedInfo.installerPackageName = ps.installerPackageName; 16307 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 16308 res.removedInfo.isUpdate = true; 16309 res.removedInfo.origUsers = installedUsers; 16310 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16311 for (int i = 0; i < installedUsers.length; i++) { 16312 final int userId = installedUsers[i]; 16313 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16314 } 16315 16316 final int childCount = (oldPackage.childPackages != null) 16317 ? oldPackage.childPackages.size() : 0; 16318 for (int i = 0; i < childCount; i++) { 16319 boolean childPackageUpdated = false; 16320 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16321 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16322 if (res.addedChildPackages != null) { 16323 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16324 if (childRes != null) { 16325 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16326 childRes.removedInfo.removedPackage = childPkg.packageName; 16327 if (childPs != null) { 16328 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16329 } 16330 childRes.removedInfo.isUpdate = true; 16331 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16332 childPackageUpdated = true; 16333 } 16334 } 16335 if (!childPackageUpdated) { 16336 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 16337 childRemovedRes.removedPackage = childPkg.packageName; 16338 if (childPs != null) { 16339 childRemovedRes.installerPackageName = childPs.installerPackageName; 16340 } 16341 childRemovedRes.isUpdate = false; 16342 childRemovedRes.dataRemoved = true; 16343 synchronized (mPackages) { 16344 if (childPs != null) { 16345 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16346 } 16347 } 16348 if (res.removedInfo.removedChildPackages == null) { 16349 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16350 } 16351 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16352 } 16353 } 16354 16355 boolean sysPkg = (isSystemApp(oldPackage)); 16356 if (sysPkg) { 16357 // Set the system/privileged/oem/vendor/product flags as needed 16358 final boolean privileged = 16359 (oldPackage.applicationInfo.privateFlags 16360 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16361 final boolean oem = 16362 (oldPackage.applicationInfo.privateFlags 16363 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 16364 final boolean vendor = 16365 (oldPackage.applicationInfo.privateFlags 16366 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 16367 final boolean product = 16368 (oldPackage.applicationInfo.privateFlags 16369 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 16370 final @ParseFlags int systemParseFlags = parseFlags; 16371 final @ScanFlags int systemScanFlags = scanFlags 16372 | SCAN_AS_SYSTEM 16373 | (privileged ? SCAN_AS_PRIVILEGED : 0) 16374 | (oem ? SCAN_AS_OEM : 0) 16375 | (vendor ? SCAN_AS_VENDOR : 0) 16376 | (product ? SCAN_AS_PRODUCT : 0); 16377 16378 replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags, 16379 user, allUsers, installerPackageName, res, installReason); 16380 } else { 16381 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 16382 user, allUsers, installerPackageName, res, installReason); 16383 } 16384 } 16385 16386 @Override 16387 public List<String> getPreviousCodePaths(String packageName) { 16388 final int callingUid = Binder.getCallingUid(); 16389 final List<String> result = new ArrayList<>(); 16390 if (getInstantAppPackageName(callingUid) != null) { 16391 return result; 16392 } 16393 final PackageSetting ps = mSettings.mPackages.get(packageName); 16394 if (ps != null 16395 && ps.oldCodePaths != null 16396 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 16397 result.addAll(ps.oldCodePaths); 16398 } 16399 return result; 16400 } 16401 16402 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16403 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16404 final @ScanFlags int scanFlags, UserHandle user, int[] allUsers, 16405 String installerPackageName, PackageInstalledInfo res, int installReason) { 16406 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16407 + deletedPackage); 16408 16409 String pkgName = deletedPackage.packageName; 16410 boolean deletedPkg = true; 16411 boolean addedPkg = false; 16412 boolean updatedSettings = false; 16413 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16414 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16415 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16416 16417 final long origUpdateTime = (pkg.mExtras != null) 16418 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16419 16420 // First delete the existing package while retaining the data directory 16421 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16422 res.removedInfo, true, pkg)) { 16423 // If the existing package wasn't successfully deleted 16424 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16425 deletedPkg = false; 16426 } else { 16427 // Successfully deleted the old package; proceed with replace. 16428 16429 // If deleted package lived in a container, give users a chance to 16430 // relinquish resources before killing. 16431 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16432 if (DEBUG_INSTALL) { 16433 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16434 } 16435 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16436 final ArrayList<String> pkgList = new ArrayList<String>(1); 16437 pkgList.add(deletedPackage.applicationInfo.packageName); 16438 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16439 } 16440 16441 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16442 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16443 16444 try { 16445 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 16446 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16447 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16448 installReason); 16449 16450 // Update the in-memory copy of the previous code paths. 16451 PackageSetting ps = mSettings.mPackages.get(pkgName); 16452 if (!killApp) { 16453 if (ps.oldCodePaths == null) { 16454 ps.oldCodePaths = new ArraySet<>(); 16455 } 16456 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16457 if (deletedPackage.splitCodePaths != null) { 16458 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16459 } 16460 } else { 16461 ps.oldCodePaths = null; 16462 } 16463 if (ps.childPackageNames != null) { 16464 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16465 final String childPkgName = ps.childPackageNames.get(i); 16466 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16467 childPs.oldCodePaths = ps.oldCodePaths; 16468 } 16469 } 16470 prepareAppDataAfterInstallLIF(newPackage); 16471 addedPkg = true; 16472 mDexManager.notifyPackageUpdated(newPackage.packageName, 16473 newPackage.baseCodePath, newPackage.splitCodePaths); 16474 } catch (PackageManagerException e) { 16475 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16476 } 16477 } 16478 16479 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16480 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16481 16482 // Revert all internal state mutations and added folders for the failed install 16483 if (addedPkg) { 16484 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16485 res.removedInfo, true, null); 16486 } 16487 16488 // Restore the old package 16489 if (deletedPkg) { 16490 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16491 File restoreFile = new File(deletedPackage.codePath); 16492 // Parse old package 16493 boolean oldExternal = isExternal(deletedPackage); 16494 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16495 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16496 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16497 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16498 try { 16499 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16500 null); 16501 } catch (PackageManagerException e) { 16502 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16503 + e.getMessage()); 16504 return; 16505 } 16506 16507 synchronized (mPackages) { 16508 // Ensure the installer package name up to date 16509 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16510 16511 // Update permissions for restored package 16512 mPermissionManager.updatePermissions( 16513 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16514 mPermissionCallback); 16515 16516 mSettings.writeLPr(); 16517 } 16518 16519 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16520 } 16521 } else { 16522 synchronized (mPackages) { 16523 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16524 if (ps != null) { 16525 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16526 if (res.removedInfo.removedChildPackages != null) { 16527 final int childCount = res.removedInfo.removedChildPackages.size(); 16528 // Iterate in reverse as we may modify the collection 16529 for (int i = childCount - 1; i >= 0; i--) { 16530 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16531 if (res.addedChildPackages.containsKey(childPackageName)) { 16532 res.removedInfo.removedChildPackages.removeAt(i); 16533 } else { 16534 PackageRemovedInfo childInfo = res.removedInfo 16535 .removedChildPackages.valueAt(i); 16536 childInfo.removedForAllUsers = mPackages.get( 16537 childInfo.removedPackage) == null; 16538 } 16539 } 16540 } 16541 } 16542 } 16543 } 16544 } 16545 16546 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16547 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16548 final @ScanFlags int scanFlags, UserHandle user, 16549 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16550 int installReason) { 16551 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16552 + ", old=" + deletedPackage); 16553 16554 final boolean disabledSystem; 16555 16556 // Remove existing system package 16557 removePackageLI(deletedPackage, true); 16558 16559 synchronized (mPackages) { 16560 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16561 } 16562 if (!disabledSystem) { 16563 // We didn't need to disable the .apk as a current system package, 16564 // which means we are replacing another update that is already 16565 // installed. We need to make sure to delete the older one's .apk. 16566 res.removedInfo.args = createInstallArgsForExisting(0, 16567 deletedPackage.applicationInfo.getCodePath(), 16568 deletedPackage.applicationInfo.getResourcePath(), 16569 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16570 } else { 16571 res.removedInfo.args = null; 16572 } 16573 16574 // Successfully disabled the old package. Now proceed with re-installation 16575 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16576 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16577 16578 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16579 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16580 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16581 16582 PackageParser.Package newPackage = null; 16583 try { 16584 // Add the package to the internal data structures 16585 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 16586 16587 // Set the update and install times 16588 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16589 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16590 System.currentTimeMillis()); 16591 16592 // Update the package dynamic state if succeeded 16593 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16594 // Now that the install succeeded make sure we remove data 16595 // directories for any child package the update removed. 16596 final int deletedChildCount = (deletedPackage.childPackages != null) 16597 ? deletedPackage.childPackages.size() : 0; 16598 final int newChildCount = (newPackage.childPackages != null) 16599 ? newPackage.childPackages.size() : 0; 16600 for (int i = 0; i < deletedChildCount; i++) { 16601 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16602 boolean childPackageDeleted = true; 16603 for (int j = 0; j < newChildCount; j++) { 16604 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16605 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16606 childPackageDeleted = false; 16607 break; 16608 } 16609 } 16610 if (childPackageDeleted) { 16611 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16612 deletedChildPkg.packageName); 16613 if (ps != null && res.removedInfo.removedChildPackages != null) { 16614 PackageRemovedInfo removedChildRes = res.removedInfo 16615 .removedChildPackages.get(deletedChildPkg.packageName); 16616 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16617 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16618 } 16619 } 16620 } 16621 16622 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16623 installReason); 16624 prepareAppDataAfterInstallLIF(newPackage); 16625 16626 mDexManager.notifyPackageUpdated(newPackage.packageName, 16627 newPackage.baseCodePath, newPackage.splitCodePaths); 16628 } 16629 } catch (PackageManagerException e) { 16630 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16631 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16632 } 16633 16634 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16635 // Re installation failed. Restore old information 16636 // Remove new pkg information 16637 if (newPackage != null) { 16638 removeInstalledPackageLI(newPackage, true); 16639 } 16640 // Add back the old system package 16641 try { 16642 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16643 } catch (PackageManagerException e) { 16644 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16645 } 16646 16647 synchronized (mPackages) { 16648 if (disabledSystem) { 16649 enableSystemPackageLPw(deletedPackage); 16650 } 16651 16652 // Ensure the installer package name up to date 16653 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16654 16655 // Update permissions for restored package 16656 mPermissionManager.updatePermissions( 16657 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16658 mPermissionCallback); 16659 16660 mSettings.writeLPr(); 16661 } 16662 16663 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16664 + " after failed upgrade"); 16665 } 16666 } 16667 16668 /** 16669 * Checks whether the parent or any of the child packages have a change shared 16670 * user. For a package to be a valid update the shred users of the parent and 16671 * the children should match. We may later support changing child shared users. 16672 * @param oldPkg The updated package. 16673 * @param newPkg The update package. 16674 * @return The shared user that change between the versions. 16675 */ 16676 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16677 PackageParser.Package newPkg) { 16678 // Check parent shared user 16679 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16680 return newPkg.packageName; 16681 } 16682 // Check child shared users 16683 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16684 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16685 for (int i = 0; i < newChildCount; i++) { 16686 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16687 // If this child was present, did it have the same shared user? 16688 for (int j = 0; j < oldChildCount; j++) { 16689 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16690 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16691 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16692 return newChildPkg.packageName; 16693 } 16694 } 16695 } 16696 return null; 16697 } 16698 16699 private void removeNativeBinariesLI(PackageSetting ps) { 16700 // Remove the lib path for the parent package 16701 if (ps != null) { 16702 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16703 // Remove the lib path for the child packages 16704 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16705 for (int i = 0; i < childCount; i++) { 16706 PackageSetting childPs = null; 16707 synchronized (mPackages) { 16708 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16709 } 16710 if (childPs != null) { 16711 NativeLibraryHelper.removeNativeBinariesLI(childPs 16712 .legacyNativeLibraryPathString); 16713 } 16714 } 16715 } 16716 } 16717 16718 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16719 // Enable the parent package 16720 mSettings.enableSystemPackageLPw(pkg.packageName); 16721 // Enable the child packages 16722 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16723 for (int i = 0; i < childCount; i++) { 16724 PackageParser.Package childPkg = pkg.childPackages.get(i); 16725 mSettings.enableSystemPackageLPw(childPkg.packageName); 16726 } 16727 } 16728 16729 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16730 PackageParser.Package newPkg) { 16731 // Disable the parent package (parent always replaced) 16732 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16733 // Disable the child packages 16734 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16735 for (int i = 0; i < childCount; i++) { 16736 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16737 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16738 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16739 } 16740 return disabled; 16741 } 16742 16743 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16744 String installerPackageName) { 16745 // Enable the parent package 16746 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16747 // Enable the child packages 16748 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16749 for (int i = 0; i < childCount; i++) { 16750 PackageParser.Package childPkg = pkg.childPackages.get(i); 16751 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16752 } 16753 } 16754 16755 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16756 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16757 // Update the parent package setting 16758 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16759 res, user, installReason); 16760 // Update the child packages setting 16761 final int childCount = (newPackage.childPackages != null) 16762 ? newPackage.childPackages.size() : 0; 16763 for (int i = 0; i < childCount; i++) { 16764 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16765 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16766 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16767 childRes.origUsers, childRes, user, installReason); 16768 } 16769 } 16770 16771 private void updateSettingsInternalLI(PackageParser.Package pkg, 16772 String installerPackageName, int[] allUsers, int[] installedForUsers, 16773 PackageInstalledInfo res, UserHandle user, int installReason) { 16774 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16775 16776 final String pkgName = pkg.packageName; 16777 16778 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath); 16779 synchronized (mPackages) { 16780// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions 16781 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 16782 mPermissionCallback); 16783 // For system-bundled packages, we assume that installing an upgraded version 16784 // of the package implies that the user actually wants to run that new code, 16785 // so we enable the package. 16786 PackageSetting ps = mSettings.mPackages.get(pkgName); 16787 final int userId = user.getIdentifier(); 16788 if (ps != null) { 16789 if (isSystemApp(pkg)) { 16790 if (DEBUG_INSTALL) { 16791 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16792 } 16793 // Enable system package for requested users 16794 if (res.origUsers != null) { 16795 for (int origUserId : res.origUsers) { 16796 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16797 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16798 origUserId, installerPackageName); 16799 } 16800 } 16801 } 16802 // Also convey the prior install/uninstall state 16803 if (allUsers != null && installedForUsers != null) { 16804 for (int currentUserId : allUsers) { 16805 final boolean installed = ArrayUtils.contains( 16806 installedForUsers, currentUserId); 16807 if (DEBUG_INSTALL) { 16808 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16809 } 16810 ps.setInstalled(installed, currentUserId); 16811 } 16812 // these install state changes will be persisted in the 16813 // upcoming call to mSettings.writeLPr(). 16814 } 16815 } 16816 // It's implied that when a user requests installation, they want the app to be 16817 // installed and enabled. 16818 if (userId != UserHandle.USER_ALL) { 16819 ps.setInstalled(true, userId); 16820 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16821 } 16822 16823 // When replacing an existing package, preserve the original install reason for all 16824 // users that had the package installed before. 16825 final Set<Integer> previousUserIds = new ArraySet<>(); 16826 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16827 final int installReasonCount = res.removedInfo.installReasons.size(); 16828 for (int i = 0; i < installReasonCount; i++) { 16829 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16830 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16831 ps.setInstallReason(previousInstallReason, previousUserId); 16832 previousUserIds.add(previousUserId); 16833 } 16834 } 16835 16836 // Set install reason for users that are having the package newly installed. 16837 if (userId == UserHandle.USER_ALL) { 16838 for (int currentUserId : sUserManager.getUserIds()) { 16839 if (!previousUserIds.contains(currentUserId)) { 16840 ps.setInstallReason(installReason, currentUserId); 16841 } 16842 } 16843 } else if (!previousUserIds.contains(userId)) { 16844 ps.setInstallReason(installReason, userId); 16845 } 16846 mSettings.writeKernelMappingLPr(ps); 16847 } 16848 res.name = pkgName; 16849 res.uid = pkg.applicationInfo.uid; 16850 res.pkg = pkg; 16851 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16852 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16853 //to update install status 16854 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16855 mSettings.writeLPr(); 16856 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16857 } 16858 16859 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16860 } 16861 16862 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16863 try { 16864 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16865 installPackageLI(args, res); 16866 } finally { 16867 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16868 } 16869 } 16870 16871 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16872 final int installFlags = args.installFlags; 16873 final String installerPackageName = args.installerPackageName; 16874 final String volumeUuid = args.volumeUuid; 16875 final File tmpPackageFile = new File(args.getCodePath()); 16876 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16877 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16878 || (args.volumeUuid != null)); 16879 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16880 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16881 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16882 final boolean virtualPreload = 16883 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 16884 boolean replace = false; 16885 @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16886 if (args.move != null) { 16887 // moving a complete application; perform an initial scan on the new install location 16888 scanFlags |= SCAN_INITIAL; 16889 } 16890 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16891 scanFlags |= SCAN_DONT_KILL_APP; 16892 } 16893 if (instantApp) { 16894 scanFlags |= SCAN_AS_INSTANT_APP; 16895 } 16896 if (fullApp) { 16897 scanFlags |= SCAN_AS_FULL_APP; 16898 } 16899 if (virtualPreload) { 16900 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 16901 } 16902 16903 // Result object to be returned 16904 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16905 res.installerPackageName = installerPackageName; 16906 16907 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16908 16909 // Sanity check 16910 if (instantApp && (forwardLocked || onExternal)) { 16911 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16912 + " external=" + onExternal); 16913 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16914 return; 16915 } 16916 16917 // Retrieve PackageSettings and parse package 16918 @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16919 | PackageParser.PARSE_ENFORCE_CODE 16920 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16921 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16922 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16923 PackageParser pp = new PackageParser(); 16924 pp.setSeparateProcesses(mSeparateProcesses); 16925 pp.setDisplayMetrics(mMetrics); 16926 pp.setCallback(mPackageParserCallback); 16927 16928 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16929 final PackageParser.Package pkg; 16930 try { 16931 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16932 DexMetadataHelper.validatePackageDexMetadata(pkg); 16933 } catch (PackageParserException e) { 16934 res.setError("Failed parse during installPackageLI", e); 16935 return; 16936 } finally { 16937 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16938 } 16939 16940 // Instant apps have several additional install-time checks. 16941 if (instantApp) { 16942 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 16943 Slog.w(TAG, 16944 "Instant app package " + pkg.packageName + " does not target at least O"); 16945 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16946 "Instant app package must target at least O"); 16947 return; 16948 } 16949 if (pkg.applicationInfo.targetSandboxVersion != 2) { 16950 Slog.w(TAG, "Instant app package " + pkg.packageName 16951 + " does not target targetSandboxVersion 2"); 16952 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16953 "Instant app package must use targetSandboxVersion 2"); 16954 return; 16955 } 16956 if (pkg.mSharedUserId != null) { 16957 Slog.w(TAG, "Instant app package " + pkg.packageName 16958 + " may not declare sharedUserId."); 16959 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16960 "Instant app package may not declare a sharedUserId"); 16961 return; 16962 } 16963 } 16964 16965 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16966 // Static shared libraries have synthetic package names 16967 renameStaticSharedLibraryPackage(pkg); 16968 16969 // No static shared libs on external storage 16970 if (onExternal) { 16971 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16972 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16973 "Packages declaring static-shared libs cannot be updated"); 16974 return; 16975 } 16976 } 16977 16978 // If we are installing a clustered package add results for the children 16979 if (pkg.childPackages != null) { 16980 synchronized (mPackages) { 16981 final int childCount = pkg.childPackages.size(); 16982 for (int i = 0; i < childCount; i++) { 16983 PackageParser.Package childPkg = pkg.childPackages.get(i); 16984 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16985 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16986 childRes.pkg = childPkg; 16987 childRes.name = childPkg.packageName; 16988 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16989 if (childPs != null) { 16990 childRes.origUsers = childPs.queryInstalledUsers( 16991 sUserManager.getUserIds(), true); 16992 } 16993 if ((mPackages.containsKey(childPkg.packageName))) { 16994 childRes.removedInfo = new PackageRemovedInfo(this); 16995 childRes.removedInfo.removedPackage = childPkg.packageName; 16996 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16997 } 16998 if (res.addedChildPackages == null) { 16999 res.addedChildPackages = new ArrayMap<>(); 17000 } 17001 res.addedChildPackages.put(childPkg.packageName, childRes); 17002 } 17003 } 17004 } 17005 17006 // If package doesn't declare API override, mark that we have an install 17007 // time CPU ABI override. 17008 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 17009 pkg.cpuAbiOverride = args.abiOverride; 17010 } 17011 17012 String pkgName = res.name = pkg.packageName; 17013 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 17014 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 17015 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 17016 return; 17017 } 17018 } 17019 17020 try { 17021 // either use what we've been given or parse directly from the APK 17022 if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) { 17023 pkg.setSigningDetails(args.signingDetails); 17024 } else { 17025 PackageParser.collectCertificates(pkg, false /* skipVerify */); 17026 } 17027 } catch (PackageParserException e) { 17028 res.setError("Failed collect during installPackageLI", e); 17029 return; 17030 } 17031 17032 if (instantApp && pkg.mSigningDetails.signatureSchemeVersion 17033 < SignatureSchemeVersion.SIGNING_BLOCK_V2) { 17034 Slog.w(TAG, "Instant app package " + pkg.packageName 17035 + " is not signed with at least APK Signature Scheme v2"); 17036 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 17037 "Instant app package must be signed with APK Signature Scheme v2 or greater"); 17038 return; 17039 } 17040 17041 // Get rid of all references to package scan path via parser. 17042 pp = null; 17043 String oldCodePath = null; 17044 boolean systemApp = false; 17045 synchronized (mPackages) { 17046 // Check if installing already existing package 17047 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 17048 String oldName = mSettings.getRenamedPackageLPr(pkgName); 17049 if (pkg.mOriginalPackages != null 17050 && pkg.mOriginalPackages.contains(oldName) 17051 && mPackages.containsKey(oldName)) { 17052 // This package is derived from an original package, 17053 // and this device has been updating from that original 17054 // name. We must continue using the original name, so 17055 // rename the new package here. 17056 pkg.setPackageName(oldName); 17057 pkgName = pkg.packageName; 17058 replace = true; 17059 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 17060 + oldName + " pkgName=" + pkgName); 17061 } else if (mPackages.containsKey(pkgName)) { 17062 // This package, under its official name, already exists 17063 // on the device; we should replace it. 17064 replace = true; 17065 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 17066 } 17067 17068 // Child packages are installed through the parent package 17069 if (pkg.parentPackage != null) { 17070 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 17071 "Package " + pkg.packageName + " is child of package " 17072 + pkg.parentPackage.parentPackage + ". Child packages " 17073 + "can be updated only through the parent package."); 17074 return; 17075 } 17076 17077 if (replace) { 17078 // Prevent apps opting out from runtime permissions 17079 PackageParser.Package oldPackage = mPackages.get(pkgName); 17080 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 17081 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 17082 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 17083 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 17084 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 17085 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 17086 + " doesn't support runtime permissions but the old" 17087 + " target SDK " + oldTargetSdk + " does."); 17088 return; 17089 } 17090 // Prevent persistent apps from being updated 17091 if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) { 17092 res.setError(PackageManager.INSTALL_FAILED_INVALID_APK, 17093 "Package " + oldPackage.packageName + " is a persistent app. " 17094 + "Persistent apps are not updateable."); 17095 return; 17096 } 17097 // Prevent apps from downgrading their targetSandbox. 17098 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 17099 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 17100 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 17101 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 17102 "Package " + pkg.packageName + " new target sandbox " 17103 + newTargetSandbox + " is incompatible with the previous value of" 17104 + oldTargetSandbox + "."); 17105 return; 17106 } 17107 17108 // Prevent installing of child packages 17109 if (oldPackage.parentPackage != null) { 17110 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 17111 "Package " + pkg.packageName + " is child of package " 17112 + oldPackage.parentPackage + ". Child packages " 17113 + "can be updated only through the parent package."); 17114 return; 17115 } 17116 } 17117 } 17118 17119 PackageSetting ps = mSettings.mPackages.get(pkgName); 17120 if (ps != null) { 17121 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 17122 17123 // Static shared libs have same package with different versions where 17124 // we internally use a synthetic package name to allow multiple versions 17125 // of the same package, therefore we need to compare signatures against 17126 // the package setting for the latest library version. 17127 PackageSetting signatureCheckPs = ps; 17128 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17129 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 17130 if (libraryEntry != null) { 17131 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 17132 } 17133 } 17134 17135 // Quick sanity check that we're signed correctly if updating; 17136 // we'll check this again later when scanning, but we want to 17137 // bail early here before tripping over redefined permissions. 17138 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 17139 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 17140 if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 17141 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 17142 + pkg.packageName + " upgrade keys do not match the " 17143 + "previously installed version"); 17144 return; 17145 } 17146 } else { 17147 try { 17148 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 17149 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 17150 // We don't care about disabledPkgSetting on install for now. 17151 final boolean compatMatch = verifySignatures( 17152 signatureCheckPs, null, pkg.mSigningDetails, compareCompat, 17153 compareRecover); 17154 // The new KeySets will be re-added later in the scanning process. 17155 if (compatMatch) { 17156 synchronized (mPackages) { 17157 ksms.removeAppKeySetDataLPw(pkg.packageName); 17158 } 17159 } 17160 } catch (PackageManagerException e) { 17161 res.setError(e.error, e.getMessage()); 17162 return; 17163 } 17164 } 17165 17166 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 17167 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 17168 systemApp = (ps.pkg.applicationInfo.flags & 17169 ApplicationInfo.FLAG_SYSTEM) != 0; 17170 } 17171 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17172 } 17173 17174 int N = pkg.permissions.size(); 17175 for (int i = N-1; i >= 0; i--) { 17176 final PackageParser.Permission perm = pkg.permissions.get(i); 17177 final BasePermission bp = 17178 (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name); 17179 17180 // Don't allow anyone but the system to define ephemeral permissions. 17181 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 17182 && !systemApp) { 17183 Slog.w(TAG, "Non-System package " + pkg.packageName 17184 + " attempting to delcare ephemeral permission " 17185 + perm.info.name + "; Removing ephemeral."); 17186 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 17187 } 17188 17189 // Check whether the newly-scanned package wants to define an already-defined perm 17190 if (bp != null) { 17191 // If the defining package is signed with our cert, it's okay. This 17192 // also includes the "updating the same package" case, of course. 17193 // "updating same package" could also involve key-rotation. 17194 final boolean sigsOk; 17195 final String sourcePackageName = bp.getSourcePackageName(); 17196 final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting(); 17197 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 17198 if (sourcePackageName.equals(pkg.packageName) 17199 && (ksms.shouldCheckUpgradeKeySetLocked( 17200 sourcePackageSetting, scanFlags))) { 17201 sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg); 17202 } else { 17203 17204 // in the event of signing certificate rotation, we need to see if the 17205 // package's certificate has rotated from the current one, or if it is an 17206 // older certificate with which the current is ok with sharing permissions 17207 if (sourcePackageSetting.signatures.mSigningDetails.checkCapability( 17208 pkg.mSigningDetails, 17209 PackageParser.SigningDetails.CertCapabilities.PERMISSION)) { 17210 sigsOk = true; 17211 } else if (pkg.mSigningDetails.checkCapability( 17212 sourcePackageSetting.signatures.mSigningDetails, 17213 PackageParser.SigningDetails.CertCapabilities.PERMISSION)) { 17214 17215 // the scanned package checks out, has signing certificate rotation 17216 // history, and is newer; bring it over 17217 sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails; 17218 sigsOk = true; 17219 } else { 17220 sigsOk = false; 17221 } 17222 } 17223 if (!sigsOk) { 17224 // If the owning package is the system itself, we log but allow 17225 // install to proceed; we fail the install on all other permission 17226 // redefinitions. 17227 if (!sourcePackageName.equals("android")) { 17228 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 17229 + pkg.packageName + " attempting to redeclare permission " 17230 + perm.info.name + " already owned by " + sourcePackageName); 17231 res.origPermission = perm.info.name; 17232 res.origPackage = sourcePackageName; 17233 return; 17234 } else { 17235 Slog.w(TAG, "Package " + pkg.packageName 17236 + " attempting to redeclare system permission " 17237 + perm.info.name + "; ignoring new declaration"); 17238 pkg.permissions.remove(i); 17239 } 17240 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 17241 // Prevent apps to change protection level to dangerous from any other 17242 // type as this would allow a privilege escalation where an app adds a 17243 // normal/signature permission in other app's group and later redefines 17244 // it as dangerous leading to the group auto-grant. 17245 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 17246 == PermissionInfo.PROTECTION_DANGEROUS) { 17247 if (bp != null && !bp.isRuntime()) { 17248 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 17249 + "non-runtime permission " + perm.info.name 17250 + " to runtime; keeping old protection level"); 17251 perm.info.protectionLevel = bp.getProtectionLevel(); 17252 } 17253 } 17254 } 17255 } 17256 } 17257 } 17258 17259 if (systemApp) { 17260 if (onExternal) { 17261 // Abort update; system app can't be replaced with app on sdcard 17262 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17263 "Cannot install updates to system apps on sdcard"); 17264 return; 17265 } else if (instantApp) { 17266 // Abort update; system app can't be replaced with an instant app 17267 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 17268 "Cannot update a system app with an instant app"); 17269 return; 17270 } 17271 } 17272 17273 if (args.move != null) { 17274 // We did an in-place move, so dex is ready to roll 17275 scanFlags |= SCAN_NO_DEX; 17276 scanFlags |= SCAN_MOVE; 17277 17278 synchronized (mPackages) { 17279 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17280 if (ps == null) { 17281 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17282 "Missing settings for moved package " + pkgName); 17283 } 17284 17285 // We moved the entire application as-is, so bring over the 17286 // previously derived ABI information. 17287 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 17288 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 17289 } 17290 17291 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 17292 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 17293 scanFlags |= SCAN_NO_DEX; 17294 17295 try { 17296 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 17297 args.abiOverride : pkg.cpuAbiOverride); 17298 final boolean extractNativeLibs = !pkg.isLibrary(); 17299 derivePackageAbi(pkg, abiOverride, extractNativeLibs); 17300 } catch (PackageManagerException pme) { 17301 Slog.e(TAG, "Error deriving application ABI", pme); 17302 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 17303 return; 17304 } 17305 17306 // Shared libraries for the package need to be updated. 17307 synchronized (mPackages) { 17308 try { 17309 updateSharedLibrariesLPr(pkg, null); 17310 } catch (PackageManagerException e) { 17311 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17312 } 17313 } 17314 } 17315 17316 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 17317 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17318 return; 17319 } 17320 17321 if (PackageManagerServiceUtils.isApkVerityEnabled()) { 17322 String apkPath = null; 17323 synchronized (mPackages) { 17324 // Note that if the attacker managed to skip verify setup, for example by tampering 17325 // with the package settings, upon reboot we will do full apk verification when 17326 // verity is not detected. 17327 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17328 if (ps != null && ps.isPrivileged()) { 17329 apkPath = pkg.baseCodePath; 17330 } 17331 } 17332 17333 if (apkPath != null) { 17334 final VerityUtils.SetupResult result = 17335 VerityUtils.generateApkVeritySetupData(apkPath); 17336 if (result.isOk()) { 17337 if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath); 17338 FileDescriptor fd = result.getUnownedFileDescriptor(); 17339 try { 17340 final byte[] signedRootHash = VerityUtils.generateFsverityRootHash(apkPath); 17341 mInstaller.installApkVerity(apkPath, fd, result.getContentSize()); 17342 mInstaller.assertFsverityRootHashMatches(apkPath, signedRootHash); 17343 } catch (InstallerException | IOException | DigestException | 17344 NoSuchAlgorithmException e) { 17345 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17346 "Failed to set up verity: " + e); 17347 return; 17348 } finally { 17349 IoUtils.closeQuietly(fd); 17350 } 17351 } else if (result.isFailed()) { 17352 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity"); 17353 return; 17354 } else { 17355 // Do nothing if verity is skipped. Will fall back to full apk verification on 17356 // reboot. 17357 } 17358 } 17359 } 17360 17361 if (!instantApp) { 17362 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17363 } else { 17364 if (DEBUG_DOMAIN_VERIFICATION) { 17365 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName); 17366 } 17367 } 17368 17369 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17370 "installPackageLI")) { 17371 if (replace) { 17372 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17373 // Static libs have a synthetic package name containing the version 17374 // and cannot be updated as an update would get a new package name, 17375 // unless this is the exact same version code which is useful for 17376 // development. 17377 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17378 if (existingPkg != null && 17379 existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) { 17380 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17381 + "static-shared libs cannot be updated"); 17382 return; 17383 } 17384 } 17385 replacePackageLIF(pkg, parseFlags, scanFlags, args.user, 17386 installerPackageName, res, args.installReason); 17387 } else { 17388 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17389 args.user, installerPackageName, volumeUuid, res, args.installReason); 17390 } 17391 } 17392 17393 // Prepare the application profiles for the new code paths. 17394 // This needs to be done before invoking dexopt so that any install-time profile 17395 // can be used for optimizations. 17396 mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier())); 17397 17398 // Check whether we need to dexopt the app. 17399 // 17400 // NOTE: it is IMPORTANT to call dexopt: 17401 // - after doRename which will sync the package data from PackageParser.Package and its 17402 // corresponding ApplicationInfo. 17403 // - after installNewPackageLIF or replacePackageLIF which will update result with the 17404 // uid of the application (pkg.applicationInfo.uid). 17405 // This update happens in place! 17406 // 17407 // We only need to dexopt if the package meets ALL of the following conditions: 17408 // 1) it is not forward locked. 17409 // 2) it is not on on an external ASEC container. 17410 // 3) it is not an instant app or if it is then dexopt is enabled via gservices. 17411 // 17412 // Note that we do not dexopt instant apps by default. dexopt can take some time to 17413 // complete, so we skip this step during installation. Instead, we'll take extra time 17414 // the first time the instant app starts. It's preferred to do it this way to provide 17415 // continuous progress to the useur instead of mysteriously blocking somewhere in the 17416 // middle of running an instant app. The default behaviour can be overridden 17417 // via gservices. 17418 final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED) 17419 && !forwardLocked 17420 && !pkg.applicationInfo.isExternalAsec() 17421 && (!instantApp || Global.getInt(mContext.getContentResolver(), 17422 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0); 17423 17424 if (performDexopt) { 17425 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17426 // Do not run PackageDexOptimizer through the local performDexOpt 17427 // method because `pkg` may not be in `mPackages` yet. 17428 // 17429 // Also, don't fail application installs if the dexopt step fails. 17430 DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName, 17431 REASON_INSTALL, 17432 DexoptOptions.DEXOPT_BOOT_COMPLETE | 17433 DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE); 17434 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17435 null /* instructionSets */, 17436 getOrCreateCompilerPackageStats(pkg), 17437 mDexManager.getPackageUseInfoOrDefault(pkg.packageName), 17438 dexoptOptions); 17439 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17440 } 17441 17442 // Notify BackgroundDexOptService that the package has been changed. 17443 // If this is an update of a package which used to fail to compile, 17444 // BackgroundDexOptService will remove it from its blacklist. 17445 // TODO: Layering violation 17446 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17447 17448 synchronized (mPackages) { 17449 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17450 if (ps != null) { 17451 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17452 ps.setUpdateAvailable(false /*updateAvailable*/); 17453 } 17454 17455 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17456 for (int i = 0; i < childCount; i++) { 17457 PackageParser.Package childPkg = pkg.childPackages.get(i); 17458 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17459 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17460 if (childPs != null) { 17461 childRes.newUsers = childPs.queryInstalledUsers( 17462 sUserManager.getUserIds(), true); 17463 } 17464 } 17465 17466 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17467 updateSequenceNumberLP(ps, res.newUsers); 17468 updateInstantAppInstallerLocked(pkgName); 17469 } 17470 } 17471 } 17472 17473 private void startIntentFilterVerifications(int userId, boolean replacing, 17474 PackageParser.Package pkg) { 17475 if (mIntentFilterVerifierComponent == null) { 17476 Slog.w(TAG, "No IntentFilter verification will not be done as " 17477 + "there is no IntentFilterVerifier available!"); 17478 return; 17479 } 17480 17481 final int verifierUid = getPackageUid( 17482 mIntentFilterVerifierComponent.getPackageName(), 17483 MATCH_DEBUG_TRIAGED_MISSING, 17484 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17485 17486 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17487 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17488 mHandler.sendMessage(msg); 17489 17490 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17491 for (int i = 0; i < childCount; i++) { 17492 PackageParser.Package childPkg = pkg.childPackages.get(i); 17493 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17494 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17495 mHandler.sendMessage(msg); 17496 } 17497 } 17498 17499 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17500 PackageParser.Package pkg) { 17501 int size = pkg.activities.size(); 17502 if (size == 0) { 17503 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17504 "No activity, so no need to verify any IntentFilter!"); 17505 return; 17506 } 17507 17508 final boolean hasDomainURLs = hasDomainURLs(pkg); 17509 if (!hasDomainURLs) { 17510 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17511 "No domain URLs, so no need to verify any IntentFilter!"); 17512 return; 17513 } 17514 17515 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17516 + " if any IntentFilter from the " + size 17517 + " Activities needs verification ..."); 17518 17519 int count = 0; 17520 final String packageName = pkg.packageName; 17521 17522 synchronized (mPackages) { 17523 // If this is a new install and we see that we've already run verification for this 17524 // package, we have nothing to do: it means the state was restored from backup. 17525 if (!replacing) { 17526 IntentFilterVerificationInfo ivi = 17527 mSettings.getIntentFilterVerificationLPr(packageName); 17528 if (ivi != null) { 17529 if (DEBUG_DOMAIN_VERIFICATION) { 17530 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17531 + ivi.getStatusString()); 17532 } 17533 return; 17534 } 17535 } 17536 17537 // If any filters need to be verified, then all need to be. 17538 boolean needToVerify = false; 17539 for (PackageParser.Activity a : pkg.activities) { 17540 for (ActivityIntentInfo filter : a.intents) { 17541 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17542 if (DEBUG_DOMAIN_VERIFICATION) { 17543 Slog.d(TAG, 17544 "Intent filter needs verification, so processing all filters"); 17545 } 17546 needToVerify = true; 17547 break; 17548 } 17549 } 17550 } 17551 17552 if (needToVerify) { 17553 final int verificationId = mIntentFilterVerificationToken++; 17554 for (PackageParser.Activity a : pkg.activities) { 17555 for (ActivityIntentInfo filter : a.intents) { 17556 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17557 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17558 "Verification needed for IntentFilter:" + filter.toString()); 17559 mIntentFilterVerifier.addOneIntentFilterVerification( 17560 verifierUid, userId, verificationId, filter, packageName); 17561 count++; 17562 } 17563 } 17564 } 17565 } 17566 } 17567 17568 if (count > 0) { 17569 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17570 + " IntentFilter verification" + (count > 1 ? "s" : "") 17571 + " for userId:" + userId); 17572 mIntentFilterVerifier.startVerifications(userId); 17573 } else { 17574 if (DEBUG_DOMAIN_VERIFICATION) { 17575 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17576 } 17577 } 17578 } 17579 17580 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17581 final ComponentName cn = filter.activity.getComponentName(); 17582 final String packageName = cn.getPackageName(); 17583 17584 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17585 packageName); 17586 if (ivi == null) { 17587 return true; 17588 } 17589 int status = ivi.getStatus(); 17590 switch (status) { 17591 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17592 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17593 return true; 17594 17595 default: 17596 // Nothing to do 17597 return false; 17598 } 17599 } 17600 17601 private static boolean isMultiArch(ApplicationInfo info) { 17602 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17603 } 17604 17605 private static boolean isExternal(PackageParser.Package pkg) { 17606 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17607 } 17608 17609 private static boolean isExternal(PackageSetting ps) { 17610 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17611 } 17612 17613 private static boolean isSystemApp(PackageParser.Package pkg) { 17614 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17615 } 17616 17617 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17618 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17619 } 17620 17621 private static boolean isOemApp(PackageParser.Package pkg) { 17622 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 17623 } 17624 17625 private static boolean isVendorApp(PackageParser.Package pkg) { 17626 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 17627 } 17628 17629 private static boolean isProductApp(PackageParser.Package pkg) { 17630 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 17631 } 17632 17633 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17634 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17635 } 17636 17637 private static boolean isSystemApp(PackageSetting ps) { 17638 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17639 } 17640 17641 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17642 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17643 } 17644 17645 private int packageFlagsToInstallFlags(PackageSetting ps) { 17646 int installFlags = 0; 17647 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17648 // This existing package was an external ASEC install when we have 17649 // the external flag without a UUID 17650 installFlags |= PackageManager.INSTALL_EXTERNAL; 17651 } 17652 if (ps.isForwardLocked()) { 17653 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17654 } 17655 return installFlags; 17656 } 17657 17658 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17659 if (isExternal(pkg)) { 17660 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17661 return mSettings.getExternalVersion(); 17662 } else { 17663 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17664 } 17665 } else { 17666 return mSettings.getInternalVersion(); 17667 } 17668 } 17669 17670 private void deleteTempPackageFiles() { 17671 final FilenameFilter filter = new FilenameFilter() { 17672 public boolean accept(File dir, String name) { 17673 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17674 } 17675 }; 17676 for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) { 17677 file.delete(); 17678 } 17679 } 17680 17681 @Override 17682 public void deletePackageAsUser(String packageName, int versionCode, 17683 IPackageDeleteObserver observer, int userId, int flags) { 17684 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17685 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17686 } 17687 17688 @Override 17689 public void deletePackageVersioned(VersionedPackage versionedPackage, 17690 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17691 final int callingUid = Binder.getCallingUid(); 17692 mContext.enforceCallingOrSelfPermission( 17693 android.Manifest.permission.DELETE_PACKAGES, null); 17694 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 17695 Preconditions.checkNotNull(versionedPackage); 17696 Preconditions.checkNotNull(observer); 17697 Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(), 17698 PackageManager.VERSION_CODE_HIGHEST, 17699 Long.MAX_VALUE, "versionCode must be >= -1"); 17700 17701 final String packageName = versionedPackage.getPackageName(); 17702 final long versionCode = versionedPackage.getLongVersionCode(); 17703 final String internalPackageName; 17704 synchronized (mPackages) { 17705 // Normalize package name to handle renamed packages and static libs 17706 internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode); 17707 } 17708 17709 final int uid = Binder.getCallingUid(); 17710 if (!isOrphaned(internalPackageName) 17711 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17712 try { 17713 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17714 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17715 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17716 observer.onUserActionRequired(intent); 17717 } catch (RemoteException re) { 17718 } 17719 return; 17720 } 17721 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17722 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17723 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17724 mContext.enforceCallingOrSelfPermission( 17725 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17726 "deletePackage for user " + userId); 17727 } 17728 17729 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17730 try { 17731 observer.onPackageDeleted(packageName, 17732 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17733 } catch (RemoteException re) { 17734 } 17735 return; 17736 } 17737 17738 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17739 try { 17740 observer.onPackageDeleted(packageName, 17741 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17742 } catch (RemoteException re) { 17743 } 17744 return; 17745 } 17746 17747 if (DEBUG_REMOVE) { 17748 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17749 + " deleteAllUsers: " + deleteAllUsers + " version=" 17750 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17751 ? "VERSION_CODE_HIGHEST" : versionCode)); 17752 } 17753 // Queue up an async operation since the package deletion may take a little while. 17754 mHandler.post(new Runnable() { 17755 public void run() { 17756 mHandler.removeCallbacks(this); 17757 int returnCode; 17758 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 17759 boolean doDeletePackage = true; 17760 if (ps != null) { 17761 final boolean targetIsInstantApp = 17762 ps.getInstantApp(UserHandle.getUserId(callingUid)); 17763 doDeletePackage = !targetIsInstantApp 17764 || canViewInstantApps; 17765 } 17766 if (doDeletePackage) { 17767 if (!deleteAllUsers) { 17768 returnCode = deletePackageX(internalPackageName, versionCode, 17769 userId, deleteFlags); 17770 } else { 17771 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17772 internalPackageName, users); 17773 // If nobody is blocking uninstall, proceed with delete for all users 17774 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17775 returnCode = deletePackageX(internalPackageName, versionCode, 17776 userId, deleteFlags); 17777 } else { 17778 // Otherwise uninstall individually for users with blockUninstalls=false 17779 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17780 for (int userId : users) { 17781 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17782 returnCode = deletePackageX(internalPackageName, versionCode, 17783 userId, userFlags); 17784 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17785 Slog.w(TAG, "Package delete failed for user " + userId 17786 + ", returnCode " + returnCode); 17787 } 17788 } 17789 } 17790 // The app has only been marked uninstalled for certain users. 17791 // We still need to report that delete was blocked 17792 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17793 } 17794 } 17795 } else { 17796 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17797 } 17798 try { 17799 observer.onPackageDeleted(packageName, returnCode, null); 17800 } catch (RemoteException e) { 17801 Log.i(TAG, "Observer no longer exists."); 17802 } //end catch 17803 } //end run 17804 }); 17805 } 17806 17807 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17808 if (pkg.staticSharedLibName != null) { 17809 return pkg.manifestPackageName; 17810 } 17811 return pkg.packageName; 17812 } 17813 17814 private String resolveInternalPackageNameLPr(String packageName, long versionCode) { 17815 // Handle renamed packages 17816 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17817 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17818 17819 // Is this a static library? 17820 LongSparseArray<SharedLibraryEntry> versionedLib = 17821 mStaticLibsByDeclaringPackage.get(packageName); 17822 if (versionedLib == null || versionedLib.size() <= 0) { 17823 return packageName; 17824 } 17825 17826 // Figure out which lib versions the caller can see 17827 LongSparseLongArray versionsCallerCanSee = null; 17828 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17829 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17830 && callingAppId != Process.ROOT_UID) { 17831 versionsCallerCanSee = new LongSparseLongArray(); 17832 String libName = versionedLib.valueAt(0).info.getName(); 17833 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17834 if (uidPackages != null) { 17835 for (String uidPackage : uidPackages) { 17836 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17837 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17838 if (libIdx >= 0) { 17839 final long libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17840 versionsCallerCanSee.append(libVersion, libVersion); 17841 } 17842 } 17843 } 17844 } 17845 17846 // Caller can see nothing - done 17847 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17848 return packageName; 17849 } 17850 17851 // Find the version the caller can see and the app version code 17852 SharedLibraryEntry highestVersion = null; 17853 final int versionCount = versionedLib.size(); 17854 for (int i = 0; i < versionCount; i++) { 17855 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17856 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17857 libEntry.info.getLongVersion()) < 0) { 17858 continue; 17859 } 17860 final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode(); 17861 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17862 if (libVersionCode == versionCode) { 17863 return libEntry.apk; 17864 } 17865 } else if (highestVersion == null) { 17866 highestVersion = libEntry; 17867 } else if (libVersionCode > highestVersion.info 17868 .getDeclaringPackage().getLongVersionCode()) { 17869 highestVersion = libEntry; 17870 } 17871 } 17872 17873 if (highestVersion != null) { 17874 return highestVersion.apk; 17875 } 17876 17877 return packageName; 17878 } 17879 17880 boolean isCallerVerifier(int callingUid) { 17881 final int callingUserId = UserHandle.getUserId(callingUid); 17882 return mRequiredVerifierPackage != null && 17883 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 17884 } 17885 17886 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17887 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17888 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17889 return true; 17890 } 17891 final int callingUserId = UserHandle.getUserId(callingUid); 17892 // If the caller installed the pkgName, then allow it to silently uninstall. 17893 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17894 return true; 17895 } 17896 17897 // Allow package verifier to silently uninstall. 17898 if (mRequiredVerifierPackage != null && 17899 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17900 return true; 17901 } 17902 17903 // Allow package uninstaller to silently uninstall. 17904 if (mRequiredUninstallerPackage != null && 17905 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17906 return true; 17907 } 17908 17909 // Allow storage manager to silently uninstall. 17910 if (mStorageManagerPackage != null && 17911 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17912 return true; 17913 } 17914 17915 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 17916 // uninstall for device owner provisioning. 17917 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 17918 == PERMISSION_GRANTED) { 17919 return true; 17920 } 17921 17922 return false; 17923 } 17924 17925 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17926 int[] result = EMPTY_INT_ARRAY; 17927 for (int userId : userIds) { 17928 if (getBlockUninstallForUser(packageName, userId)) { 17929 result = ArrayUtils.appendInt(result, userId); 17930 } 17931 } 17932 return result; 17933 } 17934 17935 @Override 17936 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17937 final int callingUid = Binder.getCallingUid(); 17938 if (getInstantAppPackageName(callingUid) != null 17939 && !isCallerSameApp(packageName, callingUid)) { 17940 return false; 17941 } 17942 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17943 } 17944 17945 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17946 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17947 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17948 try { 17949 if (dpm != null) { 17950 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17951 /* callingUserOnly =*/ false); 17952 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17953 : deviceOwnerComponentName.getPackageName(); 17954 // Does the package contains the device owner? 17955 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17956 // this check is probably not needed, since DO should be registered as a device 17957 // admin on some user too. (Original bug for this: b/17657954) 17958 if (packageName.equals(deviceOwnerPackageName)) { 17959 return true; 17960 } 17961 // Does it contain a device admin for any user? 17962 int[] users; 17963 if (userId == UserHandle.USER_ALL) { 17964 users = sUserManager.getUserIds(); 17965 } else { 17966 users = new int[]{userId}; 17967 } 17968 for (int i = 0; i < users.length; ++i) { 17969 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17970 return true; 17971 } 17972 } 17973 } 17974 } catch (RemoteException e) { 17975 } 17976 return false; 17977 } 17978 17979 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17980 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17981 } 17982 17983 /** 17984 * This method is an internal method that could be get invoked either 17985 * to delete an installed package or to clean up a failed installation. 17986 * After deleting an installed package, a broadcast is sent to notify any 17987 * listeners that the package has been removed. For cleaning up a failed 17988 * installation, the broadcast is not necessary since the package's 17989 * installation wouldn't have sent the initial broadcast either 17990 * The key steps in deleting a package are 17991 * deleting the package information in internal structures like mPackages, 17992 * deleting the packages base directories through installd 17993 * updating mSettings to reflect current status 17994 * persisting settings for later use 17995 * sending a broadcast if necessary 17996 */ 17997 int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) { 17998 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17999 final boolean res; 18000 18001 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 18002 ? UserHandle.USER_ALL : userId; 18003 18004 if (isPackageDeviceAdmin(packageName, removeUser)) { 18005 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 18006 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 18007 } 18008 18009 PackageSetting uninstalledPs = null; 18010 PackageParser.Package pkg = null; 18011 18012 // for the uninstall-updates case and restricted profiles, remember the per- 18013 // user handle installed state 18014 int[] allUsers; 18015 synchronized (mPackages) { 18016 uninstalledPs = mSettings.mPackages.get(packageName); 18017 if (uninstalledPs == null) { 18018 Slog.w(TAG, "Not removing non-existent package " + packageName); 18019 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18020 } 18021 18022 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 18023 && uninstalledPs.versionCode != versionCode) { 18024 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 18025 + uninstalledPs.versionCode + " != " + versionCode); 18026 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18027 } 18028 18029 // Static shared libs can be declared by any package, so let us not 18030 // allow removing a package if it provides a lib others depend on. 18031 pkg = mPackages.get(packageName); 18032 18033 allUsers = sUserManager.getUserIds(); 18034 18035 if (pkg != null && pkg.staticSharedLibName != null) { 18036 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 18037 pkg.staticSharedLibVersion); 18038 if (libEntry != null) { 18039 for (int currUserId : allUsers) { 18040 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 18041 continue; 18042 } 18043 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 18044 libEntry.info, 0, currUserId); 18045 if (!ArrayUtils.isEmpty(libClientPackages)) { 18046 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 18047 + " hosting lib " + libEntry.info.getName() + " version " 18048 + libEntry.info.getLongVersion() + " used by " + libClientPackages 18049 + " for user " + currUserId); 18050 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 18051 } 18052 } 18053 } 18054 } 18055 18056 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 18057 } 18058 18059 final int freezeUser; 18060 if (isUpdatedSystemApp(uninstalledPs) 18061 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 18062 // We're downgrading a system app, which will apply to all users, so 18063 // freeze them all during the downgrade 18064 freezeUser = UserHandle.USER_ALL; 18065 } else { 18066 freezeUser = removeUser; 18067 } 18068 18069 synchronized (mInstallLock) { 18070 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 18071 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 18072 deleteFlags, "deletePackageX")) { 18073 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 18074 deleteFlags | PackageManager.DELETE_CHATTY, info, true, null); 18075 } 18076 synchronized (mPackages) { 18077 if (res) { 18078 if (pkg != null) { 18079 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 18080 } 18081 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 18082 updateInstantAppInstallerLocked(packageName); 18083 } 18084 } 18085 } 18086 18087 if (res) { 18088 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 18089 info.sendPackageRemovedBroadcasts(killApp); 18090 info.sendSystemPackageUpdatedBroadcasts(); 18091 info.sendSystemPackageAppearedBroadcasts(); 18092 } 18093 // Force a gc here. 18094 Runtime.getRuntime().gc(); 18095 // Delete the resources here after sending the broadcast to let 18096 // other processes clean up before deleting resources. 18097 if (info.args != null) { 18098 synchronized (mInstallLock) { 18099 info.args.doPostDeleteLI(true); 18100 } 18101 } 18102 18103 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18104 } 18105 18106 static class PackageRemovedInfo { 18107 final PackageSender packageSender; 18108 String removedPackage; 18109 String installerPackageName; 18110 int uid = -1; 18111 int removedAppId = -1; 18112 int[] origUsers; 18113 int[] removedUsers = null; 18114 int[] broadcastUsers = null; 18115 int[] instantUserIds = null; 18116 SparseArray<Integer> installReasons; 18117 boolean isRemovedPackageSystemUpdate = false; 18118 boolean isUpdate; 18119 boolean dataRemoved; 18120 boolean removedForAllUsers; 18121 boolean isStaticSharedLib; 18122 // Clean up resources deleted packages. 18123 InstallArgs args = null; 18124 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 18125 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 18126 18127 PackageRemovedInfo(PackageSender packageSender) { 18128 this.packageSender = packageSender; 18129 } 18130 18131 void sendPackageRemovedBroadcasts(boolean killApp) { 18132 sendPackageRemovedBroadcastInternal(killApp); 18133 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 18134 for (int i = 0; i < childCount; i++) { 18135 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18136 childInfo.sendPackageRemovedBroadcastInternal(killApp); 18137 } 18138 } 18139 18140 void sendSystemPackageUpdatedBroadcasts() { 18141 if (isRemovedPackageSystemUpdate) { 18142 sendSystemPackageUpdatedBroadcastsInternal(); 18143 final int childCount = (removedChildPackages != null) 18144 ? removedChildPackages.size() : 0; 18145 for (int i = 0; i < childCount; i++) { 18146 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18147 if (childInfo.isRemovedPackageSystemUpdate) { 18148 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 18149 } 18150 } 18151 } 18152 } 18153 18154 void sendSystemPackageAppearedBroadcasts() { 18155 final int packageCount = (appearedChildPackages != null) 18156 ? appearedChildPackages.size() : 0; 18157 for (int i = 0; i < packageCount; i++) { 18158 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 18159 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 18160 true /*sendBootCompleted*/, false /*startReceiver*/, 18161 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null); 18162 } 18163 } 18164 18165 private void sendSystemPackageUpdatedBroadcastsInternal() { 18166 Bundle extras = new Bundle(2); 18167 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18168 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18169 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18170 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 18171 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18172 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 18173 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 18174 null, null, 0, removedPackage, null, null, null); 18175 if (installerPackageName != null) { 18176 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18177 removedPackage, extras, 0 /*flags*/, 18178 installerPackageName, null, null, null); 18179 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18180 removedPackage, extras, 0 /*flags*/, 18181 installerPackageName, null, null, null); 18182 } 18183 } 18184 18185 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 18186 // Don't send static shared library removal broadcasts as these 18187 // libs are visible only the the apps that depend on them an one 18188 // cannot remove the library if it has a dependency. 18189 if (isStaticSharedLib) { 18190 return; 18191 } 18192 Bundle extras = new Bundle(2); 18193 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18194 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 18195 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 18196 if (isUpdate || isRemovedPackageSystemUpdate) { 18197 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18198 } 18199 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 18200 if (removedPackage != null) { 18201 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18202 removedPackage, extras, 0, null /*targetPackage*/, null, 18203 broadcastUsers, instantUserIds); 18204 if (installerPackageName != null) { 18205 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18206 removedPackage, extras, 0 /*flags*/, 18207 installerPackageName, null, broadcastUsers, instantUserIds); 18208 } 18209 if (dataRemoved && !isRemovedPackageSystemUpdate) { 18210 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 18211 removedPackage, extras, 18212 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18213 null, null, broadcastUsers, instantUserIds); 18214 packageSender.notifyPackageRemoved(removedPackage); 18215 } 18216 } 18217 if (removedAppId >= 0) { 18218 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 18219 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18220 null, null, broadcastUsers, instantUserIds); 18221 } 18222 } 18223 18224 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 18225 removedUsers = userIds; 18226 if (removedUsers == null) { 18227 broadcastUsers = null; 18228 return; 18229 } 18230 18231 broadcastUsers = EMPTY_INT_ARRAY; 18232 instantUserIds = EMPTY_INT_ARRAY; 18233 for (int i = userIds.length - 1; i >= 0; --i) { 18234 final int userId = userIds[i]; 18235 if (deletedPackageSetting.getInstantApp(userId)) { 18236 instantUserIds = ArrayUtils.appendInt(instantUserIds, userId); 18237 } else { 18238 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 18239 } 18240 } 18241 } 18242 } 18243 18244 /* 18245 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 18246 * flag is not set, the data directory is removed as well. 18247 * make sure this flag is set for partially installed apps. If not its meaningless to 18248 * delete a partially installed application. 18249 */ 18250 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 18251 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 18252 String packageName = ps.name; 18253 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 18254 // Retrieve object to delete permissions for shared user later on 18255 final PackageParser.Package deletedPkg; 18256 final PackageSetting deletedPs; 18257 // reader 18258 synchronized (mPackages) { 18259 deletedPkg = mPackages.get(packageName); 18260 deletedPs = mSettings.mPackages.get(packageName); 18261 if (outInfo != null) { 18262 outInfo.removedPackage = packageName; 18263 outInfo.installerPackageName = ps.installerPackageName; 18264 outInfo.isStaticSharedLib = deletedPkg != null 18265 && deletedPkg.staticSharedLibName != null; 18266 outInfo.populateUsers(deletedPs == null ? null 18267 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 18268 } 18269 } 18270 18271 removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0); 18272 18273 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 18274 final PackageParser.Package resolvedPkg; 18275 if (deletedPkg != null) { 18276 resolvedPkg = deletedPkg; 18277 } else { 18278 // We don't have a parsed package when it lives on an ejected 18279 // adopted storage device, so fake something together 18280 resolvedPkg = new PackageParser.Package(ps.name); 18281 resolvedPkg.setVolumeUuid(ps.volumeUuid); 18282 } 18283 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 18284 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18285 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 18286 if (outInfo != null) { 18287 outInfo.dataRemoved = true; 18288 } 18289 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 18290 } 18291 18292 int removedAppId = -1; 18293 18294 // writer 18295 synchronized (mPackages) { 18296 boolean installedStateChanged = false; 18297 if (deletedPs != null) { 18298 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 18299 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 18300 clearDefaultBrowserIfNeeded(packageName); 18301 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 18302 removedAppId = mSettings.removePackageLPw(packageName); 18303 if (outInfo != null) { 18304 outInfo.removedAppId = removedAppId; 18305 } 18306 mPermissionManager.updatePermissions( 18307 deletedPs.name, null, false, mPackages.values(), mPermissionCallback); 18308 if (deletedPs.sharedUser != null) { 18309 // Remove permissions associated with package. Since runtime 18310 // permissions are per user we have to kill the removed package 18311 // or packages running under the shared user of the removed 18312 // package if revoking the permissions requested only by the removed 18313 // package is successful and this causes a change in gids. 18314 for (int userId : UserManagerService.getInstance().getUserIds()) { 18315 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 18316 userId); 18317 if (userIdToKill == UserHandle.USER_ALL 18318 || userIdToKill >= UserHandle.USER_SYSTEM) { 18319 // If gids changed for this user, kill all affected packages. 18320 mHandler.post(new Runnable() { 18321 @Override 18322 public void run() { 18323 // This has to happen with no lock held. 18324 killApplication(deletedPs.name, deletedPs.appId, 18325 KILL_APP_REASON_GIDS_CHANGED); 18326 } 18327 }); 18328 break; 18329 } 18330 } 18331 } 18332 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 18333 } 18334 // make sure to preserve per-user disabled state if this removal was just 18335 // a downgrade of a system app to the factory package 18336 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 18337 if (DEBUG_REMOVE) { 18338 Slog.d(TAG, "Propagating install state across downgrade"); 18339 } 18340 for (int userId : allUserHandles) { 18341 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18342 if (DEBUG_REMOVE) { 18343 Slog.d(TAG, " user " + userId + " => " + installed); 18344 } 18345 if (installed != ps.getInstalled(userId)) { 18346 installedStateChanged = true; 18347 } 18348 ps.setInstalled(installed, userId); 18349 } 18350 } 18351 } 18352 // can downgrade to reader 18353 if (writeSettings) { 18354 // Save settings now 18355 mSettings.writeLPr(); 18356 } 18357 if (installedStateChanged) { 18358 mSettings.writeKernelMappingLPr(ps); 18359 } 18360 } 18361 if (removedAppId != -1) { 18362 // A user ID was deleted here. Go through all users and remove it 18363 // from KeyStore. 18364 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 18365 } 18366 } 18367 18368 static boolean locationIsPrivileged(String path) { 18369 try { 18370 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 18371 final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 18372 final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app"); 18373 final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 18374 return path.startsWith(privilegedAppDir.getCanonicalPath()) 18375 || path.startsWith(privilegedVendorAppDir.getCanonicalPath()) 18376 || path.startsWith(privilegedOdmAppDir.getCanonicalPath()) 18377 || path.startsWith(privilegedProductAppDir.getCanonicalPath()); 18378 } catch (IOException e) { 18379 Slog.e(TAG, "Unable to access code path " + path); 18380 } 18381 return false; 18382 } 18383 18384 static boolean locationIsOem(String path) { 18385 try { 18386 return path.startsWith(Environment.getOemDirectory().getCanonicalPath()); 18387 } catch (IOException e) { 18388 Slog.e(TAG, "Unable to access code path " + path); 18389 } 18390 return false; 18391 } 18392 18393 static boolean locationIsVendor(String path) { 18394 try { 18395 return path.startsWith(Environment.getVendorDirectory().getCanonicalPath()) 18396 || path.startsWith(Environment.getOdmDirectory().getCanonicalPath()); 18397 } catch (IOException e) { 18398 Slog.e(TAG, "Unable to access code path " + path); 18399 } 18400 return false; 18401 } 18402 18403 static boolean locationIsProduct(String path) { 18404 try { 18405 return path.startsWith(Environment.getProductDirectory().getCanonicalPath()); 18406 } catch (IOException e) { 18407 Slog.e(TAG, "Unable to access code path " + path); 18408 } 18409 return false; 18410 } 18411 18412 /* 18413 * Tries to delete system package. 18414 */ 18415 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 18416 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 18417 boolean writeSettings) { 18418 if (deletedPs.parentPackageName != null) { 18419 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 18420 return false; 18421 } 18422 18423 final boolean applyUserRestrictions 18424 = (allUserHandles != null) && (outInfo.origUsers != null); 18425 final PackageSetting disabledPs; 18426 // Confirm if the system package has been updated 18427 // An updated system app can be deleted. This will also have to restore 18428 // the system pkg from system partition 18429 // reader 18430 synchronized (mPackages) { 18431 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 18432 } 18433 18434 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 18435 + " disabledPs=" + disabledPs); 18436 18437 if (disabledPs == null) { 18438 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 18439 return false; 18440 } else if (DEBUG_REMOVE) { 18441 Slog.d(TAG, "Deleting system pkg from data partition"); 18442 } 18443 18444 if (DEBUG_REMOVE) { 18445 if (applyUserRestrictions) { 18446 Slog.d(TAG, "Remembering install states:"); 18447 for (int userId : allUserHandles) { 18448 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 18449 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 18450 } 18451 } 18452 } 18453 18454 // Delete the updated package 18455 outInfo.isRemovedPackageSystemUpdate = true; 18456 if (outInfo.removedChildPackages != null) { 18457 final int childCount = (deletedPs.childPackageNames != null) 18458 ? deletedPs.childPackageNames.size() : 0; 18459 for (int i = 0; i < childCount; i++) { 18460 String childPackageName = deletedPs.childPackageNames.get(i); 18461 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 18462 .contains(childPackageName)) { 18463 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18464 childPackageName); 18465 if (childInfo != null) { 18466 childInfo.isRemovedPackageSystemUpdate = true; 18467 } 18468 } 18469 } 18470 } 18471 18472 if (disabledPs.versionCode < deletedPs.versionCode) { 18473 // Delete data for downgrades 18474 flags &= ~PackageManager.DELETE_KEEP_DATA; 18475 } else { 18476 // Preserve data by setting flag 18477 flags |= PackageManager.DELETE_KEEP_DATA; 18478 } 18479 18480 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 18481 outInfo, writeSettings, disabledPs.pkg); 18482 if (!ret) { 18483 return false; 18484 } 18485 18486 // writer 18487 synchronized (mPackages) { 18488 // NOTE: The system package always needs to be enabled; even if it's for 18489 // a compressed stub. If we don't, installing the system package fails 18490 // during scan [scanning checks the disabled packages]. We will reverse 18491 // this later, after we've "installed" the stub. 18492 // Reinstate the old system package 18493 enableSystemPackageLPw(disabledPs.pkg); 18494 // Remove any native libraries from the upgraded package. 18495 removeNativeBinariesLI(deletedPs); 18496 } 18497 18498 // Install the system package 18499 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18500 try { 18501 installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles, 18502 outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings); 18503 } catch (PackageManagerException e) { 18504 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18505 + e.getMessage()); 18506 return false; 18507 } finally { 18508 if (disabledPs.pkg.isStub) { 18509 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/); 18510 } 18511 } 18512 return true; 18513 } 18514 18515 /** 18516 * Installs a package that's already on the system partition. 18517 */ 18518 private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString, 18519 boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 18520 @Nullable PermissionsState origPermissionState, boolean writeSettings) 18521 throws PackageManagerException { 18522 @ParseFlags int parseFlags = 18523 mDefParseFlags 18524 | PackageParser.PARSE_MUST_BE_APK 18525 | PackageParser.PARSE_IS_SYSTEM_DIR; 18526 @ScanFlags int scanFlags = SCAN_AS_SYSTEM; 18527 if (isPrivileged || locationIsPrivileged(codePathString)) { 18528 scanFlags |= SCAN_AS_PRIVILEGED; 18529 } 18530 if (locationIsOem(codePathString)) { 18531 scanFlags |= SCAN_AS_OEM; 18532 } 18533 if (locationIsVendor(codePathString)) { 18534 scanFlags |= SCAN_AS_VENDOR; 18535 } 18536 if (locationIsProduct(codePathString)) { 18537 scanFlags |= SCAN_AS_PRODUCT; 18538 } 18539 18540 final File codePath = new File(codePathString); 18541 final PackageParser.Package pkg = 18542 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null); 18543 18544 try { 18545 // update shared libraries for the newly re-installed system package 18546 updateSharedLibrariesLPr(pkg, null); 18547 } catch (PackageManagerException e) { 18548 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18549 } 18550 18551 prepareAppDataAfterInstallLIF(pkg); 18552 18553 // writer 18554 synchronized (mPackages) { 18555 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 18556 18557 // Propagate the permissions state as we do not want to drop on the floor 18558 // runtime permissions. The update permissions method below will take 18559 // care of removing obsolete permissions and grant install permissions. 18560 if (origPermissionState != null) { 18561 ps.getPermissionsState().copyFrom(origPermissionState); 18562 } 18563 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 18564 mPermissionCallback); 18565 18566 final boolean applyUserRestrictions 18567 = (allUserHandles != null) && (origUserHandles != null); 18568 if (applyUserRestrictions) { 18569 boolean installedStateChanged = false; 18570 if (DEBUG_REMOVE) { 18571 Slog.d(TAG, "Propagating install state across reinstall"); 18572 } 18573 for (int userId : allUserHandles) { 18574 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 18575 if (DEBUG_REMOVE) { 18576 Slog.d(TAG, " user " + userId + " => " + installed); 18577 } 18578 if (installed != ps.getInstalled(userId)) { 18579 installedStateChanged = true; 18580 } 18581 ps.setInstalled(installed, userId); 18582 18583 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18584 } 18585 // Regardless of writeSettings we need to ensure that this restriction 18586 // state propagation is persisted 18587 mSettings.writeAllUsersPackageRestrictionsLPr(); 18588 if (installedStateChanged) { 18589 mSettings.writeKernelMappingLPr(ps); 18590 } 18591 } 18592 // can downgrade to reader here 18593 if (writeSettings) { 18594 mSettings.writeLPr(); 18595 } 18596 } 18597 return pkg; 18598 } 18599 18600 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18601 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18602 PackageRemovedInfo outInfo, boolean writeSettings, 18603 PackageParser.Package replacingPackage) { 18604 synchronized (mPackages) { 18605 if (outInfo != null) { 18606 outInfo.uid = ps.appId; 18607 } 18608 18609 if (outInfo != null && outInfo.removedChildPackages != null) { 18610 final int childCount = (ps.childPackageNames != null) 18611 ? ps.childPackageNames.size() : 0; 18612 for (int i = 0; i < childCount; i++) { 18613 String childPackageName = ps.childPackageNames.get(i); 18614 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18615 if (childPs == null) { 18616 return false; 18617 } 18618 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18619 childPackageName); 18620 if (childInfo != null) { 18621 childInfo.uid = childPs.appId; 18622 } 18623 } 18624 } 18625 } 18626 18627 // Delete package data from internal structures and also remove data if flag is set 18628 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18629 18630 // Delete the child packages data 18631 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18632 for (int i = 0; i < childCount; i++) { 18633 PackageSetting childPs; 18634 synchronized (mPackages) { 18635 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18636 } 18637 if (childPs != null) { 18638 PackageRemovedInfo childOutInfo = (outInfo != null 18639 && outInfo.removedChildPackages != null) 18640 ? outInfo.removedChildPackages.get(childPs.name) : null; 18641 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18642 && (replacingPackage != null 18643 && !replacingPackage.hasChildPackage(childPs.name)) 18644 ? flags & ~DELETE_KEEP_DATA : flags; 18645 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18646 deleteFlags, writeSettings); 18647 } 18648 } 18649 18650 // Delete application code and resources only for parent packages 18651 if (ps.parentPackageName == null) { 18652 if (deleteCodeAndResources && (outInfo != null)) { 18653 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18654 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18655 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18656 } 18657 } 18658 18659 return true; 18660 } 18661 18662 @Override 18663 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18664 int userId) { 18665 mContext.enforceCallingOrSelfPermission( 18666 android.Manifest.permission.DELETE_PACKAGES, null); 18667 synchronized (mPackages) { 18668 // Cannot block uninstall of static shared libs as they are 18669 // considered a part of the using app (emulating static linking). 18670 // Also static libs are installed always on internal storage. 18671 PackageParser.Package pkg = mPackages.get(packageName); 18672 if (pkg != null && pkg.staticSharedLibName != null) { 18673 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18674 + " providing static shared library: " + pkg.staticSharedLibName); 18675 return false; 18676 } 18677 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 18678 mSettings.writePackageRestrictionsLPr(userId); 18679 } 18680 return true; 18681 } 18682 18683 @Override 18684 public boolean getBlockUninstallForUser(String packageName, int userId) { 18685 synchronized (mPackages) { 18686 final PackageSetting ps = mSettings.mPackages.get(packageName); 18687 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 18688 return false; 18689 } 18690 return mSettings.getBlockUninstallLPr(userId, packageName); 18691 } 18692 } 18693 18694 @Override 18695 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18696 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 18697 synchronized (mPackages) { 18698 PackageSetting ps = mSettings.mPackages.get(packageName); 18699 if (ps == null) { 18700 Log.w(TAG, "Package doesn't exist: " + packageName); 18701 return false; 18702 } 18703 if (systemUserApp) { 18704 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18705 } else { 18706 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18707 } 18708 mSettings.writeLPr(); 18709 } 18710 return true; 18711 } 18712 18713 /* 18714 * This method handles package deletion in general 18715 */ 18716 private boolean deletePackageLIF(String packageName, UserHandle user, 18717 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18718 PackageRemovedInfo outInfo, boolean writeSettings, 18719 PackageParser.Package replacingPackage) { 18720 if (packageName == null) { 18721 Slog.w(TAG, "Attempt to delete null packageName."); 18722 return false; 18723 } 18724 18725 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18726 18727 PackageSetting ps; 18728 synchronized (mPackages) { 18729 ps = mSettings.mPackages.get(packageName); 18730 if (ps == null) { 18731 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18732 return false; 18733 } 18734 18735 if (ps.parentPackageName != null && (!isSystemApp(ps) 18736 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18737 if (DEBUG_REMOVE) { 18738 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18739 + ((user == null) ? UserHandle.USER_ALL : user)); 18740 } 18741 final int removedUserId = (user != null) ? user.getIdentifier() 18742 : UserHandle.USER_ALL; 18743 18744 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18745 return false; 18746 } 18747 markPackageUninstalledForUserLPw(ps, user); 18748 scheduleWritePackageRestrictionsLocked(user); 18749 return true; 18750 } 18751 } 18752 18753 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 18754 if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) { 18755 onSuspendingPackageRemoved(packageName, userId); 18756 } 18757 18758 18759 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18760 && user.getIdentifier() != UserHandle.USER_ALL)) { 18761 // The caller is asking that the package only be deleted for a single 18762 // user. To do this, we just mark its uninstalled state and delete 18763 // its data. If this is a system app, we only allow this to happen if 18764 // they have set the special DELETE_SYSTEM_APP which requests different 18765 // semantics than normal for uninstalling system apps. 18766 markPackageUninstalledForUserLPw(ps, user); 18767 18768 if (!isSystemApp(ps)) { 18769 // Do not uninstall the APK if an app should be cached 18770 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18771 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18772 // Other user still have this package installed, so all 18773 // we need to do is clear this user's data and save that 18774 // it is uninstalled. 18775 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18776 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18777 return false; 18778 } 18779 scheduleWritePackageRestrictionsLocked(user); 18780 return true; 18781 } else { 18782 // We need to set it back to 'installed' so the uninstall 18783 // broadcasts will be sent correctly. 18784 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18785 ps.setInstalled(true, user.getIdentifier()); 18786 mSettings.writeKernelMappingLPr(ps); 18787 } 18788 } else { 18789 // This is a system app, so we assume that the 18790 // other users still have this package installed, so all 18791 // we need to do is clear this user's data and save that 18792 // it is uninstalled. 18793 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18794 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18795 return false; 18796 } 18797 scheduleWritePackageRestrictionsLocked(user); 18798 return true; 18799 } 18800 } 18801 18802 // If we are deleting a composite package for all users, keep track 18803 // of result for each child. 18804 if (ps.childPackageNames != null && outInfo != null) { 18805 synchronized (mPackages) { 18806 final int childCount = ps.childPackageNames.size(); 18807 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18808 for (int i = 0; i < childCount; i++) { 18809 String childPackageName = ps.childPackageNames.get(i); 18810 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18811 childInfo.removedPackage = childPackageName; 18812 childInfo.installerPackageName = ps.installerPackageName; 18813 outInfo.removedChildPackages.put(childPackageName, childInfo); 18814 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18815 if (childPs != null) { 18816 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18817 } 18818 } 18819 } 18820 } 18821 18822 boolean ret = false; 18823 if (isSystemApp(ps)) { 18824 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18825 // When an updated system application is deleted we delete the existing resources 18826 // as well and fall back to existing code in system partition 18827 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18828 } else { 18829 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18830 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18831 outInfo, writeSettings, replacingPackage); 18832 } 18833 18834 // Take a note whether we deleted the package for all users 18835 if (outInfo != null) { 18836 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18837 if (outInfo.removedChildPackages != null) { 18838 synchronized (mPackages) { 18839 final int childCount = outInfo.removedChildPackages.size(); 18840 for (int i = 0; i < childCount; i++) { 18841 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18842 if (childInfo != null) { 18843 childInfo.removedForAllUsers = mPackages.get( 18844 childInfo.removedPackage) == null; 18845 } 18846 } 18847 } 18848 } 18849 // If we uninstalled an update to a system app there may be some 18850 // child packages that appeared as they are declared in the system 18851 // app but were not declared in the update. 18852 if (isSystemApp(ps)) { 18853 synchronized (mPackages) { 18854 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18855 final int childCount = (updatedPs.childPackageNames != null) 18856 ? updatedPs.childPackageNames.size() : 0; 18857 for (int i = 0; i < childCount; i++) { 18858 String childPackageName = updatedPs.childPackageNames.get(i); 18859 if (outInfo.removedChildPackages == null 18860 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18861 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18862 if (childPs == null) { 18863 continue; 18864 } 18865 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18866 installRes.name = childPackageName; 18867 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18868 installRes.pkg = mPackages.get(childPackageName); 18869 installRes.uid = childPs.pkg.applicationInfo.uid; 18870 if (outInfo.appearedChildPackages == null) { 18871 outInfo.appearedChildPackages = new ArrayMap<>(); 18872 } 18873 outInfo.appearedChildPackages.put(childPackageName, installRes); 18874 } 18875 } 18876 } 18877 } 18878 } 18879 18880 return ret; 18881 } 18882 18883 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18884 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18885 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18886 for (int nextUserId : userIds) { 18887 if (DEBUG_REMOVE) { 18888 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18889 } 18890 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18891 false /*installed*/, 18892 true /*stopped*/, 18893 true /*notLaunched*/, 18894 false /*hidden*/, 18895 false /*suspended*/, 18896 null, /*suspendingPackage*/ 18897 null, /*dialogMessage*/ 18898 null, /*suspendedAppExtras*/ 18899 null, /*suspendedLauncherExtras*/ 18900 false /*instantApp*/, 18901 false /*virtualPreload*/, 18902 null /*lastDisableAppCaller*/, 18903 null /*enabledComponents*/, 18904 null /*disabledComponents*/, 18905 ps.readUserState(nextUserId).domainVerificationStatus, 18906 0, PackageManager.INSTALL_REASON_UNKNOWN, 18907 null /*harmfulAppWarning*/); 18908 } 18909 mSettings.writeKernelMappingLPr(ps); 18910 } 18911 18912 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18913 PackageRemovedInfo outInfo) { 18914 final PackageParser.Package pkg; 18915 synchronized (mPackages) { 18916 pkg = mPackages.get(ps.name); 18917 } 18918 18919 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18920 : new int[] {userId}; 18921 for (int nextUserId : userIds) { 18922 if (DEBUG_REMOVE) { 18923 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18924 + nextUserId); 18925 } 18926 18927 destroyAppDataLIF(pkg, userId, 18928 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18929 destroyAppProfilesLIF(pkg, userId); 18930 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18931 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18932 schedulePackageCleaning(ps.name, nextUserId, false); 18933 synchronized (mPackages) { 18934 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18935 scheduleWritePackageRestrictionsLocked(nextUserId); 18936 } 18937 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18938 } 18939 } 18940 18941 if (outInfo != null) { 18942 outInfo.removedPackage = ps.name; 18943 outInfo.installerPackageName = ps.installerPackageName; 18944 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18945 outInfo.removedAppId = ps.appId; 18946 outInfo.removedUsers = userIds; 18947 outInfo.broadcastUsers = userIds; 18948 } 18949 18950 return true; 18951 } 18952 18953 private final class ClearStorageConnection implements ServiceConnection { 18954 IMediaContainerService mContainerService; 18955 18956 @Override 18957 public void onServiceConnected(ComponentName name, IBinder service) { 18958 synchronized (this) { 18959 mContainerService = IMediaContainerService.Stub 18960 .asInterface(Binder.allowBlocking(service)); 18961 notifyAll(); 18962 } 18963 } 18964 18965 @Override 18966 public void onServiceDisconnected(ComponentName name) { 18967 } 18968 } 18969 18970 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18971 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18972 18973 final boolean mounted; 18974 if (Environment.isExternalStorageEmulated()) { 18975 mounted = true; 18976 } else { 18977 final String status = Environment.getExternalStorageState(); 18978 18979 mounted = status.equals(Environment.MEDIA_MOUNTED) 18980 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18981 } 18982 18983 if (!mounted) { 18984 return; 18985 } 18986 18987 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18988 int[] users; 18989 if (userId == UserHandle.USER_ALL) { 18990 users = sUserManager.getUserIds(); 18991 } else { 18992 users = new int[] { userId }; 18993 } 18994 final ClearStorageConnection conn = new ClearStorageConnection(); 18995 if (mContext.bindServiceAsUser( 18996 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18997 try { 18998 for (int curUser : users) { 18999 long timeout = SystemClock.uptimeMillis() + 5000; 19000 synchronized (conn) { 19001 long now; 19002 while (conn.mContainerService == null && 19003 (now = SystemClock.uptimeMillis()) < timeout) { 19004 try { 19005 conn.wait(timeout - now); 19006 } catch (InterruptedException e) { 19007 } 19008 } 19009 } 19010 if (conn.mContainerService == null) { 19011 return; 19012 } 19013 19014 final UserEnvironment userEnv = new UserEnvironment(curUser); 19015 clearDirectory(conn.mContainerService, 19016 userEnv.buildExternalStorageAppCacheDirs(packageName)); 19017 if (allData) { 19018 clearDirectory(conn.mContainerService, 19019 userEnv.buildExternalStorageAppDataDirs(packageName)); 19020 clearDirectory(conn.mContainerService, 19021 userEnv.buildExternalStorageAppMediaDirs(packageName)); 19022 } 19023 } 19024 } finally { 19025 mContext.unbindService(conn); 19026 } 19027 } 19028 } 19029 19030 @Override 19031 public void clearApplicationProfileData(String packageName) { 19032 enforceSystemOrRoot("Only the system can clear all profile data"); 19033 19034 final PackageParser.Package pkg; 19035 synchronized (mPackages) { 19036 pkg = mPackages.get(packageName); 19037 } 19038 19039 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 19040 synchronized (mInstallLock) { 19041 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 19042 } 19043 } 19044 } 19045 19046 @Override 19047 public void clearApplicationUserData(final String packageName, 19048 final IPackageDataObserver observer, final int userId) { 19049 mContext.enforceCallingOrSelfPermission( 19050 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 19051 19052 final int callingUid = Binder.getCallingUid(); 19053 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19054 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 19055 19056 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19057 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 19058 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 19059 throw new SecurityException("Cannot clear data for a protected package: " 19060 + packageName); 19061 } 19062 // Queue up an async operation since the package deletion may take a little while. 19063 mHandler.post(new Runnable() { 19064 public void run() { 19065 mHandler.removeCallbacks(this); 19066 final boolean succeeded; 19067 if (!filterApp) { 19068 try (PackageFreezer freezer = freezePackage(packageName, 19069 "clearApplicationUserData")) { 19070 synchronized (mInstallLock) { 19071 succeeded = clearApplicationUserDataLIF(packageName, userId); 19072 } 19073 clearExternalStorageDataSync(packageName, userId, true); 19074 synchronized (mPackages) { 19075 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 19076 packageName, userId); 19077 } 19078 } 19079 if (succeeded) { 19080 // invoke DeviceStorageMonitor's update method to clear any notifications 19081 DeviceStorageMonitorInternal dsm = LocalServices 19082 .getService(DeviceStorageMonitorInternal.class); 19083 if (dsm != null) { 19084 dsm.checkMemory(); 19085 } 19086 } 19087 } else { 19088 succeeded = false; 19089 } 19090 if (observer != null) { 19091 try { 19092 observer.onRemoveCompleted(packageName, succeeded); 19093 } catch (RemoteException e) { 19094 Log.i(TAG, "Observer no longer exists."); 19095 } 19096 } //end if observer 19097 } //end run 19098 }); 19099 } 19100 19101 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 19102 if (packageName == null) { 19103 Slog.w(TAG, "Attempt to delete null packageName."); 19104 return false; 19105 } 19106 19107 // Try finding details about the requested package 19108 PackageParser.Package pkg; 19109 synchronized (mPackages) { 19110 pkg = mPackages.get(packageName); 19111 if (pkg == null) { 19112 final PackageSetting ps = mSettings.mPackages.get(packageName); 19113 if (ps != null) { 19114 pkg = ps.pkg; 19115 } 19116 } 19117 19118 if (pkg == null) { 19119 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 19120 return false; 19121 } 19122 19123 PackageSetting ps = (PackageSetting) pkg.mExtras; 19124 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 19125 } 19126 19127 clearAppDataLIF(pkg, userId, 19128 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19129 19130 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19131 removeKeystoreDataIfNeeded(userId, appId); 19132 19133 UserManagerInternal umInternal = getUserManagerInternal(); 19134 final int flags; 19135 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 19136 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19137 } else if (umInternal.isUserRunning(userId)) { 19138 flags = StorageManager.FLAG_STORAGE_DE; 19139 } else { 19140 flags = 0; 19141 } 19142 prepareAppDataContentsLIF(pkg, userId, flags); 19143 19144 return true; 19145 } 19146 19147 /** 19148 * Reverts user permission state changes (permissions and flags) in 19149 * all packages for a given user. 19150 * 19151 * @param userId The device user for which to do a reset. 19152 */ 19153 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 19154 final int packageCount = mPackages.size(); 19155 for (int i = 0; i < packageCount; i++) { 19156 PackageParser.Package pkg = mPackages.valueAt(i); 19157 PackageSetting ps = (PackageSetting) pkg.mExtras; 19158 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 19159 } 19160 } 19161 19162 private void resetNetworkPolicies(int userId) { 19163 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 19164 } 19165 19166 /** 19167 * Reverts user permission state changes (permissions and flags). 19168 * 19169 * @param ps The package for which to reset. 19170 * @param userId The device user for which to do a reset. 19171 */ 19172 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 19173 final PackageSetting ps, final int userId) { 19174 if (ps.pkg == null) { 19175 return; 19176 } 19177 19178 // These are flags that can change base on user actions. 19179 final int userSettableMask = FLAG_PERMISSION_USER_SET 19180 | FLAG_PERMISSION_USER_FIXED 19181 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 19182 | FLAG_PERMISSION_REVIEW_REQUIRED; 19183 19184 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 19185 | FLAG_PERMISSION_POLICY_FIXED; 19186 19187 boolean writeInstallPermissions = false; 19188 boolean writeRuntimePermissions = false; 19189 19190 final int permissionCount = ps.pkg.requestedPermissions.size(); 19191 for (int i = 0; i < permissionCount; i++) { 19192 final String permName = ps.pkg.requestedPermissions.get(i); 19193 final BasePermission bp = 19194 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 19195 if (bp == null) { 19196 continue; 19197 } 19198 19199 // If shared user we just reset the state to which only this app contributed. 19200 if (ps.sharedUser != null) { 19201 boolean used = false; 19202 final int packageCount = ps.sharedUser.packages.size(); 19203 for (int j = 0; j < packageCount; j++) { 19204 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 19205 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 19206 && pkg.pkg.requestedPermissions.contains(permName)) { 19207 used = true; 19208 break; 19209 } 19210 } 19211 if (used) { 19212 continue; 19213 } 19214 } 19215 19216 final PermissionsState permissionsState = ps.getPermissionsState(); 19217 19218 final int oldFlags = permissionsState.getPermissionFlags(permName, userId); 19219 19220 // Always clear the user settable flags. 19221 final boolean hasInstallState = 19222 permissionsState.getInstallPermissionState(permName) != null; 19223 // If permission review is enabled and this is a legacy app, mark the 19224 // permission as requiring a review as this is the initial state. 19225 int flags = 0; 19226 if (mSettings.mPermissions.mPermissionReviewRequired 19227 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 19228 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 19229 } 19230 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 19231 if (hasInstallState) { 19232 writeInstallPermissions = true; 19233 } else { 19234 writeRuntimePermissions = true; 19235 } 19236 } 19237 19238 // Below is only runtime permission handling. 19239 if (!bp.isRuntime()) { 19240 continue; 19241 } 19242 19243 // Never clobber system or policy. 19244 if ((oldFlags & policyOrSystemFlags) != 0) { 19245 continue; 19246 } 19247 19248 // If this permission was granted by default, make sure it is. 19249 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 19250 if (permissionsState.grantRuntimePermission(bp, userId) 19251 != PERMISSION_OPERATION_FAILURE) { 19252 writeRuntimePermissions = true; 19253 } 19254 // If permission review is enabled the permissions for a legacy apps 19255 // are represented as constantly granted runtime ones, so don't revoke. 19256 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 19257 // Otherwise, reset the permission. 19258 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 19259 switch (revokeResult) { 19260 case PERMISSION_OPERATION_SUCCESS: 19261 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 19262 writeRuntimePermissions = true; 19263 final int appId = ps.appId; 19264 mHandler.post(new Runnable() { 19265 @Override 19266 public void run() { 19267 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 19268 } 19269 }); 19270 } break; 19271 } 19272 } 19273 } 19274 19275 // Synchronously write as we are taking permissions away. 19276 if (writeRuntimePermissions) { 19277 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 19278 } 19279 19280 // Synchronously write as we are taking permissions away. 19281 if (writeInstallPermissions) { 19282 mSettings.writeLPr(); 19283 } 19284 } 19285 19286 /** 19287 * Remove entries from the keystore daemon. Will only remove it if the 19288 * {@code appId} is valid. 19289 */ 19290 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 19291 if (appId < 0) { 19292 return; 19293 } 19294 19295 final KeyStore keyStore = KeyStore.getInstance(); 19296 if (keyStore != null) { 19297 if (userId == UserHandle.USER_ALL) { 19298 for (final int individual : sUserManager.getUserIds()) { 19299 keyStore.clearUid(UserHandle.getUid(individual, appId)); 19300 } 19301 } else { 19302 keyStore.clearUid(UserHandle.getUid(userId, appId)); 19303 } 19304 } else { 19305 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 19306 } 19307 } 19308 19309 @Override 19310 public void deleteApplicationCacheFiles(final String packageName, 19311 final IPackageDataObserver observer) { 19312 final int userId = UserHandle.getCallingUserId(); 19313 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 19314 } 19315 19316 @Override 19317 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 19318 final IPackageDataObserver observer) { 19319 final int callingUid = Binder.getCallingUid(); 19320 if (mContext.checkCallingOrSelfPermission( 19321 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES) 19322 != PackageManager.PERMISSION_GRANTED) { 19323 // If the caller has the old delete cache permission, silently ignore. Else throw. 19324 if (mContext.checkCallingOrSelfPermission( 19325 android.Manifest.permission.DELETE_CACHE_FILES) 19326 == PackageManager.PERMISSION_GRANTED) { 19327 Slog.w(TAG, "Calling uid " + callingUid + " does not have " + 19328 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES + 19329 ", silently ignoring"); 19330 return; 19331 } 19332 mContext.enforceCallingOrSelfPermission( 19333 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null); 19334 } 19335 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19336 /* requireFullPermission= */ true, /* checkShell= */ false, 19337 "delete application cache files"); 19338 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 19339 android.Manifest.permission.ACCESS_INSTANT_APPS); 19340 19341 final PackageParser.Package pkg; 19342 synchronized (mPackages) { 19343 pkg = mPackages.get(packageName); 19344 } 19345 19346 // Queue up an async operation since the package deletion may take a little while. 19347 mHandler.post(new Runnable() { 19348 public void run() { 19349 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 19350 boolean doClearData = true; 19351 if (ps != null) { 19352 final boolean targetIsInstantApp = 19353 ps.getInstantApp(UserHandle.getUserId(callingUid)); 19354 doClearData = !targetIsInstantApp 19355 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 19356 } 19357 if (doClearData) { 19358 synchronized (mInstallLock) { 19359 final int flags = StorageManager.FLAG_STORAGE_DE 19360 | StorageManager.FLAG_STORAGE_CE; 19361 // We're only clearing cache files, so we don't care if the 19362 // app is unfrozen and still able to run 19363 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 19364 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19365 } 19366 clearExternalStorageDataSync(packageName, userId, false); 19367 } 19368 if (observer != null) { 19369 try { 19370 observer.onRemoveCompleted(packageName, true); 19371 } catch (RemoteException e) { 19372 Log.i(TAG, "Observer no longer exists."); 19373 } 19374 } 19375 } 19376 }); 19377 } 19378 19379 @Override 19380 public void getPackageSizeInfo(final String packageName, int userHandle, 19381 final IPackageStatsObserver observer) { 19382 throw new UnsupportedOperationException( 19383 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 19384 } 19385 19386 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 19387 final PackageSetting ps; 19388 synchronized (mPackages) { 19389 ps = mSettings.mPackages.get(packageName); 19390 if (ps == null) { 19391 Slog.w(TAG, "Failed to find settings for " + packageName); 19392 return false; 19393 } 19394 } 19395 19396 final String[] packageNames = { packageName }; 19397 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 19398 final String[] codePaths = { ps.codePathString }; 19399 19400 try { 19401 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 19402 ps.appId, ceDataInodes, codePaths, stats); 19403 19404 // For now, ignore code size of packages on system partition 19405 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 19406 stats.codeSize = 0; 19407 } 19408 19409 // External clients expect these to be tracked separately 19410 stats.dataSize -= stats.cacheSize; 19411 19412 } catch (InstallerException e) { 19413 Slog.w(TAG, String.valueOf(e)); 19414 return false; 19415 } 19416 19417 return true; 19418 } 19419 19420 private int getUidTargetSdkVersionLockedLPr(int uid) { 19421 Object obj = mSettings.getUserIdLPr(uid); 19422 if (obj instanceof SharedUserSetting) { 19423 final SharedUserSetting sus = (SharedUserSetting) obj; 19424 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 19425 final Iterator<PackageSetting> it = sus.packages.iterator(); 19426 while (it.hasNext()) { 19427 final PackageSetting ps = it.next(); 19428 if (ps.pkg != null) { 19429 int v = ps.pkg.applicationInfo.targetSdkVersion; 19430 if (v < vers) vers = v; 19431 } 19432 } 19433 return vers; 19434 } else if (obj instanceof PackageSetting) { 19435 final PackageSetting ps = (PackageSetting) obj; 19436 if (ps.pkg != null) { 19437 return ps.pkg.applicationInfo.targetSdkVersion; 19438 } 19439 } 19440 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19441 } 19442 19443 private int getPackageTargetSdkVersionLockedLPr(String packageName) { 19444 final PackageParser.Package p = mPackages.get(packageName); 19445 if (p != null) { 19446 return p.applicationInfo.targetSdkVersion; 19447 } 19448 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19449 } 19450 19451 @Override 19452 public void addPreferredActivity(IntentFilter filter, int match, 19453 ComponentName[] set, ComponentName activity, int userId) { 19454 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19455 "Adding preferred"); 19456 } 19457 19458 private void addPreferredActivityInternal(IntentFilter filter, int match, 19459 ComponentName[] set, ComponentName activity, boolean always, int userId, 19460 String opname) { 19461 // writer 19462 int callingUid = Binder.getCallingUid(); 19463 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19464 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 19465 if (filter.countActions() == 0) { 19466 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19467 return; 19468 } 19469 synchronized (mPackages) { 19470 if (mContext.checkCallingOrSelfPermission( 19471 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19472 != PackageManager.PERMISSION_GRANTED) { 19473 if (getUidTargetSdkVersionLockedLPr(callingUid) 19474 < Build.VERSION_CODES.FROYO) { 19475 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 19476 + callingUid); 19477 return; 19478 } 19479 mContext.enforceCallingOrSelfPermission( 19480 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19481 } 19482 19483 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 19484 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 19485 + userId + ":"); 19486 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19487 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 19488 scheduleWritePackageRestrictionsLocked(userId); 19489 postPreferredActivityChangedBroadcast(userId); 19490 } 19491 } 19492 19493 private void postPreferredActivityChangedBroadcast(int userId) { 19494 mHandler.post(() -> { 19495 final IActivityManager am = ActivityManager.getService(); 19496 if (am == null) { 19497 return; 19498 } 19499 19500 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 19501 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 19502 try { 19503 am.broadcastIntent(null, intent, null, null, 19504 0, null, null, null, android.app.AppOpsManager.OP_NONE, 19505 null, false, false, userId); 19506 } catch (RemoteException e) { 19507 } 19508 }); 19509 } 19510 19511 @Override 19512 public void replacePreferredActivity(IntentFilter filter, int match, 19513 ComponentName[] set, ComponentName activity, int userId) { 19514 if (filter.countActions() != 1) { 19515 throw new IllegalArgumentException( 19516 "replacePreferredActivity expects filter to have only 1 action."); 19517 } 19518 if (filter.countDataAuthorities() != 0 19519 || filter.countDataPaths() != 0 19520 || filter.countDataSchemes() > 1 19521 || filter.countDataTypes() != 0) { 19522 throw new IllegalArgumentException( 19523 "replacePreferredActivity expects filter to have no data authorities, " + 19524 "paths, or types; and at most one scheme."); 19525 } 19526 19527 final int callingUid = Binder.getCallingUid(); 19528 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19529 true /* requireFullPermission */, false /* checkShell */, 19530 "replace preferred activity"); 19531 synchronized (mPackages) { 19532 if (mContext.checkCallingOrSelfPermission( 19533 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19534 != PackageManager.PERMISSION_GRANTED) { 19535 if (getUidTargetSdkVersionLockedLPr(callingUid) 19536 < Build.VERSION_CODES.FROYO) { 19537 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 19538 + Binder.getCallingUid()); 19539 return; 19540 } 19541 mContext.enforceCallingOrSelfPermission( 19542 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19543 } 19544 19545 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19546 if (pir != null) { 19547 // Get all of the existing entries that exactly match this filter. 19548 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 19549 if (existing != null && existing.size() == 1) { 19550 PreferredActivity cur = existing.get(0); 19551 if (DEBUG_PREFERRED) { 19552 Slog.i(TAG, "Checking replace of preferred:"); 19553 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19554 if (!cur.mPref.mAlways) { 19555 Slog.i(TAG, " -- CUR; not mAlways!"); 19556 } else { 19557 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19558 Slog.i(TAG, " -- CUR: mSet=" 19559 + Arrays.toString(cur.mPref.mSetComponents)); 19560 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19561 Slog.i(TAG, " -- NEW: mMatch=" 19562 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19563 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19564 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19565 } 19566 } 19567 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19568 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19569 && cur.mPref.sameSet(set)) { 19570 // Setting the preferred activity to what it happens to be already 19571 if (DEBUG_PREFERRED) { 19572 Slog.i(TAG, "Replacing with same preferred activity " 19573 + cur.mPref.mShortComponent + " for user " 19574 + userId + ":"); 19575 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19576 } 19577 return; 19578 } 19579 } 19580 19581 if (existing != null) { 19582 if (DEBUG_PREFERRED) { 19583 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19584 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19585 } 19586 for (int i = 0; i < existing.size(); i++) { 19587 PreferredActivity pa = existing.get(i); 19588 if (DEBUG_PREFERRED) { 19589 Slog.i(TAG, "Removing existing preferred activity " 19590 + pa.mPref.mComponent + ":"); 19591 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19592 } 19593 pir.removeFilter(pa); 19594 } 19595 } 19596 } 19597 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19598 "Replacing preferred"); 19599 } 19600 } 19601 19602 @Override 19603 public void clearPackagePreferredActivities(String packageName) { 19604 final int callingUid = Binder.getCallingUid(); 19605 if (getInstantAppPackageName(callingUid) != null) { 19606 return; 19607 } 19608 // writer 19609 synchronized (mPackages) { 19610 PackageParser.Package pkg = mPackages.get(packageName); 19611 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 19612 if (mContext.checkCallingOrSelfPermission( 19613 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19614 != PackageManager.PERMISSION_GRANTED) { 19615 if (getUidTargetSdkVersionLockedLPr(callingUid) 19616 < Build.VERSION_CODES.FROYO) { 19617 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19618 + callingUid); 19619 return; 19620 } 19621 mContext.enforceCallingOrSelfPermission( 19622 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19623 } 19624 } 19625 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19626 if (ps != null 19627 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 19628 return; 19629 } 19630 int user = UserHandle.getCallingUserId(); 19631 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19632 scheduleWritePackageRestrictionsLocked(user); 19633 } 19634 } 19635 } 19636 19637 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19638 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19639 ArrayList<PreferredActivity> removed = null; 19640 boolean changed = false; 19641 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19642 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19643 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19644 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19645 continue; 19646 } 19647 Iterator<PreferredActivity> it = pir.filterIterator(); 19648 while (it.hasNext()) { 19649 PreferredActivity pa = it.next(); 19650 // Mark entry for removal only if it matches the package name 19651 // and the entry is of type "always". 19652 if (packageName == null || 19653 (pa.mPref.mComponent.getPackageName().equals(packageName) 19654 && pa.mPref.mAlways)) { 19655 if (removed == null) { 19656 removed = new ArrayList<PreferredActivity>(); 19657 } 19658 removed.add(pa); 19659 } 19660 } 19661 if (removed != null) { 19662 for (int j=0; j<removed.size(); j++) { 19663 PreferredActivity pa = removed.get(j); 19664 pir.removeFilter(pa); 19665 } 19666 changed = true; 19667 } 19668 } 19669 if (changed) { 19670 postPreferredActivityChangedBroadcast(userId); 19671 } 19672 return changed; 19673 } 19674 19675 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19676 private void clearIntentFilterVerificationsLPw(int userId) { 19677 final int packageCount = mPackages.size(); 19678 for (int i = 0; i < packageCount; i++) { 19679 PackageParser.Package pkg = mPackages.valueAt(i); 19680 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19681 } 19682 } 19683 19684 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19685 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19686 if (userId == UserHandle.USER_ALL) { 19687 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19688 sUserManager.getUserIds())) { 19689 for (int oneUserId : sUserManager.getUserIds()) { 19690 scheduleWritePackageRestrictionsLocked(oneUserId); 19691 } 19692 } 19693 } else { 19694 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19695 scheduleWritePackageRestrictionsLocked(userId); 19696 } 19697 } 19698 } 19699 19700 /** Clears state for all users, and touches intent filter verification policy */ 19701 void clearDefaultBrowserIfNeeded(String packageName) { 19702 for (int oneUserId : sUserManager.getUserIds()) { 19703 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19704 } 19705 } 19706 19707 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19708 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19709 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19710 if (packageName.equals(defaultBrowserPackageName)) { 19711 setDefaultBrowserPackageName(null, userId); 19712 } 19713 } 19714 } 19715 19716 @Override 19717 public void resetApplicationPreferences(int userId) { 19718 mContext.enforceCallingOrSelfPermission( 19719 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19720 final long identity = Binder.clearCallingIdentity(); 19721 // writer 19722 try { 19723 synchronized (mPackages) { 19724 clearPackagePreferredActivitiesLPw(null, userId); 19725 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19726 // TODO: We have to reset the default SMS and Phone. This requires 19727 // significant refactoring to keep all default apps in the package 19728 // manager (cleaner but more work) or have the services provide 19729 // callbacks to the package manager to request a default app reset. 19730 applyFactoryDefaultBrowserLPw(userId); 19731 clearIntentFilterVerificationsLPw(userId); 19732 primeDomainVerificationsLPw(userId); 19733 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19734 scheduleWritePackageRestrictionsLocked(userId); 19735 } 19736 resetNetworkPolicies(userId); 19737 } finally { 19738 Binder.restoreCallingIdentity(identity); 19739 } 19740 } 19741 19742 @Override 19743 public int getPreferredActivities(List<IntentFilter> outFilters, 19744 List<ComponentName> outActivities, String packageName) { 19745 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19746 return 0; 19747 } 19748 int num = 0; 19749 final int userId = UserHandle.getCallingUserId(); 19750 // reader 19751 synchronized (mPackages) { 19752 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19753 if (pir != null) { 19754 final Iterator<PreferredActivity> it = pir.filterIterator(); 19755 while (it.hasNext()) { 19756 final PreferredActivity pa = it.next(); 19757 if (packageName == null 19758 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19759 && pa.mPref.mAlways)) { 19760 if (outFilters != null) { 19761 outFilters.add(new IntentFilter(pa)); 19762 } 19763 if (outActivities != null) { 19764 outActivities.add(pa.mPref.mComponent); 19765 } 19766 } 19767 } 19768 } 19769 } 19770 19771 return num; 19772 } 19773 19774 @Override 19775 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19776 int userId) { 19777 int callingUid = Binder.getCallingUid(); 19778 if (callingUid != Process.SYSTEM_UID) { 19779 throw new SecurityException( 19780 "addPersistentPreferredActivity can only be run by the system"); 19781 } 19782 if (filter.countActions() == 0) { 19783 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19784 return; 19785 } 19786 synchronized (mPackages) { 19787 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19788 ":"); 19789 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19790 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19791 new PersistentPreferredActivity(filter, activity)); 19792 scheduleWritePackageRestrictionsLocked(userId); 19793 postPreferredActivityChangedBroadcast(userId); 19794 } 19795 } 19796 19797 @Override 19798 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19799 int callingUid = Binder.getCallingUid(); 19800 if (callingUid != Process.SYSTEM_UID) { 19801 throw new SecurityException( 19802 "clearPackagePersistentPreferredActivities can only be run by the system"); 19803 } 19804 ArrayList<PersistentPreferredActivity> removed = null; 19805 boolean changed = false; 19806 synchronized (mPackages) { 19807 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19808 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19809 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19810 .valueAt(i); 19811 if (userId != thisUserId) { 19812 continue; 19813 } 19814 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19815 while (it.hasNext()) { 19816 PersistentPreferredActivity ppa = it.next(); 19817 // Mark entry for removal only if it matches the package name. 19818 if (ppa.mComponent.getPackageName().equals(packageName)) { 19819 if (removed == null) { 19820 removed = new ArrayList<PersistentPreferredActivity>(); 19821 } 19822 removed.add(ppa); 19823 } 19824 } 19825 if (removed != null) { 19826 for (int j=0; j<removed.size(); j++) { 19827 PersistentPreferredActivity ppa = removed.get(j); 19828 ppir.removeFilter(ppa); 19829 } 19830 changed = true; 19831 } 19832 } 19833 19834 if (changed) { 19835 scheduleWritePackageRestrictionsLocked(userId); 19836 postPreferredActivityChangedBroadcast(userId); 19837 } 19838 } 19839 } 19840 19841 /** 19842 * Common machinery for picking apart a restored XML blob and passing 19843 * it to a caller-supplied functor to be applied to the running system. 19844 */ 19845 private void restoreFromXml(XmlPullParser parser, int userId, 19846 String expectedStartTag, BlobXmlRestorer functor) 19847 throws IOException, XmlPullParserException { 19848 int type; 19849 while ((type = parser.next()) != XmlPullParser.START_TAG 19850 && type != XmlPullParser.END_DOCUMENT) { 19851 } 19852 if (type != XmlPullParser.START_TAG) { 19853 // oops didn't find a start tag?! 19854 if (DEBUG_BACKUP) { 19855 Slog.e(TAG, "Didn't find start tag during restore"); 19856 } 19857 return; 19858 } 19859Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19860 // this is supposed to be TAG_PREFERRED_BACKUP 19861 if (!expectedStartTag.equals(parser.getName())) { 19862 if (DEBUG_BACKUP) { 19863 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19864 } 19865 return; 19866 } 19867 19868 // skip interfering stuff, then we're aligned with the backing implementation 19869 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19870Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19871 functor.apply(parser, userId); 19872 } 19873 19874 private interface BlobXmlRestorer { 19875 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19876 } 19877 19878 /** 19879 * Non-Binder method, support for the backup/restore mechanism: write the 19880 * full set of preferred activities in its canonical XML format. Returns the 19881 * XML output as a byte array, or null if there is none. 19882 */ 19883 @Override 19884 public byte[] getPreferredActivityBackup(int userId) { 19885 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19886 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19887 } 19888 19889 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19890 try { 19891 final XmlSerializer serializer = new FastXmlSerializer(); 19892 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19893 serializer.startDocument(null, true); 19894 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19895 19896 synchronized (mPackages) { 19897 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19898 } 19899 19900 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19901 serializer.endDocument(); 19902 serializer.flush(); 19903 } catch (Exception e) { 19904 if (DEBUG_BACKUP) { 19905 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19906 } 19907 return null; 19908 } 19909 19910 return dataStream.toByteArray(); 19911 } 19912 19913 @Override 19914 public void restorePreferredActivities(byte[] backup, int userId) { 19915 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19916 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19917 } 19918 19919 try { 19920 final XmlPullParser parser = Xml.newPullParser(); 19921 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19922 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19923 new BlobXmlRestorer() { 19924 @Override 19925 public void apply(XmlPullParser parser, int userId) 19926 throws XmlPullParserException, IOException { 19927 synchronized (mPackages) { 19928 mSettings.readPreferredActivitiesLPw(parser, userId); 19929 } 19930 } 19931 } ); 19932 } catch (Exception e) { 19933 if (DEBUG_BACKUP) { 19934 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19935 } 19936 } 19937 } 19938 19939 /** 19940 * Non-Binder method, support for the backup/restore mechanism: write the 19941 * default browser (etc) settings in its canonical XML format. Returns the default 19942 * browser XML representation as a byte array, or null if there is none. 19943 */ 19944 @Override 19945 public byte[] getDefaultAppsBackup(int userId) { 19946 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19947 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19948 } 19949 19950 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19951 try { 19952 final XmlSerializer serializer = new FastXmlSerializer(); 19953 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19954 serializer.startDocument(null, true); 19955 serializer.startTag(null, TAG_DEFAULT_APPS); 19956 19957 synchronized (mPackages) { 19958 mSettings.writeDefaultAppsLPr(serializer, userId); 19959 } 19960 19961 serializer.endTag(null, TAG_DEFAULT_APPS); 19962 serializer.endDocument(); 19963 serializer.flush(); 19964 } catch (Exception e) { 19965 if (DEBUG_BACKUP) { 19966 Slog.e(TAG, "Unable to write default apps for backup", e); 19967 } 19968 return null; 19969 } 19970 19971 return dataStream.toByteArray(); 19972 } 19973 19974 @Override 19975 public void restoreDefaultApps(byte[] backup, int userId) { 19976 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19977 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19978 } 19979 19980 try { 19981 final XmlPullParser parser = Xml.newPullParser(); 19982 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19983 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19984 new BlobXmlRestorer() { 19985 @Override 19986 public void apply(XmlPullParser parser, int userId) 19987 throws XmlPullParserException, IOException { 19988 synchronized (mPackages) { 19989 mSettings.readDefaultAppsLPw(parser, userId); 19990 } 19991 } 19992 } ); 19993 } catch (Exception e) { 19994 if (DEBUG_BACKUP) { 19995 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19996 } 19997 } 19998 } 19999 20000 @Override 20001 public byte[] getIntentFilterVerificationBackup(int userId) { 20002 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20003 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 20004 } 20005 20006 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20007 try { 20008 final XmlSerializer serializer = new FastXmlSerializer(); 20009 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20010 serializer.startDocument(null, true); 20011 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 20012 20013 synchronized (mPackages) { 20014 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 20015 } 20016 20017 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 20018 serializer.endDocument(); 20019 serializer.flush(); 20020 } catch (Exception e) { 20021 if (DEBUG_BACKUP) { 20022 Slog.e(TAG, "Unable to write default apps for backup", e); 20023 } 20024 return null; 20025 } 20026 20027 return dataStream.toByteArray(); 20028 } 20029 20030 @Override 20031 public void restoreIntentFilterVerification(byte[] backup, int userId) { 20032 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20033 throw new SecurityException("Only the system may call restorePreferredActivities()"); 20034 } 20035 20036 try { 20037 final XmlPullParser parser = Xml.newPullParser(); 20038 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20039 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 20040 new BlobXmlRestorer() { 20041 @Override 20042 public void apply(XmlPullParser parser, int userId) 20043 throws XmlPullParserException, IOException { 20044 synchronized (mPackages) { 20045 mSettings.readAllDomainVerificationsLPr(parser, userId); 20046 mSettings.writeLPr(); 20047 } 20048 } 20049 } ); 20050 } catch (Exception e) { 20051 if (DEBUG_BACKUP) { 20052 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 20053 } 20054 } 20055 } 20056 20057 @Override 20058 public byte[] getPermissionGrantBackup(int userId) { 20059 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20060 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 20061 } 20062 20063 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20064 try { 20065 final XmlSerializer serializer = new FastXmlSerializer(); 20066 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20067 serializer.startDocument(null, true); 20068 serializer.startTag(null, TAG_PERMISSION_BACKUP); 20069 20070 synchronized (mPackages) { 20071 serializeRuntimePermissionGrantsLPr(serializer, userId); 20072 } 20073 20074 serializer.endTag(null, TAG_PERMISSION_BACKUP); 20075 serializer.endDocument(); 20076 serializer.flush(); 20077 } catch (Exception e) { 20078 if (DEBUG_BACKUP) { 20079 Slog.e(TAG, "Unable to write default apps for backup", e); 20080 } 20081 return null; 20082 } 20083 20084 return dataStream.toByteArray(); 20085 } 20086 20087 @Override 20088 public void restorePermissionGrants(byte[] backup, int userId) { 20089 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20090 throw new SecurityException("Only the system may call restorePermissionGrants()"); 20091 } 20092 20093 try { 20094 final XmlPullParser parser = Xml.newPullParser(); 20095 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20096 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 20097 new BlobXmlRestorer() { 20098 @Override 20099 public void apply(XmlPullParser parser, int userId) 20100 throws XmlPullParserException, IOException { 20101 synchronized (mPackages) { 20102 processRestoredPermissionGrantsLPr(parser, userId); 20103 } 20104 } 20105 } ); 20106 } catch (Exception e) { 20107 if (DEBUG_BACKUP) { 20108 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 20109 } 20110 } 20111 } 20112 20113 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 20114 throws IOException { 20115 serializer.startTag(null, TAG_ALL_GRANTS); 20116 20117 final int N = mSettings.mPackages.size(); 20118 for (int i = 0; i < N; i++) { 20119 final PackageSetting ps = mSettings.mPackages.valueAt(i); 20120 boolean pkgGrantsKnown = false; 20121 20122 PermissionsState packagePerms = ps.getPermissionsState(); 20123 20124 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 20125 final int grantFlags = state.getFlags(); 20126 // only look at grants that are not system/policy fixed 20127 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 20128 final boolean isGranted = state.isGranted(); 20129 // And only back up the user-twiddled state bits 20130 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 20131 final String packageName = mSettings.mPackages.keyAt(i); 20132 if (!pkgGrantsKnown) { 20133 serializer.startTag(null, TAG_GRANT); 20134 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 20135 pkgGrantsKnown = true; 20136 } 20137 20138 final boolean userSet = 20139 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 20140 final boolean userFixed = 20141 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 20142 final boolean revoke = 20143 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 20144 20145 serializer.startTag(null, TAG_PERMISSION); 20146 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 20147 if (isGranted) { 20148 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 20149 } 20150 if (userSet) { 20151 serializer.attribute(null, ATTR_USER_SET, "true"); 20152 } 20153 if (userFixed) { 20154 serializer.attribute(null, ATTR_USER_FIXED, "true"); 20155 } 20156 if (revoke) { 20157 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 20158 } 20159 serializer.endTag(null, TAG_PERMISSION); 20160 } 20161 } 20162 } 20163 20164 if (pkgGrantsKnown) { 20165 serializer.endTag(null, TAG_GRANT); 20166 } 20167 } 20168 20169 serializer.endTag(null, TAG_ALL_GRANTS); 20170 } 20171 20172 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 20173 throws XmlPullParserException, IOException { 20174 String pkgName = null; 20175 int outerDepth = parser.getDepth(); 20176 int type; 20177 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 20178 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 20179 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 20180 continue; 20181 } 20182 20183 final String tagName = parser.getName(); 20184 if (tagName.equals(TAG_GRANT)) { 20185 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 20186 if (DEBUG_BACKUP) { 20187 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 20188 } 20189 } else if (tagName.equals(TAG_PERMISSION)) { 20190 20191 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 20192 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 20193 20194 int newFlagSet = 0; 20195 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 20196 newFlagSet |= FLAG_PERMISSION_USER_SET; 20197 } 20198 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 20199 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 20200 } 20201 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 20202 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 20203 } 20204 if (DEBUG_BACKUP) { 20205 Slog.v(TAG, " + Restoring grant:" 20206 + " pkg=" + pkgName 20207 + " perm=" + permName 20208 + " granted=" + isGranted 20209 + " bits=0x" + Integer.toHexString(newFlagSet)); 20210 } 20211 final PackageSetting ps = mSettings.mPackages.get(pkgName); 20212 if (ps != null) { 20213 // Already installed so we apply the grant immediately 20214 if (DEBUG_BACKUP) { 20215 Slog.v(TAG, " + already installed; applying"); 20216 } 20217 PermissionsState perms = ps.getPermissionsState(); 20218 BasePermission bp = 20219 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 20220 if (bp != null) { 20221 if (isGranted) { 20222 perms.grantRuntimePermission(bp, userId); 20223 } 20224 if (newFlagSet != 0) { 20225 perms.updatePermissionFlags( 20226 bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 20227 } 20228 } 20229 } else { 20230 // Need to wait for post-restore install to apply the grant 20231 if (DEBUG_BACKUP) { 20232 Slog.v(TAG, " - not yet installed; saving for later"); 20233 } 20234 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 20235 isGranted, newFlagSet, userId); 20236 } 20237 } else { 20238 PackageManagerService.reportSettingsProblem(Log.WARN, 20239 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 20240 XmlUtils.skipCurrentTag(parser); 20241 } 20242 } 20243 20244 scheduleWriteSettingsLocked(); 20245 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 20246 } 20247 20248 @Override 20249 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 20250 int sourceUserId, int targetUserId, int flags) { 20251 mContext.enforceCallingOrSelfPermission( 20252 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20253 int callingUid = Binder.getCallingUid(); 20254 enforceOwnerRights(ownerPackage, callingUid); 20255 PackageManagerServiceUtils.enforceShellRestriction( 20256 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20257 if (intentFilter.countActions() == 0) { 20258 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 20259 return; 20260 } 20261 synchronized (mPackages) { 20262 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 20263 ownerPackage, targetUserId, flags); 20264 CrossProfileIntentResolver resolver = 20265 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20266 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 20267 // We have all those whose filter is equal. Now checking if the rest is equal as well. 20268 if (existing != null) { 20269 int size = existing.size(); 20270 for (int i = 0; i < size; i++) { 20271 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 20272 return; 20273 } 20274 } 20275 } 20276 resolver.addFilter(newFilter); 20277 scheduleWritePackageRestrictionsLocked(sourceUserId); 20278 } 20279 } 20280 20281 @Override 20282 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 20283 mContext.enforceCallingOrSelfPermission( 20284 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20285 final int callingUid = Binder.getCallingUid(); 20286 enforceOwnerRights(ownerPackage, callingUid); 20287 PackageManagerServiceUtils.enforceShellRestriction( 20288 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20289 synchronized (mPackages) { 20290 CrossProfileIntentResolver resolver = 20291 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20292 ArraySet<CrossProfileIntentFilter> set = 20293 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 20294 for (CrossProfileIntentFilter filter : set) { 20295 if (filter.getOwnerPackage().equals(ownerPackage)) { 20296 resolver.removeFilter(filter); 20297 } 20298 } 20299 scheduleWritePackageRestrictionsLocked(sourceUserId); 20300 } 20301 } 20302 20303 // Enforcing that callingUid is owning pkg on userId 20304 private void enforceOwnerRights(String pkg, int callingUid) { 20305 // The system owns everything. 20306 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 20307 return; 20308 } 20309 final int callingUserId = UserHandle.getUserId(callingUid); 20310 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 20311 if (pi == null) { 20312 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 20313 + callingUserId); 20314 } 20315 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 20316 throw new SecurityException("Calling uid " + callingUid 20317 + " does not own package " + pkg); 20318 } 20319 } 20320 20321 @Override 20322 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 20323 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20324 return null; 20325 } 20326 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 20327 } 20328 20329 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 20330 UserManagerService ums = UserManagerService.getInstance(); 20331 if (ums != null) { 20332 final UserInfo parent = ums.getProfileParent(userId); 20333 final int launcherUid = (parent != null) ? parent.id : userId; 20334 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 20335 if (launcherComponent != null) { 20336 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 20337 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 20338 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 20339 .setPackage(launcherComponent.getPackageName()); 20340 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 20341 } 20342 } 20343 } 20344 20345 /** 20346 * Report the 'Home' activity which is currently set as "always use this one". If non is set 20347 * then reports the most likely home activity or null if there are more than one. 20348 */ 20349 private ComponentName getDefaultHomeActivity(int userId) { 20350 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 20351 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 20352 if (cn != null) { 20353 return cn; 20354 } 20355 20356 // Find the launcher with the highest priority and return that component if there are no 20357 // other home activity with the same priority. 20358 int lastPriority = Integer.MIN_VALUE; 20359 ComponentName lastComponent = null; 20360 final int size = allHomeCandidates.size(); 20361 for (int i = 0; i < size; i++) { 20362 final ResolveInfo ri = allHomeCandidates.get(i); 20363 if (ri.priority > lastPriority) { 20364 lastComponent = ri.activityInfo.getComponentName(); 20365 lastPriority = ri.priority; 20366 } else if (ri.priority == lastPriority) { 20367 // Two components found with same priority. 20368 lastComponent = null; 20369 } 20370 } 20371 return lastComponent; 20372 } 20373 20374 private Intent getHomeIntent() { 20375 Intent intent = new Intent(Intent.ACTION_MAIN); 20376 intent.addCategory(Intent.CATEGORY_HOME); 20377 intent.addCategory(Intent.CATEGORY_DEFAULT); 20378 return intent; 20379 } 20380 20381 private IntentFilter getHomeFilter() { 20382 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 20383 filter.addCategory(Intent.CATEGORY_HOME); 20384 filter.addCategory(Intent.CATEGORY_DEFAULT); 20385 return filter; 20386 } 20387 20388 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20389 int userId) { 20390 Intent intent = getHomeIntent(); 20391 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 20392 PackageManager.GET_META_DATA, userId); 20393 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 20394 true, false, false, userId); 20395 20396 allHomeCandidates.clear(); 20397 if (list != null) { 20398 for (ResolveInfo ri : list) { 20399 allHomeCandidates.add(ri); 20400 } 20401 } 20402 return (preferred == null || preferred.activityInfo == null) 20403 ? null 20404 : new ComponentName(preferred.activityInfo.packageName, 20405 preferred.activityInfo.name); 20406 } 20407 20408 @Override 20409 public void setHomeActivity(ComponentName comp, int userId) { 20410 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20411 return; 20412 } 20413 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 20414 getHomeActivitiesAsUser(homeActivities, userId); 20415 20416 boolean found = false; 20417 20418 final int size = homeActivities.size(); 20419 final ComponentName[] set = new ComponentName[size]; 20420 for (int i = 0; i < size; i++) { 20421 final ResolveInfo candidate = homeActivities.get(i); 20422 final ActivityInfo info = candidate.activityInfo; 20423 final ComponentName activityName = new ComponentName(info.packageName, info.name); 20424 set[i] = activityName; 20425 if (!found && activityName.equals(comp)) { 20426 found = true; 20427 } 20428 } 20429 if (!found) { 20430 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 20431 + userId); 20432 } 20433 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 20434 set, comp, userId); 20435 } 20436 20437 private @Nullable String getSetupWizardPackageName() { 20438 final Intent intent = new Intent(Intent.ACTION_MAIN); 20439 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 20440 20441 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20442 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20443 | MATCH_DISABLED_COMPONENTS, 20444 UserHandle.myUserId()); 20445 if (matches.size() == 1) { 20446 return matches.get(0).getComponentInfo().packageName; 20447 } else { 20448 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 20449 + ": matches=" + matches); 20450 return null; 20451 } 20452 } 20453 20454 private @Nullable String getStorageManagerPackageName() { 20455 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 20456 20457 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20458 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20459 | MATCH_DISABLED_COMPONENTS, 20460 UserHandle.myUserId()); 20461 if (matches.size() == 1) { 20462 return matches.get(0).getComponentInfo().packageName; 20463 } else { 20464 Slog.e(TAG, "There should probably be exactly one storage manager; found " 20465 + matches.size() + ": matches=" + matches); 20466 return null; 20467 } 20468 } 20469 20470 @Override 20471 public String getSystemTextClassifierPackageName() { 20472 return mContext.getString(R.string.config_defaultTextClassifierPackage); 20473 } 20474 20475 @Override 20476 public void setApplicationEnabledSetting(String appPackageName, 20477 int newState, int flags, int userId, String callingPackage) { 20478 if (!sUserManager.exists(userId)) return; 20479 if (callingPackage == null) { 20480 callingPackage = Integer.toString(Binder.getCallingUid()); 20481 } 20482 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 20483 } 20484 20485 @Override 20486 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 20487 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 20488 synchronized (mPackages) { 20489 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 20490 if (pkgSetting != null) { 20491 pkgSetting.setUpdateAvailable(updateAvailable); 20492 } 20493 } 20494 } 20495 20496 @Override 20497 public void setComponentEnabledSetting(ComponentName componentName, 20498 int newState, int flags, int userId) { 20499 if (!sUserManager.exists(userId)) return; 20500 setEnabledSetting(componentName.getPackageName(), 20501 componentName.getClassName(), newState, flags, userId, null); 20502 } 20503 20504 private void setEnabledSetting(final String packageName, String className, int newState, 20505 final int flags, int userId, String callingPackage) { 20506 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 20507 || newState == COMPONENT_ENABLED_STATE_ENABLED 20508 || newState == COMPONENT_ENABLED_STATE_DISABLED 20509 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20510 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 20511 throw new IllegalArgumentException("Invalid new component state: " 20512 + newState); 20513 } 20514 PackageSetting pkgSetting; 20515 final int callingUid = Binder.getCallingUid(); 20516 final int permission; 20517 if (callingUid == Process.SYSTEM_UID) { 20518 permission = PackageManager.PERMISSION_GRANTED; 20519 } else { 20520 permission = mContext.checkCallingOrSelfPermission( 20521 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20522 } 20523 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20524 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 20525 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20526 boolean sendNow = false; 20527 boolean isApp = (className == null); 20528 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 20529 String componentName = isApp ? packageName : className; 20530 int packageUid = -1; 20531 ArrayList<String> components; 20532 20533 // reader 20534 synchronized (mPackages) { 20535 pkgSetting = mSettings.mPackages.get(packageName); 20536 if (pkgSetting == null) { 20537 if (!isCallerInstantApp) { 20538 if (className == null) { 20539 throw new IllegalArgumentException("Unknown package: " + packageName); 20540 } 20541 throw new IllegalArgumentException( 20542 "Unknown component: " + packageName + "/" + className); 20543 } else { 20544 // throw SecurityException to prevent leaking package information 20545 throw new SecurityException( 20546 "Attempt to change component state; " 20547 + "pid=" + Binder.getCallingPid() 20548 + ", uid=" + callingUid 20549 + (className == null 20550 ? ", package=" + packageName 20551 : ", component=" + packageName + "/" + className)); 20552 } 20553 } 20554 } 20555 20556 // Limit who can change which apps 20557 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 20558 // Don't allow apps that don't have permission to modify other apps 20559 if (!allowedByPermission 20560 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 20561 throw new SecurityException( 20562 "Attempt to change component state; " 20563 + "pid=" + Binder.getCallingPid() 20564 + ", uid=" + callingUid 20565 + (className == null 20566 ? ", package=" + packageName 20567 : ", component=" + packageName + "/" + className)); 20568 } 20569 // Don't allow changing protected packages. 20570 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 20571 throw new SecurityException("Cannot disable a protected package: " + packageName); 20572 } 20573 } 20574 20575 synchronized (mPackages) { 20576 if (callingUid == Process.SHELL_UID 20577 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 20578 // Shell can only change whole packages between ENABLED and DISABLED_USER states 20579 // unless it is a test package. 20580 int oldState = pkgSetting.getEnabled(userId); 20581 if (className == null 20582 && 20583 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 20584 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 20585 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 20586 && 20587 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20588 || newState == COMPONENT_ENABLED_STATE_DEFAULT 20589 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 20590 // ok 20591 } else { 20592 throw new SecurityException( 20593 "Shell cannot change component state for " + packageName + "/" 20594 + className + " to " + newState); 20595 } 20596 } 20597 } 20598 if (className == null) { 20599 // We're dealing with an application/package level state change 20600 synchronized (mPackages) { 20601 if (pkgSetting.getEnabled(userId) == newState) { 20602 // Nothing to do 20603 return; 20604 } 20605 } 20606 // If we're enabling a system stub, there's a little more work to do. 20607 // Prior to enabling the package, we need to decompress the APK(s) to the 20608 // data partition and then replace the version on the system partition. 20609 final PackageParser.Package deletedPkg = pkgSetting.pkg; 20610 final boolean isSystemStub = deletedPkg.isStub 20611 && deletedPkg.isSystem(); 20612 if (isSystemStub 20613 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20614 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 20615 final File codePath = decompressPackage(deletedPkg); 20616 if (codePath == null) { 20617 Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name); 20618 return; 20619 } 20620 // TODO remove direct parsing of the package object during internal cleanup 20621 // of scan package 20622 // We need to call parse directly here for no other reason than we need 20623 // the new package in order to disable the old one [we use the information 20624 // for some internal optimization to optionally create a new package setting 20625 // object on replace]. However, we can't get the package from the scan 20626 // because the scan modifies live structures and we need to remove the 20627 // old [system] package from the system before a scan can be attempted. 20628 // Once scan is indempotent we can remove this parse and use the package 20629 // object we scanned, prior to adding it to package settings. 20630 final PackageParser pp = new PackageParser(); 20631 pp.setSeparateProcesses(mSeparateProcesses); 20632 pp.setDisplayMetrics(mMetrics); 20633 pp.setCallback(mPackageParserCallback); 20634 final PackageParser.Package tmpPkg; 20635 try { 20636 final @ParseFlags int parseFlags = mDefParseFlags 20637 | PackageParser.PARSE_MUST_BE_APK 20638 | PackageParser.PARSE_IS_SYSTEM_DIR; 20639 tmpPkg = pp.parsePackage(codePath, parseFlags); 20640 } catch (PackageParserException e) { 20641 Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e); 20642 return; 20643 } 20644 synchronized (mInstallLock) { 20645 // Disable the stub and remove any package entries 20646 removePackageLI(deletedPkg, true); 20647 synchronized (mPackages) { 20648 disableSystemPackageLPw(deletedPkg, tmpPkg); 20649 } 20650 final PackageParser.Package pkg; 20651 try (PackageFreezer freezer = 20652 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20653 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 20654 | PackageParser.PARSE_ENFORCE_CODE; 20655 pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 20656 0 /*currentTime*/, null /*user*/); 20657 prepareAppDataAfterInstallLIF(pkg); 20658 synchronized (mPackages) { 20659 try { 20660 updateSharedLibrariesLPr(pkg, null); 20661 } catch (PackageManagerException e) { 20662 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 20663 } 20664 mPermissionManager.updatePermissions( 20665 pkg.packageName, pkg, true, mPackages.values(), 20666 mPermissionCallback); 20667 mSettings.writeLPr(); 20668 } 20669 } catch (PackageManagerException e) { 20670 // Whoops! Something went wrong; try to roll back to the stub 20671 Slog.w(TAG, "Failed to install compressed system package:" 20672 + pkgSetting.name, e); 20673 // Remove the failed install 20674 removeCodePathLI(codePath); 20675 20676 // Install the system package 20677 try (PackageFreezer freezer = 20678 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20679 synchronized (mPackages) { 20680 // NOTE: The system package always needs to be enabled; even 20681 // if it's for a compressed stub. If we don't, installing the 20682 // system package fails during scan [scanning checks the disabled 20683 // packages]. We will reverse this later, after we've "installed" 20684 // the stub. 20685 // This leaves us in a fragile state; the stub should never be 20686 // enabled, so, cross your fingers and hope nothing goes wrong 20687 // until we can disable the package later. 20688 enableSystemPackageLPw(deletedPkg); 20689 } 20690 installPackageFromSystemLIF(deletedPkg.codePath, 20691 false /*isPrivileged*/, null /*allUserHandles*/, 20692 null /*origUserHandles*/, null /*origPermissionsState*/, 20693 true /*writeSettings*/); 20694 } catch (PackageManagerException pme) { 20695 Slog.w(TAG, "Failed to restore system package:" 20696 + deletedPkg.packageName, pme); 20697 } finally { 20698 synchronized (mPackages) { 20699 mSettings.disableSystemPackageLPw( 20700 deletedPkg.packageName, true /*replaced*/); 20701 mSettings.writeLPr(); 20702 } 20703 } 20704 return; 20705 } 20706 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE 20707 | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20708 mDexManager.notifyPackageUpdated(pkg.packageName, 20709 pkg.baseCodePath, pkg.splitCodePaths); 20710 } 20711 } 20712 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20713 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20714 // Don't care about who enables an app. 20715 callingPackage = null; 20716 } 20717 synchronized (mPackages) { 20718 pkgSetting.setEnabled(newState, userId, callingPackage); 20719 } 20720 } else { 20721 synchronized (mPackages) { 20722 // We're dealing with a component level state change 20723 // First, verify that this is a valid class name. 20724 PackageParser.Package pkg = pkgSetting.pkg; 20725 if (pkg == null || !pkg.hasComponentClassName(className)) { 20726 if (pkg != null && 20727 pkg.applicationInfo.targetSdkVersion >= 20728 Build.VERSION_CODES.JELLY_BEAN) { 20729 throw new IllegalArgumentException("Component class " + className 20730 + " does not exist in " + packageName); 20731 } else { 20732 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20733 + className + " does not exist in " + packageName); 20734 } 20735 } 20736 switch (newState) { 20737 case COMPONENT_ENABLED_STATE_ENABLED: 20738 if (!pkgSetting.enableComponentLPw(className, userId)) { 20739 return; 20740 } 20741 break; 20742 case COMPONENT_ENABLED_STATE_DISABLED: 20743 if (!pkgSetting.disableComponentLPw(className, userId)) { 20744 return; 20745 } 20746 break; 20747 case COMPONENT_ENABLED_STATE_DEFAULT: 20748 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20749 return; 20750 } 20751 break; 20752 default: 20753 Slog.e(TAG, "Invalid new component state: " + newState); 20754 return; 20755 } 20756 } 20757 } 20758 synchronized (mPackages) { 20759 scheduleWritePackageRestrictionsLocked(userId); 20760 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 20761 final long callingId = Binder.clearCallingIdentity(); 20762 try { 20763 updateInstantAppInstallerLocked(packageName); 20764 } finally { 20765 Binder.restoreCallingIdentity(callingId); 20766 } 20767 components = mPendingBroadcasts.get(userId, packageName); 20768 final boolean newPackage = components == null; 20769 if (newPackage) { 20770 components = new ArrayList<String>(); 20771 } 20772 if (!components.contains(componentName)) { 20773 components.add(componentName); 20774 } 20775 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20776 sendNow = true; 20777 // Purge entry from pending broadcast list if another one exists already 20778 // since we are sending one right away. 20779 mPendingBroadcasts.remove(userId, packageName); 20780 } else { 20781 if (newPackage) { 20782 mPendingBroadcasts.put(userId, packageName, components); 20783 } 20784 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20785 // Schedule a message 20786 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20787 } 20788 } 20789 } 20790 20791 long callingId = Binder.clearCallingIdentity(); 20792 try { 20793 if (sendNow) { 20794 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20795 sendPackageChangedBroadcast(packageName, 20796 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20797 } 20798 } finally { 20799 Binder.restoreCallingIdentity(callingId); 20800 } 20801 } 20802 20803 @Override 20804 public void flushPackageRestrictionsAsUser(int userId) { 20805 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20806 return; 20807 } 20808 if (!sUserManager.exists(userId)) { 20809 return; 20810 } 20811 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20812 false /* checkShell */, "flushPackageRestrictions"); 20813 synchronized (mPackages) { 20814 mSettings.writePackageRestrictionsLPr(userId); 20815 mDirtyUsers.remove(userId); 20816 if (mDirtyUsers.isEmpty()) { 20817 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20818 } 20819 } 20820 } 20821 20822 private void sendPackageChangedBroadcast(String packageName, 20823 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20824 if (DEBUG_INSTALL) 20825 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20826 + componentNames); 20827 Bundle extras = new Bundle(4); 20828 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20829 String nameList[] = new String[componentNames.size()]; 20830 componentNames.toArray(nameList); 20831 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20832 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20833 extras.putInt(Intent.EXTRA_UID, packageUid); 20834 // If this is not reporting a change of the overall package, then only send it 20835 // to registered receivers. We don't want to launch a swath of apps for every 20836 // little component state change. 20837 final int flags = !componentNames.contains(packageName) 20838 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20839 final int userId = UserHandle.getUserId(packageUid); 20840 final boolean isInstantApp = isInstantApp(packageName, userId); 20841 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 20842 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 20843 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20844 userIds, instantUserIds); 20845 } 20846 20847 @Override 20848 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20849 if (!sUserManager.exists(userId)) return; 20850 final int callingUid = Binder.getCallingUid(); 20851 if (getInstantAppPackageName(callingUid) != null) { 20852 return; 20853 } 20854 final int permission = mContext.checkCallingOrSelfPermission( 20855 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20856 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20857 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20858 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20859 // writer 20860 synchronized (mPackages) { 20861 final PackageSetting ps = mSettings.mPackages.get(packageName); 20862 if (!filterAppAccessLPr(ps, callingUid, userId) 20863 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20864 allowedByPermission, callingUid, userId)) { 20865 scheduleWritePackageRestrictionsLocked(userId); 20866 } 20867 } 20868 } 20869 20870 @Override 20871 public String getInstallerPackageName(String packageName) { 20872 final int callingUid = Binder.getCallingUid(); 20873 synchronized (mPackages) { 20874 final PackageSetting ps = mSettings.mPackages.get(packageName); 20875 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20876 return null; 20877 } 20878 return mSettings.getInstallerPackageNameLPr(packageName); 20879 } 20880 } 20881 20882 public boolean isOrphaned(String packageName) { 20883 // reader 20884 synchronized (mPackages) { 20885 return mSettings.isOrphaned(packageName); 20886 } 20887 } 20888 20889 @Override 20890 public int getApplicationEnabledSetting(String packageName, int userId) { 20891 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20892 int callingUid = Binder.getCallingUid(); 20893 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20894 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20895 // reader 20896 synchronized (mPackages) { 20897 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 20898 return COMPONENT_ENABLED_STATE_DISABLED; 20899 } 20900 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20901 } 20902 } 20903 20904 @Override 20905 public int getComponentEnabledSetting(ComponentName component, int userId) { 20906 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20907 int callingUid = Binder.getCallingUid(); 20908 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20909 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 20910 synchronized (mPackages) { 20911 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 20912 component, TYPE_UNKNOWN, userId)) { 20913 return COMPONENT_ENABLED_STATE_DISABLED; 20914 } 20915 return mSettings.getComponentEnabledSettingLPr(component, userId); 20916 } 20917 } 20918 20919 @Override 20920 public void enterSafeMode() { 20921 enforceSystemOrRoot("Only the system can request entering safe mode"); 20922 20923 if (!mSystemReady) { 20924 mSafeMode = true; 20925 } 20926 } 20927 20928 @Override 20929 public void systemReady() { 20930 enforceSystemOrRoot("Only the system can claim the system is ready"); 20931 20932 mSystemReady = true; 20933 final ContentResolver resolver = mContext.getContentResolver(); 20934 ContentObserver co = new ContentObserver(mHandler) { 20935 @Override 20936 public void onChange(boolean selfChange) { 20937 mWebInstantAppsDisabled = 20938 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20939 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20940 } 20941 }; 20942 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20943 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20944 false, co, UserHandle.USER_SYSTEM); 20945 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure 20946 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20947 co.onChange(true); 20948 20949 // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to 20950 // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once 20951 // it is done. 20952 ContentObserver privAppOobObserver = new ContentObserver(mHandler) { 20953 @Override 20954 public void onChange(boolean selfChange) { 20955 int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0); 20956 SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, 20957 oobEnabled == 1 ? "true" : "false"); 20958 } 20959 }; 20960 mContext.getContentResolver().registerContentObserver( 20961 Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver, 20962 UserHandle.USER_SYSTEM); 20963 // At boot, restore the value from the setting, which persists across reboot. 20964 privAppOobObserver.onChange(true); 20965 20966 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20967 // disabled after already being started. 20968 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20969 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20970 20971 // Read the compatibilty setting when the system is ready. 20972 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20973 mContext.getContentResolver(), 20974 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20975 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20976 if (DEBUG_SETTINGS) { 20977 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20978 } 20979 20980 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20981 20982 synchronized (mPackages) { 20983 // Verify that all of the preferred activity components actually 20984 // exist. It is possible for applications to be updated and at 20985 // that point remove a previously declared activity component that 20986 // had been set as a preferred activity. We try to clean this up 20987 // the next time we encounter that preferred activity, but it is 20988 // possible for the user flow to never be able to return to that 20989 // situation so here we do a sanity check to make sure we haven't 20990 // left any junk around. 20991 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20992 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20993 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20994 removed.clear(); 20995 for (PreferredActivity pa : pir.filterSet()) { 20996 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20997 removed.add(pa); 20998 } 20999 } 21000 if (removed.size() > 0) { 21001 for (int r=0; r<removed.size(); r++) { 21002 PreferredActivity pa = removed.get(r); 21003 Slog.w(TAG, "Removing dangling preferred activity: " 21004 + pa.mPref.mComponent); 21005 pir.removeFilter(pa); 21006 } 21007 mSettings.writePackageRestrictionsLPr( 21008 mSettings.mPreferredActivities.keyAt(i)); 21009 } 21010 } 21011 21012 for (int userId : UserManagerService.getInstance().getUserIds()) { 21013 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 21014 grantPermissionsUserIds = ArrayUtils.appendInt( 21015 grantPermissionsUserIds, userId); 21016 } 21017 } 21018 } 21019 sUserManager.systemReady(); 21020 // If we upgraded grant all default permissions before kicking off. 21021 for (int userId : grantPermissionsUserIds) { 21022 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 21023 } 21024 21025 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 21026 // If we did not grant default permissions, we preload from this the 21027 // default permission exceptions lazily to ensure we don't hit the 21028 // disk on a new user creation. 21029 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 21030 } 21031 21032 // Now that we've scanned all packages, and granted any default 21033 // permissions, ensure permissions are updated. Beware of dragons if you 21034 // try optimizing this. 21035 synchronized (mPackages) { 21036 mPermissionManager.updateAllPermissions( 21037 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 21038 mPermissionCallback); 21039 } 21040 21041 // Kick off any messages waiting for system ready 21042 if (mPostSystemReadyMessages != null) { 21043 for (Message msg : mPostSystemReadyMessages) { 21044 msg.sendToTarget(); 21045 } 21046 mPostSystemReadyMessages = null; 21047 } 21048 21049 // Watch for external volumes that come and go over time 21050 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21051 storage.registerListener(mStorageListener); 21052 21053 mInstallerService.systemReady(); 21054 mPackageDexOptimizer.systemReady(); 21055 21056 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 21057 StorageManagerInternal.class); 21058 StorageManagerInternal.addExternalStoragePolicy( 21059 new StorageManagerInternal.ExternalStorageMountPolicy() { 21060 @Override 21061 public int getMountMode(int uid, String packageName) { 21062 if (Process.isIsolated(uid)) { 21063 return Zygote.MOUNT_EXTERNAL_NONE; 21064 } 21065 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 21066 return Zygote.MOUNT_EXTERNAL_DEFAULT; 21067 } 21068 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 21069 return Zygote.MOUNT_EXTERNAL_READ; 21070 } 21071 return Zygote.MOUNT_EXTERNAL_WRITE; 21072 } 21073 21074 @Override 21075 public boolean hasExternalStorage(int uid, String packageName) { 21076 return true; 21077 } 21078 }); 21079 21080 // Now that we're mostly running, clean up stale users and apps 21081 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 21082 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 21083 21084 mPermissionManager.systemReady(); 21085 21086 if (mInstantAppResolverConnection != null) { 21087 mContext.registerReceiver(new BroadcastReceiver() { 21088 @Override 21089 public void onReceive(Context context, Intent intent) { 21090 mInstantAppResolverConnection.optimisticBind(); 21091 mContext.unregisterReceiver(this); 21092 } 21093 }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED)); 21094 } 21095 } 21096 21097 public void waitForAppDataPrepared() { 21098 if (mPrepareAppDataFuture == null) { 21099 return; 21100 } 21101 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 21102 mPrepareAppDataFuture = null; 21103 } 21104 21105 @Override 21106 public boolean isSafeMode() { 21107 // allow instant applications 21108 return mSafeMode; 21109 } 21110 21111 @Override 21112 public boolean hasSystemUidErrors() { 21113 // allow instant applications 21114 return mHasSystemUidErrors; 21115 } 21116 21117 static String arrayToString(int[] array) { 21118 StringBuffer buf = new StringBuffer(128); 21119 buf.append('['); 21120 if (array != null) { 21121 for (int i=0; i<array.length; i++) { 21122 if (i > 0) buf.append(", "); 21123 buf.append(array[i]); 21124 } 21125 } 21126 buf.append(']'); 21127 return buf.toString(); 21128 } 21129 21130 @Override 21131 public void onShellCommand(FileDescriptor in, FileDescriptor out, 21132 FileDescriptor err, String[] args, ShellCallback callback, 21133 ResultReceiver resultReceiver) { 21134 (new PackageManagerShellCommand(this)).exec( 21135 this, in, out, err, args, callback, resultReceiver); 21136 } 21137 21138 @Override 21139 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 21140 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 21141 21142 DumpState dumpState = new DumpState(); 21143 boolean fullPreferred = false; 21144 boolean checkin = false; 21145 21146 String packageName = null; 21147 ArraySet<String> permissionNames = null; 21148 21149 int opti = 0; 21150 while (opti < args.length) { 21151 String opt = args[opti]; 21152 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 21153 break; 21154 } 21155 opti++; 21156 21157 if ("-a".equals(opt)) { 21158 // Right now we only know how to print all. 21159 } else if ("-h".equals(opt)) { 21160 pw.println("Package manager dump options:"); 21161 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 21162 pw.println(" --checkin: dump for a checkin"); 21163 pw.println(" -f: print details of intent filters"); 21164 pw.println(" -h: print this help"); 21165 pw.println(" cmd may be one of:"); 21166 pw.println(" l[ibraries]: list known shared libraries"); 21167 pw.println(" f[eatures]: list device features"); 21168 pw.println(" k[eysets]: print known keysets"); 21169 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 21170 pw.println(" perm[issions]: dump permissions"); 21171 pw.println(" permission [name ...]: dump declaration and use of given permission"); 21172 pw.println(" pref[erred]: print preferred package settings"); 21173 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 21174 pw.println(" prov[iders]: dump content providers"); 21175 pw.println(" p[ackages]: dump installed packages"); 21176 pw.println(" s[hared-users]: dump shared user IDs"); 21177 pw.println(" m[essages]: print collected runtime messages"); 21178 pw.println(" v[erifiers]: print package verifier info"); 21179 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 21180 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 21181 pw.println(" version: print database version info"); 21182 pw.println(" write: write current settings now"); 21183 pw.println(" installs: details about install sessions"); 21184 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 21185 pw.println(" dexopt: dump dexopt state"); 21186 pw.println(" compiler-stats: dump compiler statistics"); 21187 pw.println(" service-permissions: dump permissions required by services"); 21188 pw.println(" <package.name>: info about given package"); 21189 return; 21190 } else if ("--checkin".equals(opt)) { 21191 checkin = true; 21192 } else if ("-f".equals(opt)) { 21193 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21194 } else if ("--proto".equals(opt)) { 21195 dumpProto(fd); 21196 return; 21197 } else { 21198 pw.println("Unknown argument: " + opt + "; use -h for help"); 21199 } 21200 } 21201 21202 // Is the caller requesting to dump a particular piece of data? 21203 if (opti < args.length) { 21204 String cmd = args[opti]; 21205 opti++; 21206 // Is this a package name? 21207 if ("android".equals(cmd) || cmd.contains(".")) { 21208 packageName = cmd; 21209 // When dumping a single package, we always dump all of its 21210 // filter information since the amount of data will be reasonable. 21211 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21212 } else if ("check-permission".equals(cmd)) { 21213 if (opti >= args.length) { 21214 pw.println("Error: check-permission missing permission argument"); 21215 return; 21216 } 21217 String perm = args[opti]; 21218 opti++; 21219 if (opti >= args.length) { 21220 pw.println("Error: check-permission missing package argument"); 21221 return; 21222 } 21223 21224 String pkg = args[opti]; 21225 opti++; 21226 int user = UserHandle.getUserId(Binder.getCallingUid()); 21227 if (opti < args.length) { 21228 try { 21229 user = Integer.parseInt(args[opti]); 21230 } catch (NumberFormatException e) { 21231 pw.println("Error: check-permission user argument is not a number: " 21232 + args[opti]); 21233 return; 21234 } 21235 } 21236 21237 // Normalize package name to handle renamed packages and static libs 21238 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 21239 21240 pw.println(checkPermission(perm, pkg, user)); 21241 return; 21242 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 21243 dumpState.setDump(DumpState.DUMP_LIBS); 21244 } else if ("f".equals(cmd) || "features".equals(cmd)) { 21245 dumpState.setDump(DumpState.DUMP_FEATURES); 21246 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 21247 if (opti >= args.length) { 21248 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 21249 | DumpState.DUMP_SERVICE_RESOLVERS 21250 | DumpState.DUMP_RECEIVER_RESOLVERS 21251 | DumpState.DUMP_CONTENT_RESOLVERS); 21252 } else { 21253 while (opti < args.length) { 21254 String name = args[opti]; 21255 if ("a".equals(name) || "activity".equals(name)) { 21256 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 21257 } else if ("s".equals(name) || "service".equals(name)) { 21258 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 21259 } else if ("r".equals(name) || "receiver".equals(name)) { 21260 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 21261 } else if ("c".equals(name) || "content".equals(name)) { 21262 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 21263 } else { 21264 pw.println("Error: unknown resolver table type: " + name); 21265 return; 21266 } 21267 opti++; 21268 } 21269 } 21270 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 21271 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 21272 } else if ("permission".equals(cmd)) { 21273 if (opti >= args.length) { 21274 pw.println("Error: permission requires permission name"); 21275 return; 21276 } 21277 permissionNames = new ArraySet<>(); 21278 while (opti < args.length) { 21279 permissionNames.add(args[opti]); 21280 opti++; 21281 } 21282 dumpState.setDump(DumpState.DUMP_PERMISSIONS 21283 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 21284 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 21285 dumpState.setDump(DumpState.DUMP_PREFERRED); 21286 } else if ("preferred-xml".equals(cmd)) { 21287 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 21288 if (opti < args.length && "--full".equals(args[opti])) { 21289 fullPreferred = true; 21290 opti++; 21291 } 21292 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 21293 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 21294 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 21295 dumpState.setDump(DumpState.DUMP_PACKAGES); 21296 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 21297 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 21298 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 21299 dumpState.setDump(DumpState.DUMP_PROVIDERS); 21300 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 21301 dumpState.setDump(DumpState.DUMP_MESSAGES); 21302 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 21303 dumpState.setDump(DumpState.DUMP_VERIFIERS); 21304 } else if ("i".equals(cmd) || "ifv".equals(cmd) 21305 || "intent-filter-verifiers".equals(cmd)) { 21306 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 21307 } else if ("version".equals(cmd)) { 21308 dumpState.setDump(DumpState.DUMP_VERSION); 21309 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 21310 dumpState.setDump(DumpState.DUMP_KEYSETS); 21311 } else if ("installs".equals(cmd)) { 21312 dumpState.setDump(DumpState.DUMP_INSTALLS); 21313 } else if ("frozen".equals(cmd)) { 21314 dumpState.setDump(DumpState.DUMP_FROZEN); 21315 } else if ("volumes".equals(cmd)) { 21316 dumpState.setDump(DumpState.DUMP_VOLUMES); 21317 } else if ("dexopt".equals(cmd)) { 21318 dumpState.setDump(DumpState.DUMP_DEXOPT); 21319 } else if ("compiler-stats".equals(cmd)) { 21320 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 21321 } else if ("changes".equals(cmd)) { 21322 dumpState.setDump(DumpState.DUMP_CHANGES); 21323 } else if ("service-permissions".equals(cmd)) { 21324 dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS); 21325 } else if ("write".equals(cmd)) { 21326 synchronized (mPackages) { 21327 mSettings.writeLPr(); 21328 pw.println("Settings written."); 21329 return; 21330 } 21331 } 21332 } 21333 21334 if (checkin) { 21335 pw.println("vers,1"); 21336 } 21337 21338 // reader 21339 synchronized (mPackages) { 21340 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 21341 if (!checkin) { 21342 if (dumpState.onTitlePrinted()) 21343 pw.println(); 21344 pw.println("Database versions:"); 21345 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 21346 } 21347 } 21348 21349 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 21350 if (!checkin) { 21351 if (dumpState.onTitlePrinted()) 21352 pw.println(); 21353 pw.println("Verifiers:"); 21354 pw.print(" Required: "); 21355 pw.print(mRequiredVerifierPackage); 21356 pw.print(" (uid="); 21357 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21358 UserHandle.USER_SYSTEM)); 21359 pw.println(")"); 21360 } else if (mRequiredVerifierPackage != null) { 21361 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 21362 pw.print(","); 21363 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21364 UserHandle.USER_SYSTEM)); 21365 } 21366 } 21367 21368 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 21369 packageName == null) { 21370 if (mIntentFilterVerifierComponent != null) { 21371 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21372 if (!checkin) { 21373 if (dumpState.onTitlePrinted()) 21374 pw.println(); 21375 pw.println("Intent Filter Verifier:"); 21376 pw.print(" Using: "); 21377 pw.print(verifierPackageName); 21378 pw.print(" (uid="); 21379 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21380 UserHandle.USER_SYSTEM)); 21381 pw.println(")"); 21382 } else if (verifierPackageName != null) { 21383 pw.print("ifv,"); pw.print(verifierPackageName); 21384 pw.print(","); 21385 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21386 UserHandle.USER_SYSTEM)); 21387 } 21388 } else { 21389 pw.println(); 21390 pw.println("No Intent Filter Verifier available!"); 21391 } 21392 } 21393 21394 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 21395 boolean printedHeader = false; 21396 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 21397 while (it.hasNext()) { 21398 String libName = it.next(); 21399 LongSparseArray<SharedLibraryEntry> versionedLib 21400 = mSharedLibraries.get(libName); 21401 if (versionedLib == null) { 21402 continue; 21403 } 21404 final int versionCount = versionedLib.size(); 21405 for (int i = 0; i < versionCount; i++) { 21406 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 21407 if (!checkin) { 21408 if (!printedHeader) { 21409 if (dumpState.onTitlePrinted()) 21410 pw.println(); 21411 pw.println("Libraries:"); 21412 printedHeader = true; 21413 } 21414 pw.print(" "); 21415 } else { 21416 pw.print("lib,"); 21417 } 21418 pw.print(libEntry.info.getName()); 21419 if (libEntry.info.isStatic()) { 21420 pw.print(" version=" + libEntry.info.getLongVersion()); 21421 } 21422 if (!checkin) { 21423 pw.print(" -> "); 21424 } 21425 if (libEntry.path != null) { 21426 pw.print(" (jar) "); 21427 pw.print(libEntry.path); 21428 } else { 21429 pw.print(" (apk) "); 21430 pw.print(libEntry.apk); 21431 } 21432 pw.println(); 21433 } 21434 } 21435 } 21436 21437 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 21438 if (dumpState.onTitlePrinted()) 21439 pw.println(); 21440 if (!checkin) { 21441 pw.println("Features:"); 21442 } 21443 21444 synchronized (mAvailableFeatures) { 21445 for (FeatureInfo feat : mAvailableFeatures.values()) { 21446 if (checkin) { 21447 pw.print("feat,"); 21448 pw.print(feat.name); 21449 pw.print(","); 21450 pw.println(feat.version); 21451 } else { 21452 pw.print(" "); 21453 pw.print(feat.name); 21454 if (feat.version > 0) { 21455 pw.print(" version="); 21456 pw.print(feat.version); 21457 } 21458 pw.println(); 21459 } 21460 } 21461 } 21462 } 21463 21464 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 21465 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 21466 : "Activity Resolver Table:", " ", packageName, 21467 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21468 dumpState.setTitlePrinted(true); 21469 } 21470 } 21471 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 21472 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 21473 : "Receiver Resolver Table:", " ", packageName, 21474 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21475 dumpState.setTitlePrinted(true); 21476 } 21477 } 21478 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 21479 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 21480 : "Service Resolver Table:", " ", packageName, 21481 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21482 dumpState.setTitlePrinted(true); 21483 } 21484 } 21485 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 21486 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 21487 : "Provider Resolver Table:", " ", packageName, 21488 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21489 dumpState.setTitlePrinted(true); 21490 } 21491 } 21492 21493 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 21494 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21495 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21496 int user = mSettings.mPreferredActivities.keyAt(i); 21497 if (pir.dump(pw, 21498 dumpState.getTitlePrinted() 21499 ? "\nPreferred Activities User " + user + ":" 21500 : "Preferred Activities User " + user + ":", " ", 21501 packageName, true, false)) { 21502 dumpState.setTitlePrinted(true); 21503 } 21504 } 21505 } 21506 21507 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 21508 pw.flush(); 21509 FileOutputStream fout = new FileOutputStream(fd); 21510 BufferedOutputStream str = new BufferedOutputStream(fout); 21511 XmlSerializer serializer = new FastXmlSerializer(); 21512 try { 21513 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 21514 serializer.startDocument(null, true); 21515 serializer.setFeature( 21516 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 21517 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 21518 serializer.endDocument(); 21519 serializer.flush(); 21520 } catch (IllegalArgumentException e) { 21521 pw.println("Failed writing: " + e); 21522 } catch (IllegalStateException e) { 21523 pw.println("Failed writing: " + e); 21524 } catch (IOException e) { 21525 pw.println("Failed writing: " + e); 21526 } 21527 } 21528 21529 if (!checkin 21530 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 21531 && packageName == null) { 21532 pw.println(); 21533 int count = mSettings.mPackages.size(); 21534 if (count == 0) { 21535 pw.println("No applications!"); 21536 pw.println(); 21537 } else { 21538 final String prefix = " "; 21539 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 21540 if (allPackageSettings.size() == 0) { 21541 pw.println("No domain preferred apps!"); 21542 pw.println(); 21543 } else { 21544 pw.println("App verification status:"); 21545 pw.println(); 21546 count = 0; 21547 for (PackageSetting ps : allPackageSettings) { 21548 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 21549 if (ivi == null || ivi.getPackageName() == null) continue; 21550 pw.println(prefix + "Package: " + ivi.getPackageName()); 21551 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 21552 pw.println(prefix + "Status: " + ivi.getStatusString()); 21553 pw.println(); 21554 count++; 21555 } 21556 if (count == 0) { 21557 pw.println(prefix + "No app verification established."); 21558 pw.println(); 21559 } 21560 for (int userId : sUserManager.getUserIds()) { 21561 pw.println("App linkages for user " + userId + ":"); 21562 pw.println(); 21563 count = 0; 21564 for (PackageSetting ps : allPackageSettings) { 21565 final long status = ps.getDomainVerificationStatusForUser(userId); 21566 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 21567 && !DEBUG_DOMAIN_VERIFICATION) { 21568 continue; 21569 } 21570 pw.println(prefix + "Package: " + ps.name); 21571 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 21572 String statusStr = IntentFilterVerificationInfo. 21573 getStatusStringFromValue(status); 21574 pw.println(prefix + "Status: " + statusStr); 21575 pw.println(); 21576 count++; 21577 } 21578 if (count == 0) { 21579 pw.println(prefix + "No configured app linkages."); 21580 pw.println(); 21581 } 21582 } 21583 } 21584 } 21585 } 21586 21587 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 21588 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 21589 } 21590 21591 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 21592 boolean printedSomething = false; 21593 for (PackageParser.Provider p : mProviders.mProviders.values()) { 21594 if (packageName != null && !packageName.equals(p.info.packageName)) { 21595 continue; 21596 } 21597 if (!printedSomething) { 21598 if (dumpState.onTitlePrinted()) 21599 pw.println(); 21600 pw.println("Registered ContentProviders:"); 21601 printedSomething = true; 21602 } 21603 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 21604 pw.print(" "); pw.println(p.toString()); 21605 } 21606 printedSomething = false; 21607 for (Map.Entry<String, PackageParser.Provider> entry : 21608 mProvidersByAuthority.entrySet()) { 21609 PackageParser.Provider p = entry.getValue(); 21610 if (packageName != null && !packageName.equals(p.info.packageName)) { 21611 continue; 21612 } 21613 if (!printedSomething) { 21614 if (dumpState.onTitlePrinted()) 21615 pw.println(); 21616 pw.println("ContentProvider Authorities:"); 21617 printedSomething = true; 21618 } 21619 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 21620 pw.print(" "); pw.println(p.toString()); 21621 if (p.info != null && p.info.applicationInfo != null) { 21622 final String appInfo = p.info.applicationInfo.toString(); 21623 pw.print(" applicationInfo="); pw.println(appInfo); 21624 } 21625 } 21626 } 21627 21628 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 21629 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 21630 } 21631 21632 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 21633 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 21634 } 21635 21636 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 21637 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 21638 } 21639 21640 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 21641 if (dumpState.onTitlePrinted()) pw.println(); 21642 pw.println("Package Changes:"); 21643 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 21644 final int K = mChangedPackages.size(); 21645 for (int i = 0; i < K; i++) { 21646 final SparseArray<String> changes = mChangedPackages.valueAt(i); 21647 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 21648 final int N = changes.size(); 21649 if (N == 0) { 21650 pw.print(" "); pw.println("No packages changed"); 21651 } else { 21652 for (int j = 0; j < N; j++) { 21653 final String pkgName = changes.valueAt(j); 21654 final int sequenceNumber = changes.keyAt(j); 21655 pw.print(" "); 21656 pw.print("seq="); 21657 pw.print(sequenceNumber); 21658 pw.print(", package="); 21659 pw.println(pkgName); 21660 } 21661 } 21662 } 21663 } 21664 21665 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 21666 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 21667 } 21668 21669 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21670 // XXX should handle packageName != null by dumping only install data that 21671 // the given package is involved with. 21672 if (dumpState.onTitlePrinted()) pw.println(); 21673 21674 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21675 ipw.println(); 21676 ipw.println("Frozen packages:"); 21677 ipw.increaseIndent(); 21678 if (mFrozenPackages.size() == 0) { 21679 ipw.println("(none)"); 21680 } else { 21681 for (int i = 0; i < mFrozenPackages.size(); i++) { 21682 ipw.println(mFrozenPackages.valueAt(i)); 21683 } 21684 } 21685 ipw.decreaseIndent(); 21686 } 21687 21688 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 21689 if (dumpState.onTitlePrinted()) pw.println(); 21690 21691 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21692 ipw.println(); 21693 ipw.println("Loaded volumes:"); 21694 ipw.increaseIndent(); 21695 if (mLoadedVolumes.size() == 0) { 21696 ipw.println("(none)"); 21697 } else { 21698 for (int i = 0; i < mLoadedVolumes.size(); i++) { 21699 ipw.println(mLoadedVolumes.valueAt(i)); 21700 } 21701 } 21702 ipw.decreaseIndent(); 21703 } 21704 21705 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS) 21706 && packageName == null) { 21707 if (dumpState.onTitlePrinted()) pw.println(); 21708 pw.println("Service permissions:"); 21709 21710 final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator(); 21711 while (filterIterator.hasNext()) { 21712 final ServiceIntentInfo info = filterIterator.next(); 21713 final ServiceInfo serviceInfo = info.service.info; 21714 final String permission = serviceInfo.permission; 21715 if (permission != null) { 21716 pw.print(" "); 21717 pw.print(serviceInfo.getComponentName().flattenToShortString()); 21718 pw.print(": "); 21719 pw.println(permission); 21720 } 21721 } 21722 } 21723 21724 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21725 if (dumpState.onTitlePrinted()) pw.println(); 21726 dumpDexoptStateLPr(pw, packageName); 21727 } 21728 21729 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21730 if (dumpState.onTitlePrinted()) pw.println(); 21731 dumpCompilerStatsLPr(pw, packageName); 21732 } 21733 21734 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21735 if (dumpState.onTitlePrinted()) pw.println(); 21736 mSettings.dumpReadMessagesLPr(pw, dumpState); 21737 21738 pw.println(); 21739 pw.println("Package warning messages:"); 21740 dumpCriticalInfo(pw, null); 21741 } 21742 21743 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21744 dumpCriticalInfo(pw, "msg,"); 21745 } 21746 } 21747 21748 // PackageInstaller should be called outside of mPackages lock 21749 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21750 // XXX should handle packageName != null by dumping only install data that 21751 // the given package is involved with. 21752 if (dumpState.onTitlePrinted()) pw.println(); 21753 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21754 } 21755 } 21756 21757 private void dumpProto(FileDescriptor fd) { 21758 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21759 21760 synchronized (mPackages) { 21761 final long requiredVerifierPackageToken = 21762 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21763 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21764 proto.write( 21765 PackageServiceDumpProto.PackageShortProto.UID, 21766 getPackageUid( 21767 mRequiredVerifierPackage, 21768 MATCH_DEBUG_TRIAGED_MISSING, 21769 UserHandle.USER_SYSTEM)); 21770 proto.end(requiredVerifierPackageToken); 21771 21772 if (mIntentFilterVerifierComponent != null) { 21773 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21774 final long verifierPackageToken = 21775 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21776 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21777 proto.write( 21778 PackageServiceDumpProto.PackageShortProto.UID, 21779 getPackageUid( 21780 verifierPackageName, 21781 MATCH_DEBUG_TRIAGED_MISSING, 21782 UserHandle.USER_SYSTEM)); 21783 proto.end(verifierPackageToken); 21784 } 21785 21786 dumpSharedLibrariesProto(proto); 21787 dumpFeaturesProto(proto); 21788 mSettings.dumpPackagesProto(proto); 21789 mSettings.dumpSharedUsersProto(proto); 21790 dumpCriticalInfo(proto); 21791 } 21792 proto.flush(); 21793 } 21794 21795 private void dumpFeaturesProto(ProtoOutputStream proto) { 21796 synchronized (mAvailableFeatures) { 21797 final int count = mAvailableFeatures.size(); 21798 for (int i = 0; i < count; i++) { 21799 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES); 21800 } 21801 } 21802 } 21803 21804 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21805 final int count = mSharedLibraries.size(); 21806 for (int i = 0; i < count; i++) { 21807 final String libName = mSharedLibraries.keyAt(i); 21808 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21809 if (versionedLib == null) { 21810 continue; 21811 } 21812 final int versionCount = versionedLib.size(); 21813 for (int j = 0; j < versionCount; j++) { 21814 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21815 final long sharedLibraryToken = 21816 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21817 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21818 final boolean isJar = (libEntry.path != null); 21819 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21820 if (isJar) { 21821 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21822 } else { 21823 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21824 } 21825 proto.end(sharedLibraryToken); 21826 } 21827 } 21828 } 21829 21830 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21831 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21832 ipw.println(); 21833 ipw.println("Dexopt state:"); 21834 ipw.increaseIndent(); 21835 Collection<PackageParser.Package> packages = null; 21836 if (packageName != null) { 21837 PackageParser.Package targetPackage = mPackages.get(packageName); 21838 if (targetPackage != null) { 21839 packages = Collections.singletonList(targetPackage); 21840 } else { 21841 ipw.println("Unable to find package: " + packageName); 21842 return; 21843 } 21844 } else { 21845 packages = mPackages.values(); 21846 } 21847 21848 for (PackageParser.Package pkg : packages) { 21849 ipw.println("[" + pkg.packageName + "]"); 21850 ipw.increaseIndent(); 21851 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 21852 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 21853 ipw.decreaseIndent(); 21854 } 21855 } 21856 21857 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21858 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21859 ipw.println(); 21860 ipw.println("Compiler stats:"); 21861 ipw.increaseIndent(); 21862 Collection<PackageParser.Package> packages = null; 21863 if (packageName != null) { 21864 PackageParser.Package targetPackage = mPackages.get(packageName); 21865 if (targetPackage != null) { 21866 packages = Collections.singletonList(targetPackage); 21867 } else { 21868 ipw.println("Unable to find package: " + packageName); 21869 return; 21870 } 21871 } else { 21872 packages = mPackages.values(); 21873 } 21874 21875 for (PackageParser.Package pkg : packages) { 21876 ipw.println("[" + pkg.packageName + "]"); 21877 ipw.increaseIndent(); 21878 21879 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21880 if (stats == null) { 21881 ipw.println("(No recorded stats)"); 21882 } else { 21883 stats.dump(ipw); 21884 } 21885 ipw.decreaseIndent(); 21886 } 21887 } 21888 21889 private String dumpDomainString(String packageName) { 21890 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21891 .getList(); 21892 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21893 21894 ArraySet<String> result = new ArraySet<>(); 21895 if (iviList.size() > 0) { 21896 for (IntentFilterVerificationInfo ivi : iviList) { 21897 for (String host : ivi.getDomains()) { 21898 result.add(host); 21899 } 21900 } 21901 } 21902 if (filters != null && filters.size() > 0) { 21903 for (IntentFilter filter : filters) { 21904 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21905 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21906 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21907 result.addAll(filter.getHostsList()); 21908 } 21909 } 21910 } 21911 21912 StringBuilder sb = new StringBuilder(result.size() * 16); 21913 for (String domain : result) { 21914 if (sb.length() > 0) sb.append(" "); 21915 sb.append(domain); 21916 } 21917 return sb.toString(); 21918 } 21919 21920 // ------- apps on sdcard specific code ------- 21921 static final boolean DEBUG_SD_INSTALL = false; 21922 21923 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21924 21925 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21926 21927 private boolean mMediaMounted = false; 21928 21929 static String getEncryptKey() { 21930 try { 21931 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21932 SD_ENCRYPTION_KEYSTORE_NAME); 21933 if (sdEncKey == null) { 21934 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21935 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21936 if (sdEncKey == null) { 21937 Slog.e(TAG, "Failed to create encryption keys"); 21938 return null; 21939 } 21940 } 21941 return sdEncKey; 21942 } catch (NoSuchAlgorithmException nsae) { 21943 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21944 return null; 21945 } catch (IOException ioe) { 21946 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21947 return null; 21948 } 21949 } 21950 21951 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21952 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21953 final int size = infos.size(); 21954 final String[] packageNames = new String[size]; 21955 final int[] packageUids = new int[size]; 21956 for (int i = 0; i < size; i++) { 21957 final ApplicationInfo info = infos.get(i); 21958 packageNames[i] = info.packageName; 21959 packageUids[i] = info.uid; 21960 } 21961 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21962 finishedReceiver); 21963 } 21964 21965 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21966 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21967 sendResourcesChangedBroadcast(mediaStatus, replacing, 21968 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21969 } 21970 21971 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21972 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21973 int size = pkgList.length; 21974 if (size > 0) { 21975 // Send broadcasts here 21976 Bundle extras = new Bundle(); 21977 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21978 if (uidArr != null) { 21979 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21980 } 21981 if (replacing) { 21982 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21983 } 21984 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21985 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21986 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null); 21987 } 21988 } 21989 21990 private void loadPrivatePackages(final VolumeInfo vol) { 21991 mHandler.post(new Runnable() { 21992 @Override 21993 public void run() { 21994 loadPrivatePackagesInner(vol); 21995 } 21996 }); 21997 } 21998 21999 private void loadPrivatePackagesInner(VolumeInfo vol) { 22000 final String volumeUuid = vol.fsUuid; 22001 if (TextUtils.isEmpty(volumeUuid)) { 22002 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 22003 return; 22004 } 22005 22006 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 22007 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 22008 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 22009 22010 final VersionInfo ver; 22011 final List<PackageSetting> packages; 22012 synchronized (mPackages) { 22013 ver = mSettings.findOrCreateVersion(volumeUuid); 22014 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22015 } 22016 22017 for (PackageSetting ps : packages) { 22018 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 22019 synchronized (mInstallLock) { 22020 final PackageParser.Package pkg; 22021 try { 22022 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 22023 loaded.add(pkg.applicationInfo); 22024 22025 } catch (PackageManagerException e) { 22026 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 22027 } 22028 22029 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 22030 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 22031 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 22032 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 22033 } 22034 } 22035 } 22036 22037 // Reconcile app data for all started/unlocked users 22038 final StorageManager sm = mContext.getSystemService(StorageManager.class); 22039 final UserManager um = mContext.getSystemService(UserManager.class); 22040 UserManagerInternal umInternal = getUserManagerInternal(); 22041 for (UserInfo user : um.getUsers()) { 22042 final int flags; 22043 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22044 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22045 } else if (umInternal.isUserRunning(user.id)) { 22046 flags = StorageManager.FLAG_STORAGE_DE; 22047 } else { 22048 continue; 22049 } 22050 22051 try { 22052 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 22053 synchronized (mInstallLock) { 22054 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 22055 } 22056 } catch (IllegalStateException e) { 22057 // Device was probably ejected, and we'll process that event momentarily 22058 Slog.w(TAG, "Failed to prepare storage: " + e); 22059 } 22060 } 22061 22062 synchronized (mPackages) { 22063 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 22064 if (sdkUpdated) { 22065 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 22066 + mSdkVersion + "; regranting permissions for " + volumeUuid); 22067 } 22068 mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(), 22069 mPermissionCallback); 22070 22071 // Yay, everything is now upgraded 22072 ver.forceCurrent(); 22073 22074 mSettings.writeLPr(); 22075 } 22076 22077 for (PackageFreezer freezer : freezers) { 22078 freezer.close(); 22079 } 22080 22081 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 22082 sendResourcesChangedBroadcast(true, false, loaded, null); 22083 mLoadedVolumes.add(vol.getId()); 22084 } 22085 22086 private void unloadPrivatePackages(final VolumeInfo vol) { 22087 mHandler.post(new Runnable() { 22088 @Override 22089 public void run() { 22090 unloadPrivatePackagesInner(vol); 22091 } 22092 }); 22093 } 22094 22095 private void unloadPrivatePackagesInner(VolumeInfo vol) { 22096 final String volumeUuid = vol.fsUuid; 22097 if (TextUtils.isEmpty(volumeUuid)) { 22098 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 22099 return; 22100 } 22101 22102 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 22103 synchronized (mInstallLock) { 22104 synchronized (mPackages) { 22105 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 22106 for (PackageSetting ps : packages) { 22107 if (ps.pkg == null) continue; 22108 22109 final ApplicationInfo info = ps.pkg.applicationInfo; 22110 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 22111 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 22112 22113 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 22114 "unloadPrivatePackagesInner")) { 22115 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 22116 false, null)) { 22117 unloaded.add(info); 22118 } else { 22119 Slog.w(TAG, "Failed to unload " + ps.codePath); 22120 } 22121 } 22122 22123 // Try very hard to release any references to this package 22124 // so we don't risk the system server being killed due to 22125 // open FDs 22126 AttributeCache.instance().removePackage(ps.name); 22127 } 22128 22129 mSettings.writeLPr(); 22130 } 22131 } 22132 22133 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 22134 sendResourcesChangedBroadcast(false, false, unloaded, null); 22135 mLoadedVolumes.remove(vol.getId()); 22136 22137 // Try very hard to release any references to this path so we don't risk 22138 // the system server being killed due to open FDs 22139 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 22140 22141 for (int i = 0; i < 3; i++) { 22142 System.gc(); 22143 System.runFinalization(); 22144 } 22145 } 22146 22147 private void assertPackageKnown(String volumeUuid, String packageName) 22148 throws PackageManagerException { 22149 synchronized (mPackages) { 22150 // Normalize package name to handle renamed packages 22151 packageName = normalizePackageNameLPr(packageName); 22152 22153 final PackageSetting ps = mSettings.mPackages.get(packageName); 22154 if (ps == null) { 22155 throw new PackageManagerException("Package " + packageName + " is unknown"); 22156 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 22157 throw new PackageManagerException( 22158 "Package " + packageName + " found on unknown volume " + volumeUuid 22159 + "; expected volume " + ps.volumeUuid); 22160 } 22161 } 22162 } 22163 22164 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 22165 throws PackageManagerException { 22166 synchronized (mPackages) { 22167 // Normalize package name to handle renamed packages 22168 packageName = normalizePackageNameLPr(packageName); 22169 22170 final PackageSetting ps = mSettings.mPackages.get(packageName); 22171 if (ps == null) { 22172 throw new PackageManagerException("Package " + packageName + " is unknown"); 22173 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 22174 throw new PackageManagerException( 22175 "Package " + packageName + " found on unknown volume " + volumeUuid 22176 + "; expected volume " + ps.volumeUuid); 22177 } else if (!ps.getInstalled(userId)) { 22178 throw new PackageManagerException( 22179 "Package " + packageName + " not installed for user " + userId); 22180 } 22181 } 22182 } 22183 22184 private List<String> collectAbsoluteCodePaths() { 22185 synchronized (mPackages) { 22186 List<String> codePaths = new ArrayList<>(); 22187 final int packageCount = mSettings.mPackages.size(); 22188 for (int i = 0; i < packageCount; i++) { 22189 final PackageSetting ps = mSettings.mPackages.valueAt(i); 22190 codePaths.add(ps.codePath.getAbsolutePath()); 22191 } 22192 return codePaths; 22193 } 22194 } 22195 22196 /** 22197 * Examine all apps present on given mounted volume, and destroy apps that 22198 * aren't expected, either due to uninstallation or reinstallation on 22199 * another volume. 22200 */ 22201 private void reconcileApps(String volumeUuid) { 22202 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 22203 List<File> filesToDelete = null; 22204 22205 final File[] files = FileUtils.listFilesOrEmpty( 22206 Environment.getDataAppDirectory(volumeUuid)); 22207 for (File file : files) { 22208 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 22209 && !PackageInstallerService.isStageName(file.getName()); 22210 if (!isPackage) { 22211 // Ignore entries which are not packages 22212 continue; 22213 } 22214 22215 String absolutePath = file.getAbsolutePath(); 22216 22217 boolean pathValid = false; 22218 final int absoluteCodePathCount = absoluteCodePaths.size(); 22219 for (int i = 0; i < absoluteCodePathCount; i++) { 22220 String absoluteCodePath = absoluteCodePaths.get(i); 22221 if (absolutePath.startsWith(absoluteCodePath)) { 22222 pathValid = true; 22223 break; 22224 } 22225 } 22226 22227 if (!pathValid) { 22228 if (filesToDelete == null) { 22229 filesToDelete = new ArrayList<>(); 22230 } 22231 filesToDelete.add(file); 22232 } 22233 } 22234 22235 if (filesToDelete != null) { 22236 final int fileToDeleteCount = filesToDelete.size(); 22237 for (int i = 0; i < fileToDeleteCount; i++) { 22238 File fileToDelete = filesToDelete.get(i); 22239 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 22240 synchronized (mInstallLock) { 22241 removeCodePathLI(fileToDelete); 22242 } 22243 } 22244 } 22245 } 22246 22247 /** 22248 * Reconcile all app data for the given user. 22249 * <p> 22250 * Verifies that directories exist and that ownership and labeling is 22251 * correct for all installed apps on all mounted volumes. 22252 */ 22253 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 22254 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22255 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 22256 final String volumeUuid = vol.getFsUuid(); 22257 synchronized (mInstallLock) { 22258 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 22259 } 22260 } 22261 } 22262 22263 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22264 boolean migrateAppData) { 22265 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 22266 } 22267 22268 /** 22269 * Reconcile all app data on given mounted volume. 22270 * <p> 22271 * Destroys app data that isn't expected, either due to uninstallation or 22272 * reinstallation on another volume. 22273 * <p> 22274 * Verifies that directories exist and that ownership and labeling is 22275 * correct for all installed apps. 22276 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 22277 */ 22278 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22279 boolean migrateAppData, boolean onlyCoreApps) { 22280 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 22281 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 22282 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 22283 22284 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 22285 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 22286 22287 // First look for stale data that doesn't belong, and check if things 22288 // have changed since we did our last restorecon 22289 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22290 if (StorageManager.isFileEncryptedNativeOrEmulated() 22291 && !StorageManager.isUserKeyUnlocked(userId)) { 22292 throw new RuntimeException( 22293 "Yikes, someone asked us to reconcile CE storage while " + userId 22294 + " was still locked; this would have caused massive data loss!"); 22295 } 22296 22297 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 22298 for (File file : files) { 22299 final String packageName = file.getName(); 22300 try { 22301 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22302 } catch (PackageManagerException e) { 22303 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22304 try { 22305 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22306 StorageManager.FLAG_STORAGE_CE, 0); 22307 } catch (InstallerException e2) { 22308 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22309 } 22310 } 22311 } 22312 } 22313 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 22314 final File[] files = FileUtils.listFilesOrEmpty(deDir); 22315 for (File file : files) { 22316 final String packageName = file.getName(); 22317 try { 22318 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22319 } catch (PackageManagerException e) { 22320 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22321 try { 22322 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22323 StorageManager.FLAG_STORAGE_DE, 0); 22324 } catch (InstallerException e2) { 22325 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22326 } 22327 } 22328 } 22329 } 22330 22331 // Ensure that data directories are ready to roll for all packages 22332 // installed for this volume and user 22333 final List<PackageSetting> packages; 22334 synchronized (mPackages) { 22335 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22336 } 22337 int preparedCount = 0; 22338 for (PackageSetting ps : packages) { 22339 final String packageName = ps.name; 22340 if (ps.pkg == null) { 22341 Slog.w(TAG, "Odd, missing scanned package " + packageName); 22342 // TODO: might be due to legacy ASEC apps; we should circle back 22343 // and reconcile again once they're scanned 22344 continue; 22345 } 22346 // Skip non-core apps if requested 22347 if (onlyCoreApps && !ps.pkg.coreApp) { 22348 result.add(packageName); 22349 continue; 22350 } 22351 22352 if (ps.getInstalled(userId)) { 22353 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 22354 preparedCount++; 22355 } 22356 } 22357 22358 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 22359 return result; 22360 } 22361 22362 /** 22363 * Prepare app data for the given app just after it was installed or 22364 * upgraded. This method carefully only touches users that it's installed 22365 * for, and it forces a restorecon to handle any seinfo changes. 22366 * <p> 22367 * Verifies that directories exist and that ownership and labeling is 22368 * correct for all installed apps. If there is an ownership mismatch, it 22369 * will try recovering system apps by wiping data; third-party app data is 22370 * left intact. 22371 * <p> 22372 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 22373 */ 22374 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 22375 final PackageSetting ps; 22376 synchronized (mPackages) { 22377 ps = mSettings.mPackages.get(pkg.packageName); 22378 mSettings.writeKernelMappingLPr(ps); 22379 } 22380 22381 final UserManager um = mContext.getSystemService(UserManager.class); 22382 UserManagerInternal umInternal = getUserManagerInternal(); 22383 for (UserInfo user : um.getUsers()) { 22384 final int flags; 22385 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22386 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22387 } else if (umInternal.isUserRunning(user.id)) { 22388 flags = StorageManager.FLAG_STORAGE_DE; 22389 } else { 22390 continue; 22391 } 22392 22393 if (ps.getInstalled(user.id)) { 22394 // TODO: when user data is locked, mark that we're still dirty 22395 prepareAppDataLIF(pkg, user.id, flags); 22396 } 22397 } 22398 } 22399 22400 /** 22401 * Prepare app data for the given app. 22402 * <p> 22403 * Verifies that directories exist and that ownership and labeling is 22404 * correct for all installed apps. If there is an ownership mismatch, this 22405 * will try recovering system apps by wiping data; third-party app data is 22406 * left intact. 22407 */ 22408 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 22409 if (pkg == null) { 22410 Slog.wtf(TAG, "Package was null!", new Throwable()); 22411 return; 22412 } 22413 prepareAppDataLeafLIF(pkg, userId, flags); 22414 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22415 for (int i = 0; i < childCount; i++) { 22416 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 22417 } 22418 } 22419 22420 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 22421 boolean maybeMigrateAppData) { 22422 prepareAppDataLIF(pkg, userId, flags); 22423 22424 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 22425 // We may have just shuffled around app data directories, so 22426 // prepare them one more time 22427 prepareAppDataLIF(pkg, userId, flags); 22428 } 22429 } 22430 22431 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22432 if (DEBUG_APP_DATA) { 22433 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 22434 + Integer.toHexString(flags)); 22435 } 22436 22437 final PackageSetting ps; 22438 synchronized (mPackages) { 22439 ps = mSettings.mPackages.get(pkg.packageName); 22440 } 22441 final String volumeUuid = pkg.volumeUuid; 22442 final String packageName = pkg.packageName; 22443 final ApplicationInfo app = (ps == null) 22444 ? pkg.applicationInfo 22445 : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId); 22446 22447 final int appId = UserHandle.getAppId(app.uid); 22448 22449 Preconditions.checkNotNull(app.seInfo); 22450 22451 final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : ""); 22452 long ceDataInode = -1; 22453 try { 22454 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22455 appId, seInfo, app.targetSdkVersion); 22456 } catch (InstallerException e) { 22457 if (app.isSystemApp()) { 22458 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 22459 + ", but trying to recover: " + e); 22460 destroyAppDataLeafLIF(pkg, userId, flags); 22461 try { 22462 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22463 appId, seInfo, app.targetSdkVersion); 22464 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 22465 } catch (InstallerException e2) { 22466 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 22467 } 22468 } else { 22469 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22470 } 22471 } 22472 // Prepare the application profiles only for upgrades and first boot (so that we don't 22473 // repeat the same operation at each boot). 22474 // We only have to cover the upgrade and first boot here because for app installs we 22475 // prepare the profiles before invoking dexopt (in installPackageLI). 22476 // 22477 // We also have to cover non system users because we do not call the usual install package 22478 // methods for them. 22479 if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) { 22480 mArtManagerService.prepareAppProfiles(pkg, userId); 22481 } 22482 22483 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22484 // TODO: mark this structure as dirty so we persist it! 22485 synchronized (mPackages) { 22486 if (ps != null) { 22487 ps.setCeDataInode(ceDataInode, userId); 22488 } 22489 } 22490 } 22491 22492 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22493 } 22494 22495 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22496 if (pkg == null) { 22497 Slog.wtf(TAG, "Package was null!", new Throwable()); 22498 return; 22499 } 22500 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22501 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22502 for (int i = 0; i < childCount; i++) { 22503 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22504 } 22505 } 22506 22507 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22508 final String volumeUuid = pkg.volumeUuid; 22509 final String packageName = pkg.packageName; 22510 final ApplicationInfo app = pkg.applicationInfo; 22511 22512 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22513 // Create a native library symlink only if we have native libraries 22514 // and if the native libraries are 32 bit libraries. We do not provide 22515 // this symlink for 64 bit libraries. 22516 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22517 final String nativeLibPath = app.nativeLibraryDir; 22518 try { 22519 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22520 nativeLibPath, userId); 22521 } catch (InstallerException e) { 22522 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22523 } 22524 } 22525 } 22526 } 22527 22528 /** 22529 * For system apps on non-FBE devices, this method migrates any existing 22530 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22531 * requested by the app. 22532 */ 22533 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22534 if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated() 22535 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22536 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22537 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22538 try { 22539 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22540 storageTarget); 22541 } catch (InstallerException e) { 22542 logCriticalInfo(Log.WARN, 22543 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22544 } 22545 return true; 22546 } else { 22547 return false; 22548 } 22549 } 22550 22551 public PackageFreezer freezePackage(String packageName, String killReason) { 22552 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22553 } 22554 22555 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22556 return new PackageFreezer(packageName, userId, killReason); 22557 } 22558 22559 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22560 String killReason) { 22561 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22562 } 22563 22564 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22565 String killReason) { 22566 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22567 return new PackageFreezer(); 22568 } else { 22569 return freezePackage(packageName, userId, killReason); 22570 } 22571 } 22572 22573 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22574 String killReason) { 22575 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22576 } 22577 22578 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22579 String killReason) { 22580 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22581 return new PackageFreezer(); 22582 } else { 22583 return freezePackage(packageName, userId, killReason); 22584 } 22585 } 22586 22587 /** 22588 * Class that freezes and kills the given package upon creation, and 22589 * unfreezes it upon closing. This is typically used when doing surgery on 22590 * app code/data to prevent the app from running while you're working. 22591 */ 22592 private class PackageFreezer implements AutoCloseable { 22593 private final String mPackageName; 22594 private final PackageFreezer[] mChildren; 22595 22596 private final boolean mWeFroze; 22597 22598 private final AtomicBoolean mClosed = new AtomicBoolean(); 22599 private final CloseGuard mCloseGuard = CloseGuard.get(); 22600 22601 /** 22602 * Create and return a stub freezer that doesn't actually do anything, 22603 * typically used when someone requested 22604 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22605 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22606 */ 22607 public PackageFreezer() { 22608 mPackageName = null; 22609 mChildren = null; 22610 mWeFroze = false; 22611 mCloseGuard.open("close"); 22612 } 22613 22614 public PackageFreezer(String packageName, int userId, String killReason) { 22615 synchronized (mPackages) { 22616 mPackageName = packageName; 22617 mWeFroze = mFrozenPackages.add(mPackageName); 22618 22619 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22620 if (ps != null) { 22621 killApplication(ps.name, ps.appId, userId, killReason); 22622 } 22623 22624 final PackageParser.Package p = mPackages.get(packageName); 22625 if (p != null && p.childPackages != null) { 22626 final int N = p.childPackages.size(); 22627 mChildren = new PackageFreezer[N]; 22628 for (int i = 0; i < N; i++) { 22629 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22630 userId, killReason); 22631 } 22632 } else { 22633 mChildren = null; 22634 } 22635 } 22636 mCloseGuard.open("close"); 22637 } 22638 22639 @Override 22640 protected void finalize() throws Throwable { 22641 try { 22642 if (mCloseGuard != null) { 22643 mCloseGuard.warnIfOpen(); 22644 } 22645 22646 close(); 22647 } finally { 22648 super.finalize(); 22649 } 22650 } 22651 22652 @Override 22653 public void close() { 22654 mCloseGuard.close(); 22655 if (mClosed.compareAndSet(false, true)) { 22656 synchronized (mPackages) { 22657 if (mWeFroze) { 22658 mFrozenPackages.remove(mPackageName); 22659 } 22660 22661 if (mChildren != null) { 22662 for (PackageFreezer freezer : mChildren) { 22663 freezer.close(); 22664 } 22665 } 22666 } 22667 } 22668 } 22669 } 22670 22671 /** 22672 * Verify that given package is currently frozen. 22673 */ 22674 private void checkPackageFrozen(String packageName) { 22675 synchronized (mPackages) { 22676 if (!mFrozenPackages.contains(packageName)) { 22677 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22678 } 22679 } 22680 } 22681 22682 @Override 22683 public int movePackage(final String packageName, final String volumeUuid) { 22684 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22685 22686 final int callingUid = Binder.getCallingUid(); 22687 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 22688 final int moveId = mNextMoveId.getAndIncrement(); 22689 mHandler.post(new Runnable() { 22690 @Override 22691 public void run() { 22692 try { 22693 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 22694 } catch (PackageManagerException e) { 22695 Slog.w(TAG, "Failed to move " + packageName, e); 22696 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 22697 } 22698 } 22699 }); 22700 return moveId; 22701 } 22702 22703 private void movePackageInternal(final String packageName, final String volumeUuid, 22704 final int moveId, final int callingUid, UserHandle user) 22705 throws PackageManagerException { 22706 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22707 final PackageManager pm = mContext.getPackageManager(); 22708 22709 final boolean currentAsec; 22710 final String currentVolumeUuid; 22711 final File codeFile; 22712 final String installerPackageName; 22713 final String packageAbiOverride; 22714 final int appId; 22715 final String seinfo; 22716 final String label; 22717 final int targetSdkVersion; 22718 final PackageFreezer freezer; 22719 final int[] installedUserIds; 22720 22721 // reader 22722 synchronized (mPackages) { 22723 final PackageParser.Package pkg = mPackages.get(packageName); 22724 final PackageSetting ps = mSettings.mPackages.get(packageName); 22725 if (pkg == null 22726 || ps == null 22727 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 22728 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22729 } 22730 if (pkg.applicationInfo.isSystemApp()) { 22731 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22732 "Cannot move system application"); 22733 } 22734 22735 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22736 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22737 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22738 if (isInternalStorage && !allow3rdPartyOnInternal) { 22739 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22740 "3rd party apps are not allowed on internal storage"); 22741 } 22742 22743 if (pkg.applicationInfo.isExternalAsec()) { 22744 currentAsec = true; 22745 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22746 } else if (pkg.applicationInfo.isForwardLocked()) { 22747 currentAsec = true; 22748 currentVolumeUuid = "forward_locked"; 22749 } else { 22750 currentAsec = false; 22751 currentVolumeUuid = ps.volumeUuid; 22752 22753 final File probe = new File(pkg.codePath); 22754 final File probeOat = new File(probe, "oat"); 22755 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22756 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22757 "Move only supported for modern cluster style installs"); 22758 } 22759 } 22760 22761 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22762 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22763 "Package already moved to " + volumeUuid); 22764 } 22765 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22766 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22767 "Device admin cannot be moved"); 22768 } 22769 22770 if (mFrozenPackages.contains(packageName)) { 22771 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22772 "Failed to move already frozen package"); 22773 } 22774 22775 codeFile = new File(pkg.codePath); 22776 installerPackageName = ps.installerPackageName; 22777 packageAbiOverride = ps.cpuAbiOverrideString; 22778 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22779 seinfo = pkg.applicationInfo.seInfo; 22780 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22781 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22782 freezer = freezePackage(packageName, "movePackageInternal"); 22783 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22784 } 22785 22786 final Bundle extras = new Bundle(); 22787 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22788 extras.putString(Intent.EXTRA_TITLE, label); 22789 mMoveCallbacks.notifyCreated(moveId, extras); 22790 22791 int installFlags; 22792 final boolean moveCompleteApp; 22793 final File measurePath; 22794 22795 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22796 installFlags = INSTALL_INTERNAL; 22797 moveCompleteApp = !currentAsec; 22798 measurePath = Environment.getDataAppDirectory(volumeUuid); 22799 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22800 installFlags = INSTALL_EXTERNAL; 22801 moveCompleteApp = false; 22802 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22803 } else { 22804 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22805 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22806 || !volume.isMountedWritable()) { 22807 freezer.close(); 22808 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22809 "Move location not mounted private volume"); 22810 } 22811 22812 Preconditions.checkState(!currentAsec); 22813 22814 installFlags = INSTALL_INTERNAL; 22815 moveCompleteApp = true; 22816 measurePath = Environment.getDataAppDirectory(volumeUuid); 22817 } 22818 22819 // If we're moving app data around, we need all the users unlocked 22820 if (moveCompleteApp) { 22821 for (int userId : installedUserIds) { 22822 if (StorageManager.isFileEncryptedNativeOrEmulated() 22823 && !StorageManager.isUserKeyUnlocked(userId)) { 22824 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 22825 "User " + userId + " must be unlocked"); 22826 } 22827 } 22828 } 22829 22830 final PackageStats stats = new PackageStats(null, -1); 22831 synchronized (mInstaller) { 22832 for (int userId : installedUserIds) { 22833 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22834 freezer.close(); 22835 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22836 "Failed to measure package size"); 22837 } 22838 } 22839 } 22840 22841 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22842 + stats.dataSize); 22843 22844 final long startFreeBytes = measurePath.getUsableSpace(); 22845 final long sizeBytes; 22846 if (moveCompleteApp) { 22847 sizeBytes = stats.codeSize + stats.dataSize; 22848 } else { 22849 sizeBytes = stats.codeSize; 22850 } 22851 22852 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22853 freezer.close(); 22854 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22855 "Not enough free space to move"); 22856 } 22857 22858 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22859 22860 final CountDownLatch installedLatch = new CountDownLatch(1); 22861 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22862 @Override 22863 public void onUserActionRequired(Intent intent) throws RemoteException { 22864 throw new IllegalStateException(); 22865 } 22866 22867 @Override 22868 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22869 Bundle extras) throws RemoteException { 22870 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22871 + PackageManager.installStatusToString(returnCode, msg)); 22872 22873 installedLatch.countDown(); 22874 freezer.close(); 22875 22876 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22877 switch (status) { 22878 case PackageInstaller.STATUS_SUCCESS: 22879 mMoveCallbacks.notifyStatusChanged(moveId, 22880 PackageManager.MOVE_SUCCEEDED); 22881 break; 22882 case PackageInstaller.STATUS_FAILURE_STORAGE: 22883 mMoveCallbacks.notifyStatusChanged(moveId, 22884 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22885 break; 22886 default: 22887 mMoveCallbacks.notifyStatusChanged(moveId, 22888 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22889 break; 22890 } 22891 } 22892 }; 22893 22894 final MoveInfo move; 22895 if (moveCompleteApp) { 22896 // Kick off a thread to report progress estimates 22897 new Thread() { 22898 @Override 22899 public void run() { 22900 while (true) { 22901 try { 22902 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22903 break; 22904 } 22905 } catch (InterruptedException ignored) { 22906 } 22907 22908 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22909 final int progress = 10 + (int) MathUtils.constrain( 22910 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22911 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22912 } 22913 } 22914 }.start(); 22915 22916 final String dataAppName = codeFile.getName(); 22917 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22918 dataAppName, appId, seinfo, targetSdkVersion); 22919 } else { 22920 move = null; 22921 } 22922 22923 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22924 22925 final Message msg = mHandler.obtainMessage(INIT_COPY); 22926 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22927 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22928 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22929 packageAbiOverride, null /*grantedPermissions*/, 22930 PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN); 22931 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22932 msg.obj = params; 22933 22934 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22935 System.identityHashCode(msg.obj)); 22936 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22937 System.identityHashCode(msg.obj)); 22938 22939 mHandler.sendMessage(msg); 22940 } 22941 22942 @Override 22943 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22944 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22945 22946 final int realMoveId = mNextMoveId.getAndIncrement(); 22947 final Bundle extras = new Bundle(); 22948 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22949 mMoveCallbacks.notifyCreated(realMoveId, extras); 22950 22951 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22952 @Override 22953 public void onCreated(int moveId, Bundle extras) { 22954 // Ignored 22955 } 22956 22957 @Override 22958 public void onStatusChanged(int moveId, int status, long estMillis) { 22959 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22960 } 22961 }; 22962 22963 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22964 storage.setPrimaryStorageUuid(volumeUuid, callback); 22965 return realMoveId; 22966 } 22967 22968 @Override 22969 public int getMoveStatus(int moveId) { 22970 mContext.enforceCallingOrSelfPermission( 22971 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22972 return mMoveCallbacks.mLastStatus.get(moveId); 22973 } 22974 22975 @Override 22976 public void registerMoveCallback(IPackageMoveObserver callback) { 22977 mContext.enforceCallingOrSelfPermission( 22978 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22979 mMoveCallbacks.register(callback); 22980 } 22981 22982 @Override 22983 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22984 mContext.enforceCallingOrSelfPermission( 22985 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22986 mMoveCallbacks.unregister(callback); 22987 } 22988 22989 @Override 22990 public boolean setInstallLocation(int loc) { 22991 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22992 null); 22993 if (getInstallLocation() == loc) { 22994 return true; 22995 } 22996 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22997 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22998 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22999 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 23000 return true; 23001 } 23002 return false; 23003 } 23004 23005 @Override 23006 public int getInstallLocation() { 23007 // allow instant app access 23008 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 23009 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 23010 PackageHelper.APP_INSTALL_AUTO); 23011 } 23012 23013 /** Called by UserManagerService */ 23014 void cleanUpUser(UserManagerService userManager, int userHandle) { 23015 synchronized (mPackages) { 23016 mDirtyUsers.remove(userHandle); 23017 mUserNeedsBadging.delete(userHandle); 23018 mSettings.removeUserLPw(userHandle); 23019 mPendingBroadcasts.remove(userHandle); 23020 mInstantAppRegistry.onUserRemovedLPw(userHandle); 23021 removeUnusedPackagesLPw(userManager, userHandle); 23022 } 23023 } 23024 23025 /** 23026 * We're removing userHandle and would like to remove any downloaded packages 23027 * that are no longer in use by any other user. 23028 * @param userHandle the user being removed 23029 */ 23030 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 23031 final boolean DEBUG_CLEAN_APKS = false; 23032 int [] users = userManager.getUserIds(); 23033 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 23034 while (psit.hasNext()) { 23035 PackageSetting ps = psit.next(); 23036 if (ps.pkg == null) { 23037 continue; 23038 } 23039 final String packageName = ps.pkg.packageName; 23040 // Skip over if system app 23041 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 23042 continue; 23043 } 23044 if (DEBUG_CLEAN_APKS) { 23045 Slog.i(TAG, "Checking package " + packageName); 23046 } 23047 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 23048 if (keep) { 23049 if (DEBUG_CLEAN_APKS) { 23050 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 23051 } 23052 } else { 23053 for (int i = 0; i < users.length; i++) { 23054 if (users[i] != userHandle && ps.getInstalled(users[i])) { 23055 keep = true; 23056 if (DEBUG_CLEAN_APKS) { 23057 Slog.i(TAG, " Keeping package " + packageName + " for user " 23058 + users[i]); 23059 } 23060 break; 23061 } 23062 } 23063 } 23064 if (!keep) { 23065 if (DEBUG_CLEAN_APKS) { 23066 Slog.i(TAG, " Removing package " + packageName); 23067 } 23068 mHandler.post(new Runnable() { 23069 public void run() { 23070 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23071 userHandle, 0); 23072 } //end run 23073 }); 23074 } 23075 } 23076 } 23077 23078 /** Called by UserManagerService */ 23079 void createNewUser(int userId, String[] disallowedPackages) { 23080 synchronized (mInstallLock) { 23081 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 23082 } 23083 synchronized (mPackages) { 23084 scheduleWritePackageRestrictionsLocked(userId); 23085 scheduleWritePackageListLocked(userId); 23086 applyFactoryDefaultBrowserLPw(userId); 23087 primeDomainVerificationsLPw(userId); 23088 } 23089 } 23090 23091 void onNewUserCreated(final int userId) { 23092 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 23093 synchronized(mPackages) { 23094 // If permission review for legacy apps is required, we represent 23095 // dagerous permissions for such apps as always granted runtime 23096 // permissions to keep per user flag state whether review is needed. 23097 // Hence, if a new user is added we have to propagate dangerous 23098 // permission grants for these legacy apps. 23099 if (mSettings.mPermissions.mPermissionReviewRequired) { 23100// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG 23101 mPermissionManager.updateAllPermissions( 23102 StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(), 23103 mPermissionCallback); 23104 } 23105 } 23106 } 23107 23108 @Override 23109 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 23110 mContext.enforceCallingOrSelfPermission( 23111 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 23112 "Only package verification agents can read the verifier device identity"); 23113 23114 synchronized (mPackages) { 23115 return mSettings.getVerifierDeviceIdentityLPw(); 23116 } 23117 } 23118 23119 @Override 23120 public void setPermissionEnforced(String permission, boolean enforced) { 23121 // TODO: Now that we no longer change GID for storage, this should to away. 23122 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 23123 "setPermissionEnforced"); 23124 if (READ_EXTERNAL_STORAGE.equals(permission)) { 23125 synchronized (mPackages) { 23126 if (mSettings.mReadExternalStorageEnforced == null 23127 || mSettings.mReadExternalStorageEnforced != enforced) { 23128 mSettings.mReadExternalStorageEnforced = 23129 enforced ? Boolean.TRUE : Boolean.FALSE; 23130 mSettings.writeLPr(); 23131 } 23132 } 23133 // kill any non-foreground processes so we restart them and 23134 // grant/revoke the GID. 23135 final IActivityManager am = ActivityManager.getService(); 23136 if (am != null) { 23137 final long token = Binder.clearCallingIdentity(); 23138 try { 23139 am.killProcessesBelowForeground("setPermissionEnforcement"); 23140 } catch (RemoteException e) { 23141 } finally { 23142 Binder.restoreCallingIdentity(token); 23143 } 23144 } 23145 } else { 23146 throw new IllegalArgumentException("No selective enforcement for " + permission); 23147 } 23148 } 23149 23150 @Override 23151 @Deprecated 23152 public boolean isPermissionEnforced(String permission) { 23153 // allow instant applications 23154 return true; 23155 } 23156 23157 @Override 23158 public boolean isStorageLow() { 23159 // allow instant applications 23160 final long token = Binder.clearCallingIdentity(); 23161 try { 23162 final DeviceStorageMonitorInternal 23163 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 23164 if (dsm != null) { 23165 return dsm.isMemoryLow(); 23166 } else { 23167 return false; 23168 } 23169 } finally { 23170 Binder.restoreCallingIdentity(token); 23171 } 23172 } 23173 23174 @Override 23175 public IPackageInstaller getPackageInstaller() { 23176 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23177 return null; 23178 } 23179 return mInstallerService; 23180 } 23181 23182 @Override 23183 public IArtManager getArtManager() { 23184 return mArtManagerService; 23185 } 23186 23187 private boolean userNeedsBadging(int userId) { 23188 int index = mUserNeedsBadging.indexOfKey(userId); 23189 if (index < 0) { 23190 final UserInfo userInfo; 23191 final long token = Binder.clearCallingIdentity(); 23192 try { 23193 userInfo = sUserManager.getUserInfo(userId); 23194 } finally { 23195 Binder.restoreCallingIdentity(token); 23196 } 23197 final boolean b; 23198 if (userInfo != null && userInfo.isManagedProfile()) { 23199 b = true; 23200 } else { 23201 b = false; 23202 } 23203 mUserNeedsBadging.put(userId, b); 23204 return b; 23205 } 23206 return mUserNeedsBadging.valueAt(index); 23207 } 23208 23209 @Override 23210 public KeySet getKeySetByAlias(String packageName, String alias) { 23211 if (packageName == null || alias == null) { 23212 return null; 23213 } 23214 synchronized(mPackages) { 23215 final PackageParser.Package pkg = mPackages.get(packageName); 23216 if (pkg == null) { 23217 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23218 throw new IllegalArgumentException("Unknown package: " + packageName); 23219 } 23220 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23221 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 23222 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 23223 throw new IllegalArgumentException("Unknown package: " + packageName); 23224 } 23225 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23226 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 23227 } 23228 } 23229 23230 @Override 23231 public KeySet getSigningKeySet(String packageName) { 23232 if (packageName == null) { 23233 return null; 23234 } 23235 synchronized(mPackages) { 23236 final int callingUid = Binder.getCallingUid(); 23237 final int callingUserId = UserHandle.getUserId(callingUid); 23238 final PackageParser.Package pkg = mPackages.get(packageName); 23239 if (pkg == null) { 23240 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23241 throw new IllegalArgumentException("Unknown package: " + packageName); 23242 } 23243 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23244 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 23245 // filter and pretend the package doesn't exist 23246 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 23247 + ", uid:" + callingUid); 23248 throw new IllegalArgumentException("Unknown package: " + packageName); 23249 } 23250 if (pkg.applicationInfo.uid != callingUid 23251 && Process.SYSTEM_UID != callingUid) { 23252 throw new SecurityException("May not access signing KeySet of other apps."); 23253 } 23254 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23255 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 23256 } 23257 } 23258 23259 @Override 23260 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 23261 final int callingUid = Binder.getCallingUid(); 23262 if (getInstantAppPackageName(callingUid) != null) { 23263 return false; 23264 } 23265 if (packageName == null || ks == null) { 23266 return false; 23267 } 23268 synchronized(mPackages) { 23269 final PackageParser.Package pkg = mPackages.get(packageName); 23270 if (pkg == null 23271 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23272 UserHandle.getUserId(callingUid))) { 23273 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23274 throw new IllegalArgumentException("Unknown package: " + packageName); 23275 } 23276 IBinder ksh = ks.getToken(); 23277 if (ksh instanceof KeySetHandle) { 23278 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23279 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 23280 } 23281 return false; 23282 } 23283 } 23284 23285 @Override 23286 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 23287 final int callingUid = Binder.getCallingUid(); 23288 if (getInstantAppPackageName(callingUid) != null) { 23289 return false; 23290 } 23291 if (packageName == null || ks == null) { 23292 return false; 23293 } 23294 synchronized(mPackages) { 23295 final PackageParser.Package pkg = mPackages.get(packageName); 23296 if (pkg == null 23297 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23298 UserHandle.getUserId(callingUid))) { 23299 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23300 throw new IllegalArgumentException("Unknown package: " + packageName); 23301 } 23302 IBinder ksh = ks.getToken(); 23303 if (ksh instanceof KeySetHandle) { 23304 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23305 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 23306 } 23307 return false; 23308 } 23309 } 23310 23311 private void deletePackageIfUnusedLPr(final String packageName) { 23312 PackageSetting ps = mSettings.mPackages.get(packageName); 23313 if (ps == null) { 23314 return; 23315 } 23316 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 23317 // TODO Implement atomic delete if package is unused 23318 // It is currently possible that the package will be deleted even if it is installed 23319 // after this method returns. 23320 mHandler.post(new Runnable() { 23321 public void run() { 23322 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23323 0, PackageManager.DELETE_ALL_USERS); 23324 } 23325 }); 23326 } 23327 } 23328 23329 /** 23330 * Check and throw if the given before/after packages would be considered a 23331 * downgrade. 23332 */ 23333 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 23334 throws PackageManagerException { 23335 if (after.getLongVersionCode() < before.getLongVersionCode()) { 23336 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23337 "Update version code " + after.versionCode + " is older than current " 23338 + before.getLongVersionCode()); 23339 } else if (after.getLongVersionCode() == before.getLongVersionCode()) { 23340 if (after.baseRevisionCode < before.baseRevisionCode) { 23341 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23342 "Update base revision code " + after.baseRevisionCode 23343 + " is older than current " + before.baseRevisionCode); 23344 } 23345 23346 if (!ArrayUtils.isEmpty(after.splitNames)) { 23347 for (int i = 0; i < after.splitNames.length; i++) { 23348 final String splitName = after.splitNames[i]; 23349 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 23350 if (j != -1) { 23351 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 23352 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23353 "Update split " + splitName + " revision code " 23354 + after.splitRevisionCodes[i] + " is older than current " 23355 + before.splitRevisionCodes[j]); 23356 } 23357 } 23358 } 23359 } 23360 } 23361 } 23362 23363 private static class MoveCallbacks extends Handler { 23364 private static final int MSG_CREATED = 1; 23365 private static final int MSG_STATUS_CHANGED = 2; 23366 23367 private final RemoteCallbackList<IPackageMoveObserver> 23368 mCallbacks = new RemoteCallbackList<>(); 23369 23370 private final SparseIntArray mLastStatus = new SparseIntArray(); 23371 23372 public MoveCallbacks(Looper looper) { 23373 super(looper); 23374 } 23375 23376 public void register(IPackageMoveObserver callback) { 23377 mCallbacks.register(callback); 23378 } 23379 23380 public void unregister(IPackageMoveObserver callback) { 23381 mCallbacks.unregister(callback); 23382 } 23383 23384 @Override 23385 public void handleMessage(Message msg) { 23386 final SomeArgs args = (SomeArgs) msg.obj; 23387 final int n = mCallbacks.beginBroadcast(); 23388 for (int i = 0; i < n; i++) { 23389 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 23390 try { 23391 invokeCallback(callback, msg.what, args); 23392 } catch (RemoteException ignored) { 23393 } 23394 } 23395 mCallbacks.finishBroadcast(); 23396 args.recycle(); 23397 } 23398 23399 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 23400 throws RemoteException { 23401 switch (what) { 23402 case MSG_CREATED: { 23403 callback.onCreated(args.argi1, (Bundle) args.arg2); 23404 break; 23405 } 23406 case MSG_STATUS_CHANGED: { 23407 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 23408 break; 23409 } 23410 } 23411 } 23412 23413 private void notifyCreated(int moveId, Bundle extras) { 23414 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 23415 23416 final SomeArgs args = SomeArgs.obtain(); 23417 args.argi1 = moveId; 23418 args.arg2 = extras; 23419 obtainMessage(MSG_CREATED, args).sendToTarget(); 23420 } 23421 23422 private void notifyStatusChanged(int moveId, int status) { 23423 notifyStatusChanged(moveId, status, -1); 23424 } 23425 23426 private void notifyStatusChanged(int moveId, int status, long estMillis) { 23427 Slog.v(TAG, "Move " + moveId + " status " + status); 23428 23429 final SomeArgs args = SomeArgs.obtain(); 23430 args.argi1 = moveId; 23431 args.argi2 = status; 23432 args.arg3 = estMillis; 23433 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 23434 23435 synchronized (mLastStatus) { 23436 mLastStatus.put(moveId, status); 23437 } 23438 } 23439 } 23440 23441 private final static class OnPermissionChangeListeners extends Handler { 23442 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 23443 23444 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 23445 new RemoteCallbackList<>(); 23446 23447 public OnPermissionChangeListeners(Looper looper) { 23448 super(looper); 23449 } 23450 23451 @Override 23452 public void handleMessage(Message msg) { 23453 switch (msg.what) { 23454 case MSG_ON_PERMISSIONS_CHANGED: { 23455 final int uid = msg.arg1; 23456 handleOnPermissionsChanged(uid); 23457 } break; 23458 } 23459 } 23460 23461 public void addListenerLocked(IOnPermissionsChangeListener listener) { 23462 mPermissionListeners.register(listener); 23463 23464 } 23465 23466 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 23467 mPermissionListeners.unregister(listener); 23468 } 23469 23470 public void onPermissionsChanged(int uid) { 23471 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 23472 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 23473 } 23474 } 23475 23476 private void handleOnPermissionsChanged(int uid) { 23477 final int count = mPermissionListeners.beginBroadcast(); 23478 try { 23479 for (int i = 0; i < count; i++) { 23480 IOnPermissionsChangeListener callback = mPermissionListeners 23481 .getBroadcastItem(i); 23482 try { 23483 callback.onPermissionsChanged(uid); 23484 } catch (RemoteException e) { 23485 Log.e(TAG, "Permission listener is dead", e); 23486 } 23487 } 23488 } finally { 23489 mPermissionListeners.finishBroadcast(); 23490 } 23491 } 23492 } 23493 23494 private class PackageManagerNative extends IPackageManagerNative.Stub { 23495 @Override 23496 public String[] getNamesForUids(int[] uids) throws RemoteException { 23497 final String[] results = PackageManagerService.this.getNamesForUids(uids); 23498 // massage results so they can be parsed by the native binder 23499 for (int i = results.length - 1; i >= 0; --i) { 23500 if (results[i] == null) { 23501 results[i] = ""; 23502 } 23503 } 23504 return results; 23505 } 23506 23507 // NB: this differentiates between preloads and sideloads 23508 @Override 23509 public String getInstallerForPackage(String packageName) throws RemoteException { 23510 final String installerName = getInstallerPackageName(packageName); 23511 if (!TextUtils.isEmpty(installerName)) { 23512 return installerName; 23513 } 23514 // differentiate between preload and sideload 23515 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23516 ApplicationInfo appInfo = getApplicationInfo(packageName, 23517 /*flags*/ 0, 23518 /*userId*/ callingUser); 23519 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 23520 return "preload"; 23521 } 23522 return ""; 23523 } 23524 23525 @Override 23526 public long getVersionCodeForPackage(String packageName) throws RemoteException { 23527 try { 23528 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23529 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 23530 if (pInfo != null) { 23531 return pInfo.getLongVersionCode(); 23532 } 23533 } catch (Exception e) { 23534 } 23535 return 0; 23536 } 23537 } 23538 23539 private class PackageManagerInternalImpl extends PackageManagerInternal { 23540 @Override 23541 public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask, 23542 int flagValues, int userId) { 23543 PackageManagerService.this.updatePermissionFlags( 23544 permName, packageName, flagMask, flagValues, userId); 23545 } 23546 23547 @Override 23548 public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) { 23549 SigningDetails sd = getSigningDetails(packageName); 23550 if (sd == null) { 23551 return false; 23552 } 23553 return sd.hasSha256Certificate(restoringFromSigHash, 23554 SigningDetails.CertCapabilities.INSTALLED_DATA); 23555 } 23556 23557 @Override 23558 public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) { 23559 SigningDetails sd = getSigningDetails(packageName); 23560 if (sd == null) { 23561 return false; 23562 } 23563 return sd.hasCertificate(restoringFromSig, 23564 SigningDetails.CertCapabilities.INSTALLED_DATA); 23565 } 23566 23567 private SigningDetails getSigningDetails(@NonNull String packageName) { 23568 synchronized (mPackages) { 23569 PackageParser.Package p = mPackages.get(packageName); 23570 if (p == null) { 23571 return null; 23572 } 23573 return p.mSigningDetails; 23574 } 23575 } 23576 23577 @Override 23578 public int getPermissionFlagsTEMP(String permName, String packageName, int userId) { 23579 return PackageManagerService.this.getPermissionFlags(permName, packageName, userId); 23580 } 23581 23582 @Override 23583 public boolean isInstantApp(String packageName, int userId) { 23584 return PackageManagerService.this.isInstantApp(packageName, userId); 23585 } 23586 23587 @Override 23588 public String getInstantAppPackageName(int uid) { 23589 return PackageManagerService.this.getInstantAppPackageName(uid); 23590 } 23591 23592 @Override 23593 public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) { 23594 synchronized (mPackages) { 23595 return PackageManagerService.this.filterAppAccessLPr( 23596 (PackageSetting) pkg.mExtras, callingUid, userId); 23597 } 23598 } 23599 23600 @Override 23601 public PackageParser.Package getPackage(String packageName) { 23602 synchronized (mPackages) { 23603 packageName = resolveInternalPackageNameLPr( 23604 packageName, PackageManager.VERSION_CODE_HIGHEST); 23605 return mPackages.get(packageName); 23606 } 23607 } 23608 23609 @Override 23610 public Object getPackageSetting(String packageName) { 23611 synchronized (mPackages) { 23612 return mSettings.getPackageLPr(packageName); 23613 } 23614 } 23615 23616 @Override 23617 public PackageList getPackageList(PackageListObserver observer) { 23618 synchronized (mPackages) { 23619 final int N = mPackages.size(); 23620 final ArrayList<String> list = new ArrayList<>(N); 23621 for (int i = 0; i < N; i++) { 23622 list.add(mPackages.keyAt(i)); 23623 } 23624 final PackageList packageList = new PackageList(list, observer); 23625 if (observer != null) { 23626 mPackageListObservers.add(packageList); 23627 } 23628 return packageList; 23629 } 23630 } 23631 23632 @Override 23633 public void removePackageListObserver(PackageListObserver observer) { 23634 synchronized (mPackages) { 23635 mPackageListObservers.remove(observer); 23636 } 23637 } 23638 23639 @Override 23640 public PackageParser.Package getDisabledPackage(String packageName) { 23641 synchronized (mPackages) { 23642 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 23643 return (ps != null) ? ps.pkg : null; 23644 } 23645 } 23646 23647 @Override 23648 public String getKnownPackageName(int knownPackage, int userId) { 23649 switch(knownPackage) { 23650 case PackageManagerInternal.PACKAGE_BROWSER: 23651 return getDefaultBrowserPackageName(userId); 23652 case PackageManagerInternal.PACKAGE_INSTALLER: 23653 return mRequiredInstallerPackage; 23654 case PackageManagerInternal.PACKAGE_SETUP_WIZARD: 23655 return mSetupWizardPackage; 23656 case PackageManagerInternal.PACKAGE_SYSTEM: 23657 return "android"; 23658 case PackageManagerInternal.PACKAGE_VERIFIER: 23659 return mRequiredVerifierPackage; 23660 case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER: 23661 return mSystemTextClassifierPackage; 23662 } 23663 return null; 23664 } 23665 23666 @Override 23667 public boolean isResolveActivityComponent(ComponentInfo component) { 23668 return mResolveActivity.packageName.equals(component.packageName) 23669 && mResolveActivity.name.equals(component.name); 23670 } 23671 23672 @Override 23673 public void setLocationPackagesProvider(PackagesProvider provider) { 23674 mDefaultPermissionPolicy.setLocationPackagesProvider(provider); 23675 } 23676 23677 @Override 23678 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23679 mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider); 23680 } 23681 23682 @Override 23683 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23684 mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider); 23685 } 23686 23687 @Override 23688 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23689 mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider); 23690 } 23691 23692 @Override 23693 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23694 mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider); 23695 } 23696 23697 @Override 23698 public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) { 23699 mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider); 23700 } 23701 23702 @Override 23703 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23704 mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider); 23705 } 23706 23707 @Override 23708 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23709 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId); 23710 } 23711 23712 @Override 23713 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23714 synchronized (mPackages) { 23715 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23716 } 23717 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId); 23718 } 23719 23720 @Override 23721 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23722 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager( 23723 packageName, userId); 23724 } 23725 23726 @Override 23727 public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) { 23728 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp( 23729 packageName, userId); 23730 } 23731 23732 @Override 23733 public void setKeepUninstalledPackages(final List<String> packageList) { 23734 Preconditions.checkNotNull(packageList); 23735 List<String> removedFromList = null; 23736 synchronized (mPackages) { 23737 if (mKeepUninstalledPackages != null) { 23738 final int packagesCount = mKeepUninstalledPackages.size(); 23739 for (int i = 0; i < packagesCount; i++) { 23740 String oldPackage = mKeepUninstalledPackages.get(i); 23741 if (packageList != null && packageList.contains(oldPackage)) { 23742 continue; 23743 } 23744 if (removedFromList == null) { 23745 removedFromList = new ArrayList<>(); 23746 } 23747 removedFromList.add(oldPackage); 23748 } 23749 } 23750 mKeepUninstalledPackages = new ArrayList<>(packageList); 23751 if (removedFromList != null) { 23752 final int removedCount = removedFromList.size(); 23753 for (int i = 0; i < removedCount; i++) { 23754 deletePackageIfUnusedLPr(removedFromList.get(i)); 23755 } 23756 } 23757 } 23758 } 23759 23760 @Override 23761 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23762 synchronized (mPackages) { 23763 return mPermissionManager.isPermissionsReviewRequired( 23764 mPackages.get(packageName), userId); 23765 } 23766 } 23767 23768 @Override 23769 public PackageInfo getPackageInfo( 23770 String packageName, int flags, int filterCallingUid, int userId) { 23771 return PackageManagerService.this 23772 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 23773 flags, filterCallingUid, userId); 23774 } 23775 23776 @Override 23777 public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) { 23778 synchronized (mPackages) { 23779 final PackageSetting ps = mSettings.mPackages.get(packageName); 23780 PersistableBundle launcherExtras = null; 23781 if (ps != null) { 23782 launcherExtras = ps.readUserState(userId).suspendedLauncherExtras; 23783 } 23784 return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null; 23785 } 23786 } 23787 23788 @Override 23789 public boolean isPackageSuspended(String packageName, int userId) { 23790 synchronized (mPackages) { 23791 final PackageSetting ps = mSettings.mPackages.get(packageName); 23792 return (ps != null) ? ps.getSuspended(userId) : false; 23793 } 23794 } 23795 23796 @Override 23797 public String getSuspendingPackage(String suspendedPackage, int userId) { 23798 synchronized (mPackages) { 23799 final PackageSetting ps = mSettings.mPackages.get(suspendedPackage); 23800 return (ps != null) ? ps.readUserState(userId).suspendingPackage : null; 23801 } 23802 } 23803 23804 @Override 23805 public String getSuspendedDialogMessage(String suspendedPackage, int userId) { 23806 synchronized (mPackages) { 23807 final PackageSetting ps = mSettings.mPackages.get(suspendedPackage); 23808 return (ps != null) ? ps.readUserState(userId).dialogMessage : null; 23809 } 23810 } 23811 23812 @Override 23813 public int getPackageUid(String packageName, int flags, int userId) { 23814 return PackageManagerService.this 23815 .getPackageUid(packageName, flags, userId); 23816 } 23817 23818 @Override 23819 public ApplicationInfo getApplicationInfo( 23820 String packageName, int flags, int filterCallingUid, int userId) { 23821 return PackageManagerService.this 23822 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 23823 } 23824 23825 @Override 23826 public ActivityInfo getActivityInfo( 23827 ComponentName component, int flags, int filterCallingUid, int userId) { 23828 return PackageManagerService.this 23829 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 23830 } 23831 23832 @Override 23833 public List<ResolveInfo> queryIntentActivities( 23834 Intent intent, int flags, int filterCallingUid, int userId) { 23835 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23836 return PackageManagerService.this 23837 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 23838 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 23839 } 23840 23841 @Override 23842 public List<ResolveInfo> queryIntentServices( 23843 Intent intent, int flags, int callingUid, int userId) { 23844 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23845 return PackageManagerService.this 23846 .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid, 23847 false); 23848 } 23849 23850 @Override 23851 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23852 int userId) { 23853 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23854 } 23855 23856 @Override 23857 public ComponentName getDefaultHomeActivity(int userId) { 23858 return PackageManagerService.this.getDefaultHomeActivity(userId); 23859 } 23860 23861 @Override 23862 public void setDeviceAndProfileOwnerPackages( 23863 int deviceOwnerUserId, String deviceOwnerPackage, 23864 SparseArray<String> profileOwnerPackages) { 23865 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23866 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23867 } 23868 23869 @Override 23870 public boolean isPackageDataProtected(int userId, String packageName) { 23871 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23872 } 23873 23874 @Override 23875 public boolean isPackageEphemeral(int userId, String packageName) { 23876 synchronized (mPackages) { 23877 final PackageSetting ps = mSettings.mPackages.get(packageName); 23878 return ps != null ? ps.getInstantApp(userId) : false; 23879 } 23880 } 23881 23882 @Override 23883 public boolean wasPackageEverLaunched(String packageName, int userId) { 23884 synchronized (mPackages) { 23885 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23886 } 23887 } 23888 23889 @Override 23890 public void grantRuntimePermission(String packageName, String permName, int userId, 23891 boolean overridePolicy) { 23892 PackageManagerService.this.mPermissionManager.grantRuntimePermission( 23893 permName, packageName, overridePolicy, getCallingUid(), userId, 23894 mPermissionCallback); 23895 } 23896 23897 @Override 23898 public void revokeRuntimePermission(String packageName, String permName, int userId, 23899 boolean overridePolicy) { 23900 mPermissionManager.revokeRuntimePermission( 23901 permName, packageName, overridePolicy, getCallingUid(), userId, 23902 mPermissionCallback); 23903 } 23904 23905 @Override 23906 public String getNameForUid(int uid) { 23907 return PackageManagerService.this.getNameForUid(uid); 23908 } 23909 23910 @Override 23911 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23912 Intent origIntent, String resolvedType, String callingPackage, 23913 Bundle verificationBundle, int userId) { 23914 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23915 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 23916 userId); 23917 } 23918 23919 @Override 23920 public void grantEphemeralAccess(int userId, Intent intent, 23921 int targetAppId, int ephemeralAppId) { 23922 synchronized (mPackages) { 23923 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23924 targetAppId, ephemeralAppId); 23925 } 23926 } 23927 23928 @Override 23929 public boolean isInstantAppInstallerComponent(ComponentName component) { 23930 synchronized (mPackages) { 23931 return mInstantAppInstallerActivity != null 23932 && mInstantAppInstallerActivity.getComponentName().equals(component); 23933 } 23934 } 23935 23936 @Override 23937 public void pruneInstantApps() { 23938 mInstantAppRegistry.pruneInstantApps(); 23939 } 23940 23941 @Override 23942 public String getSetupWizardPackageName() { 23943 return mSetupWizardPackage; 23944 } 23945 23946 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23947 if (policy != null) { 23948 mExternalSourcesPolicy = policy; 23949 } 23950 } 23951 23952 @Override 23953 public boolean isPackagePersistent(String packageName) { 23954 synchronized (mPackages) { 23955 PackageParser.Package pkg = mPackages.get(packageName); 23956 return pkg != null 23957 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23958 | ApplicationInfo.FLAG_PERSISTENT)) == 23959 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23960 : false; 23961 } 23962 } 23963 23964 @Override 23965 public boolean isLegacySystemApp(Package pkg) { 23966 synchronized (mPackages) { 23967 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23968 return mPromoteSystemApps 23969 && ps.isSystem() 23970 && mExistingSystemPackages.contains(ps.name); 23971 } 23972 } 23973 23974 @Override 23975 public List<PackageInfo> getOverlayPackages(int userId) { 23976 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23977 synchronized (mPackages) { 23978 for (PackageParser.Package p : mPackages.values()) { 23979 if (p.mOverlayTarget != null) { 23980 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23981 if (pkg != null) { 23982 overlayPackages.add(pkg); 23983 } 23984 } 23985 } 23986 } 23987 return overlayPackages; 23988 } 23989 23990 @Override 23991 public List<String> getTargetPackageNames(int userId) { 23992 List<String> targetPackages = new ArrayList<>(); 23993 synchronized (mPackages) { 23994 for (PackageParser.Package p : mPackages.values()) { 23995 if (p.mOverlayTarget == null) { 23996 targetPackages.add(p.packageName); 23997 } 23998 } 23999 } 24000 return targetPackages; 24001 } 24002 24003 @Override 24004 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 24005 @Nullable List<String> overlayPackageNames) { 24006 synchronized (mPackages) { 24007 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 24008 Slog.e(TAG, "failed to find package " + targetPackageName); 24009 return false; 24010 } 24011 ArrayList<String> overlayPaths = null; 24012 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 24013 final int N = overlayPackageNames.size(); 24014 overlayPaths = new ArrayList<>(N); 24015 for (int i = 0; i < N; i++) { 24016 final String packageName = overlayPackageNames.get(i); 24017 final PackageParser.Package pkg = mPackages.get(packageName); 24018 if (pkg == null) { 24019 Slog.e(TAG, "failed to find package " + packageName); 24020 return false; 24021 } 24022 overlayPaths.add(pkg.baseCodePath); 24023 } 24024 } 24025 24026 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 24027 ps.setOverlayPaths(overlayPaths, userId); 24028 return true; 24029 } 24030 } 24031 24032 @Override 24033 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 24034 int flags, int userId, boolean resolveForStart, int filterCallingUid) { 24035 return resolveIntentInternal( 24036 intent, resolvedType, flags, userId, resolveForStart, filterCallingUid); 24037 } 24038 24039 @Override 24040 public ResolveInfo resolveService(Intent intent, String resolvedType, 24041 int flags, int userId, int callingUid) { 24042 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 24043 } 24044 24045 @Override 24046 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 24047 return PackageManagerService.this.resolveContentProviderInternal( 24048 name, flags, userId); 24049 } 24050 24051 @Override 24052 public void addIsolatedUid(int isolatedUid, int ownerUid) { 24053 synchronized (mPackages) { 24054 mIsolatedOwners.put(isolatedUid, ownerUid); 24055 } 24056 } 24057 24058 @Override 24059 public void removeIsolatedUid(int isolatedUid) { 24060 synchronized (mPackages) { 24061 mIsolatedOwners.delete(isolatedUid); 24062 } 24063 } 24064 24065 @Override 24066 public int getUidTargetSdkVersion(int uid) { 24067 synchronized (mPackages) { 24068 return getUidTargetSdkVersionLockedLPr(uid); 24069 } 24070 } 24071 24072 @Override 24073 public int getPackageTargetSdkVersion(String packageName) { 24074 synchronized (mPackages) { 24075 return getPackageTargetSdkVersionLockedLPr(packageName); 24076 } 24077 } 24078 24079 @Override 24080 public boolean canAccessInstantApps(int callingUid, int userId) { 24081 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 24082 } 24083 24084 @Override 24085 public boolean canAccessComponent(int callingUid, ComponentName component, int userId) { 24086 synchronized (mPackages) { 24087 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 24088 return !PackageManagerService.this.filterAppAccessLPr( 24089 ps, callingUid, component, TYPE_UNKNOWN, userId); 24090 } 24091 } 24092 24093 @Override 24094 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 24095 synchronized (mPackages) { 24096 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 24097 } 24098 } 24099 24100 @Override 24101 public void notifyPackageUse(String packageName, int reason) { 24102 synchronized (mPackages) { 24103 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 24104 } 24105 } 24106 } 24107 24108 @Override 24109 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 24110 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 24111 synchronized (mPackages) { 24112 final long identity = Binder.clearCallingIdentity(); 24113 try { 24114 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps( 24115 packageNames, userId); 24116 } finally { 24117 Binder.restoreCallingIdentity(identity); 24118 } 24119 } 24120 } 24121 24122 @Override 24123 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 24124 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 24125 synchronized (mPackages) { 24126 final long identity = Binder.clearCallingIdentity(); 24127 try { 24128 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices( 24129 packageNames, userId); 24130 } finally { 24131 Binder.restoreCallingIdentity(identity); 24132 } 24133 } 24134 } 24135 24136 @Override 24137 public void grantDefaultPermissionsToEnabledTelephonyDataServices( 24138 String[] packageNames, int userId) { 24139 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices"); 24140 synchronized (mPackages) { 24141 Binder.withCleanCallingIdentity( () -> { 24142 mDefaultPermissionPolicy. 24143 grantDefaultPermissionsToEnabledTelephonyDataServices( 24144 packageNames, userId); 24145 }); 24146 } 24147 } 24148 24149 @Override 24150 public void revokeDefaultPermissionsFromDisabledTelephonyDataServices( 24151 String[] packageNames, int userId) { 24152 enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices"); 24153 synchronized (mPackages) { 24154 Binder.withCleanCallingIdentity( () -> { 24155 mDefaultPermissionPolicy. 24156 revokeDefaultPermissionsFromDisabledTelephonyDataServices( 24157 packageNames, userId); 24158 }); 24159 } 24160 } 24161 24162 @Override 24163 public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) { 24164 enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp"); 24165 synchronized (mPackages) { 24166 final long identity = Binder.clearCallingIdentity(); 24167 try { 24168 mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp( 24169 packageName, userId); 24170 } finally { 24171 Binder.restoreCallingIdentity(identity); 24172 } 24173 } 24174 } 24175 24176 @Override 24177 public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) { 24178 enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps"); 24179 synchronized (mPackages) { 24180 final long identity = Binder.clearCallingIdentity(); 24181 try { 24182 mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId); 24183 } finally { 24184 Binder.restoreCallingIdentity(identity); 24185 } 24186 } 24187 } 24188 24189 private static void enforceSystemOrPhoneCaller(String tag) { 24190 int callingUid = Binder.getCallingUid(); 24191 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 24192 throw new SecurityException( 24193 "Cannot call " + tag + " from UID " + callingUid); 24194 } 24195 } 24196 24197 boolean isHistoricalPackageUsageAvailable() { 24198 return mPackageUsage.isHistoricalPackageUsageAvailable(); 24199 } 24200 24201 /** 24202 * Return a <b>copy</b> of the collection of packages known to the package manager. 24203 * @return A copy of the values of mPackages. 24204 */ 24205 Collection<PackageParser.Package> getPackages() { 24206 synchronized (mPackages) { 24207 return new ArrayList<>(mPackages.values()); 24208 } 24209 } 24210 24211 /** 24212 * Logs process start information (including base APK hash) to the security log. 24213 * @hide 24214 */ 24215 @Override 24216 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 24217 String apkFile, int pid) { 24218 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 24219 return; 24220 } 24221 if (!SecurityLog.isLoggingEnabled()) { 24222 return; 24223 } 24224 Bundle data = new Bundle(); 24225 data.putLong("startTimestamp", System.currentTimeMillis()); 24226 data.putString("processName", processName); 24227 data.putInt("uid", uid); 24228 data.putString("seinfo", seinfo); 24229 data.putString("apkFile", apkFile); 24230 data.putInt("pid", pid); 24231 Message msg = mProcessLoggingHandler.obtainMessage( 24232 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 24233 msg.setData(data); 24234 mProcessLoggingHandler.sendMessage(msg); 24235 } 24236 24237 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 24238 return mCompilerStats.getPackageStats(pkgName); 24239 } 24240 24241 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 24242 return getOrCreateCompilerPackageStats(pkg.packageName); 24243 } 24244 24245 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 24246 return mCompilerStats.getOrCreatePackageStats(pkgName); 24247 } 24248 24249 public void deleteCompilerPackageStats(String pkgName) { 24250 mCompilerStats.deletePackageStats(pkgName); 24251 } 24252 24253 @Override 24254 public int getInstallReason(String packageName, int userId) { 24255 final int callingUid = Binder.getCallingUid(); 24256 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24257 true /* requireFullPermission */, false /* checkShell */, 24258 "get install reason"); 24259 synchronized (mPackages) { 24260 final PackageSetting ps = mSettings.mPackages.get(packageName); 24261 if (filterAppAccessLPr(ps, callingUid, userId)) { 24262 return PackageManager.INSTALL_REASON_UNKNOWN; 24263 } 24264 if (ps != null) { 24265 return ps.getInstallReason(userId); 24266 } 24267 } 24268 return PackageManager.INSTALL_REASON_UNKNOWN; 24269 } 24270 24271 @Override 24272 public boolean canRequestPackageInstalls(String packageName, int userId) { 24273 return canRequestPackageInstallsInternal(packageName, 0, userId, 24274 true /* throwIfPermNotDeclared*/); 24275 } 24276 24277 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 24278 boolean throwIfPermNotDeclared) { 24279 int callingUid = Binder.getCallingUid(); 24280 int uid = getPackageUid(packageName, 0, userId); 24281 if (callingUid != uid && callingUid != Process.ROOT_UID 24282 && callingUid != Process.SYSTEM_UID) { 24283 throw new SecurityException( 24284 "Caller uid " + callingUid + " does not own package " + packageName); 24285 } 24286 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 24287 if (info == null) { 24288 return false; 24289 } 24290 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 24291 return false; 24292 } 24293 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 24294 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 24295 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 24296 if (throwIfPermNotDeclared) { 24297 throw new SecurityException("Need to declare " + appOpPermission 24298 + " to call this api"); 24299 } else { 24300 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 24301 return false; 24302 } 24303 } 24304 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 24305 return false; 24306 } 24307 if (mExternalSourcesPolicy != null) { 24308 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 24309 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 24310 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 24311 } 24312 } 24313 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 24314 } 24315 24316 @Override 24317 public ComponentName getInstantAppResolverSettingsComponent() { 24318 return mInstantAppResolverSettingsComponent; 24319 } 24320 24321 @Override 24322 public ComponentName getInstantAppInstallerComponent() { 24323 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 24324 return null; 24325 } 24326 return mInstantAppInstallerActivity == null 24327 ? null : mInstantAppInstallerActivity.getComponentName(); 24328 } 24329 24330 @Override 24331 public String getInstantAppAndroidId(String packageName, int userId) { 24332 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 24333 "getInstantAppAndroidId"); 24334 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 24335 true /* requireFullPermission */, false /* checkShell */, 24336 "getInstantAppAndroidId"); 24337 // Make sure the target is an Instant App. 24338 if (!isInstantApp(packageName, userId)) { 24339 return null; 24340 } 24341 synchronized (mPackages) { 24342 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 24343 } 24344 } 24345 24346 boolean canHaveOatDir(String packageName) { 24347 synchronized (mPackages) { 24348 PackageParser.Package p = mPackages.get(packageName); 24349 if (p == null) { 24350 return false; 24351 } 24352 return p.canHaveOatDir(); 24353 } 24354 } 24355 24356 private String getOatDir(PackageParser.Package pkg) { 24357 if (!pkg.canHaveOatDir()) { 24358 return null; 24359 } 24360 File codePath = new File(pkg.codePath); 24361 if (codePath.isDirectory()) { 24362 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 24363 } 24364 return null; 24365 } 24366 24367 void deleteOatArtifactsOfPackage(String packageName) { 24368 final String[] instructionSets; 24369 final List<String> codePaths; 24370 final String oatDir; 24371 final PackageParser.Package pkg; 24372 synchronized (mPackages) { 24373 pkg = mPackages.get(packageName); 24374 } 24375 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 24376 codePaths = pkg.getAllCodePaths(); 24377 oatDir = getOatDir(pkg); 24378 24379 for (String codePath : codePaths) { 24380 for (String isa : instructionSets) { 24381 try { 24382 mInstaller.deleteOdex(codePath, isa, oatDir); 24383 } catch (InstallerException e) { 24384 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 24385 } 24386 } 24387 } 24388 } 24389 24390 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 24391 Set<String> unusedPackages = new HashSet<>(); 24392 long currentTimeInMillis = System.currentTimeMillis(); 24393 synchronized (mPackages) { 24394 for (PackageParser.Package pkg : mPackages.values()) { 24395 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 24396 if (ps == null) { 24397 continue; 24398 } 24399 PackageDexUsage.PackageUseInfo packageUseInfo = 24400 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 24401 if (PackageManagerServiceUtils 24402 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 24403 downgradeTimeThresholdMillis, packageUseInfo, 24404 pkg.getLatestPackageUseTimeInMills(), 24405 pkg.getLatestForegroundPackageUseTimeInMills())) { 24406 unusedPackages.add(pkg.packageName); 24407 } 24408 } 24409 } 24410 return unusedPackages; 24411 } 24412 24413 @Override 24414 public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning, 24415 int userId) { 24416 final int callingUid = Binder.getCallingUid(); 24417 final int callingAppId = UserHandle.getAppId(callingUid); 24418 24419 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24420 true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo"); 24421 24422 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24423 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24424 throw new SecurityException("Caller must have the " 24425 + SET_HARMFUL_APP_WARNINGS + " permission."); 24426 } 24427 24428 synchronized(mPackages) { 24429 mSettings.setHarmfulAppWarningLPw(packageName, warning, userId); 24430 scheduleWritePackageRestrictionsLocked(userId); 24431 } 24432 } 24433 24434 @Nullable 24435 @Override 24436 public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) { 24437 final int callingUid = Binder.getCallingUid(); 24438 final int callingAppId = UserHandle.getAppId(callingUid); 24439 24440 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24441 true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo"); 24442 24443 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24444 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24445 throw new SecurityException("Caller must have the " 24446 + SET_HARMFUL_APP_WARNINGS + " permission."); 24447 } 24448 24449 synchronized(mPackages) { 24450 return mSettings.getHarmfulAppWarningLPr(packageName, userId); 24451 } 24452 } 24453 24454 @Override 24455 public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) { 24456 final int callingUid = Binder.getCallingUid(); 24457 final int callingAppId = UserHandle.getAppId(callingUid); 24458 24459 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24460 false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected"); 24461 24462 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID 24463 && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) { 24464 throw new SecurityException("Caller must have the " 24465 + MANAGE_DEVICE_ADMINS + " permission."); 24466 } 24467 24468 return mProtectedPackages.isPackageStateProtected(userId, packageName); 24469 } 24470} 24471 24472interface PackageSender { 24473 /** 24474 * @param userIds User IDs where the action occurred on a full application 24475 * @param instantUserIds User IDs where the action occurred on an instant application 24476 */ 24477 void sendPackageBroadcast(final String action, final String pkg, 24478 final Bundle extras, final int flags, final String targetPkg, 24479 final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds); 24480 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 24481 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds); 24482 void notifyPackageAdded(String packageName); 24483 void notifyPackageRemoved(String packageName); 24484} 24485