PackageManagerService.java revision 5564f880db3292327872a07df8e230eee78be14b
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.DELETE_PACKAGES; 20import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS; 21import static android.Manifest.permission.INSTALL_PACKAGES; 22import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS; 23import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 24import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 25import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 26import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 27import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509; 28import static android.content.pm.PackageManager.CERT_INPUT_SHA256; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 34import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 39import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 42import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 43import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 44import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 52import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 53import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 54import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 55import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 59import static android.content.pm.PackageManager.INSTALL_INTERNAL; 60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 66import static android.content.pm.PackageManager.MATCH_ALL; 67import static android.content.pm.PackageManager.MATCH_ANY_USER; 68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER; 81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 83import static android.content.pm.PackageManager.PERMISSION_DENIED; 84import static android.content.pm.PackageManager.PERMISSION_GRANTED; 85import static android.content.pm.PackageParser.isApkFile; 86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 87import static android.os.storage.StorageManager.FLAG_STORAGE_CE; 88import static android.os.storage.StorageManager.FLAG_STORAGE_DE; 89import static android.system.OsConstants.O_CREAT; 90import static android.system.OsConstants.O_RDWR; 91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 95import static com.android.internal.util.ArrayUtils.appendInt; 96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 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.signingDetailsHasCertificate; 112import static com.android.server.pm.PackageManagerServiceUtils.signingDetailsHasSha256Certificate; 113import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures; 114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE; 115import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS; 116import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 117 118import android.Manifest; 119import android.annotation.IntDef; 120import android.annotation.NonNull; 121import android.annotation.Nullable; 122import android.app.ActivityManager; 123import android.app.ActivityManagerInternal; 124import android.app.AppOpsManager; 125import android.app.IActivityManager; 126import android.app.ResourcesManager; 127import android.app.admin.IDevicePolicyManager; 128import android.app.admin.SecurityLog; 129import android.app.backup.IBackupManager; 130import android.content.BroadcastReceiver; 131import android.content.ComponentName; 132import android.content.ContentResolver; 133import android.content.Context; 134import android.content.IIntentReceiver; 135import android.content.Intent; 136import android.content.IntentFilter; 137import android.content.IntentSender; 138import android.content.IntentSender.SendIntentException; 139import android.content.ServiceConnection; 140import android.content.pm.ActivityInfo; 141import android.content.pm.ApplicationInfo; 142import android.content.pm.AppsQueryHelper; 143import android.content.pm.AuxiliaryResolveInfo; 144import android.content.pm.ChangedPackages; 145import android.content.pm.ComponentInfo; 146import android.content.pm.FallbackCategoryProvider; 147import android.content.pm.FeatureInfo; 148import android.content.pm.IDexModuleRegisterCallback; 149import android.content.pm.IOnPermissionsChangeListener; 150import android.content.pm.IPackageDataObserver; 151import android.content.pm.IPackageDeleteObserver; 152import android.content.pm.IPackageDeleteObserver2; 153import android.content.pm.IPackageInstallObserver2; 154import android.content.pm.IPackageInstaller; 155import android.content.pm.IPackageManager; 156import android.content.pm.IPackageManagerNative; 157import android.content.pm.IPackageMoveObserver; 158import android.content.pm.IPackageStatsObserver; 159import android.content.pm.InstantAppInfo; 160import android.content.pm.InstantAppRequest; 161import android.content.pm.InstantAppResolveInfo; 162import android.content.pm.InstrumentationInfo; 163import android.content.pm.IntentFilterVerificationInfo; 164import android.content.pm.KeySet; 165import android.content.pm.PackageCleanItem; 166import android.content.pm.PackageInfo; 167import android.content.pm.PackageInfoLite; 168import android.content.pm.PackageInstaller; 169import android.content.pm.PackageList; 170import android.content.pm.PackageManager; 171import android.content.pm.PackageManagerInternal; 172import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 173import android.content.pm.PackageManagerInternal.PackageListObserver; 174import android.content.pm.PackageParser; 175import android.content.pm.PackageParser.ActivityIntentInfo; 176import android.content.pm.PackageParser.Package; 177import android.content.pm.PackageParser.PackageLite; 178import android.content.pm.PackageParser.PackageParserException; 179import android.content.pm.PackageParser.ParseFlags; 180import android.content.pm.PackageParser.ServiceIntentInfo; 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.ServiceInfo; 190import android.content.pm.SharedLibraryInfo; 191import android.content.pm.Signature; 192import android.content.pm.UserInfo; 193import android.content.pm.VerifierDeviceIdentity; 194import android.content.pm.VerifierInfo; 195import android.content.pm.VersionedPackage; 196import android.content.pm.dex.ArtManager; 197import android.content.pm.dex.DexMetadataHelper; 198import android.content.pm.dex.IArtManager; 199import android.content.res.Resources; 200import android.database.ContentObserver; 201import android.graphics.Bitmap; 202import android.hardware.display.DisplayManager; 203import android.net.Uri; 204import android.os.Binder; 205import android.os.Build; 206import android.os.Bundle; 207import android.os.Debug; 208import android.os.Environment; 209import android.os.Environment.UserEnvironment; 210import android.os.FileUtils; 211import android.os.Handler; 212import android.os.IBinder; 213import android.os.Looper; 214import android.os.Message; 215import android.os.Parcel; 216import android.os.ParcelFileDescriptor; 217import android.os.PatternMatcher; 218import android.os.Process; 219import android.os.RemoteCallbackList; 220import android.os.RemoteException; 221import android.os.ResultReceiver; 222import android.os.SELinux; 223import android.os.ServiceManager; 224import android.os.ShellCallback; 225import android.os.SystemClock; 226import android.os.SystemProperties; 227import android.os.Trace; 228import android.os.UserHandle; 229import android.os.UserManager; 230import android.os.UserManagerInternal; 231import android.os.storage.IStorageManager; 232import android.os.storage.StorageEventListener; 233import android.os.storage.StorageManager; 234import android.os.storage.StorageManagerInternal; 235import android.os.storage.VolumeInfo; 236import android.os.storage.VolumeRecord; 237import android.provider.Settings.Global; 238import android.provider.Settings.Secure; 239import android.security.KeyStore; 240import android.security.SystemKeyStore; 241import android.service.pm.PackageServiceDumpProto; 242import android.system.ErrnoException; 243import android.system.Os; 244import android.text.TextUtils; 245import android.text.format.DateUtils; 246import android.util.ArrayMap; 247import android.util.ArraySet; 248import android.util.Base64; 249import android.util.DisplayMetrics; 250import android.util.EventLog; 251import android.util.ExceptionUtils; 252import android.util.Log; 253import android.util.LogPrinter; 254import android.util.LongSparseArray; 255import android.util.LongSparseLongArray; 256import android.util.MathUtils; 257import android.util.PackageUtils; 258import android.util.Pair; 259import android.util.PrintStreamPrinter; 260import android.util.Slog; 261import android.util.SparseArray; 262import android.util.SparseBooleanArray; 263import android.util.SparseIntArray; 264import android.util.TimingsTraceLog; 265import android.util.Xml; 266import android.util.jar.StrictJarFile; 267import android.util.proto.ProtoOutputStream; 268import android.view.Display; 269 270import com.android.internal.R; 271import com.android.internal.annotations.GuardedBy; 272import com.android.internal.app.IMediaContainerService; 273import com.android.internal.app.ResolverActivity; 274import com.android.internal.content.NativeLibraryHelper; 275import com.android.internal.content.PackageHelper; 276import com.android.internal.logging.MetricsLogger; 277import com.android.internal.os.IParcelFileDescriptorFactory; 278import com.android.internal.os.SomeArgs; 279import com.android.internal.os.Zygote; 280import com.android.internal.telephony.CarrierAppUtils; 281import com.android.internal.util.ArrayUtils; 282import com.android.internal.util.ConcurrentUtils; 283import com.android.internal.util.DumpUtils; 284import com.android.internal.util.FastXmlSerializer; 285import com.android.internal.util.IndentingPrintWriter; 286import com.android.internal.util.Preconditions; 287import com.android.internal.util.XmlUtils; 288import com.android.server.AttributeCache; 289import com.android.server.DeviceIdleController; 290import com.android.server.EventLogTags; 291import com.android.server.FgThread; 292import com.android.server.IntentResolver; 293import com.android.server.LocalServices; 294import com.android.server.LockGuard; 295import com.android.server.ServiceThread; 296import com.android.server.SystemConfig; 297import com.android.server.SystemServerInitThreadPool; 298import com.android.server.Watchdog; 299import com.android.server.net.NetworkPolicyManagerInternal; 300import com.android.server.pm.Installer.InstallerException; 301import com.android.server.pm.Settings.DatabaseVersion; 302import com.android.server.pm.Settings.VersionInfo; 303import com.android.server.pm.dex.ArtManagerService; 304import com.android.server.pm.dex.DexLogger; 305import com.android.server.pm.dex.DexManager; 306import com.android.server.pm.dex.DexoptOptions; 307import com.android.server.pm.dex.PackageDexUsage; 308import com.android.server.pm.permission.BasePermission; 309import com.android.server.pm.permission.DefaultPermissionGrantPolicy; 310import com.android.server.pm.permission.PermissionManagerService; 311import com.android.server.pm.permission.PermissionManagerInternal; 312import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback; 313import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback; 314import com.android.server.pm.permission.PermissionsState; 315import com.android.server.pm.permission.PermissionsState.PermissionState; 316import com.android.server.security.VerityUtils; 317import com.android.server.storage.DeviceStorageMonitorInternal; 318 319import dalvik.system.CloseGuard; 320import dalvik.system.VMRuntime; 321 322import libcore.io.IoUtils; 323 324import org.xmlpull.v1.XmlPullParser; 325import org.xmlpull.v1.XmlPullParserException; 326import org.xmlpull.v1.XmlSerializer; 327 328import java.io.BufferedOutputStream; 329import java.io.ByteArrayInputStream; 330import java.io.ByteArrayOutputStream; 331import java.io.File; 332import java.io.FileDescriptor; 333import java.io.FileInputStream; 334import java.io.FileOutputStream; 335import java.io.FilenameFilter; 336import java.io.IOException; 337import java.io.PrintWriter; 338import java.lang.annotation.Retention; 339import java.lang.annotation.RetentionPolicy; 340import java.nio.charset.StandardCharsets; 341import java.security.DigestException; 342import java.security.DigestInputStream; 343import java.security.MessageDigest; 344import java.security.NoSuchAlgorithmException; 345import java.security.PublicKey; 346import java.security.SecureRandom; 347import java.security.cert.CertificateException; 348import java.util.ArrayList; 349import java.util.Arrays; 350import java.util.Collection; 351import java.util.Collections; 352import java.util.Comparator; 353import java.util.HashMap; 354import java.util.HashSet; 355import java.util.Iterator; 356import java.util.LinkedHashSet; 357import java.util.List; 358import java.util.Map; 359import java.util.Objects; 360import java.util.Set; 361import java.util.concurrent.CountDownLatch; 362import java.util.concurrent.Future; 363import java.util.concurrent.TimeUnit; 364import java.util.concurrent.atomic.AtomicBoolean; 365import java.util.concurrent.atomic.AtomicInteger; 366 367/** 368 * Keep track of all those APKs everywhere. 369 * <p> 370 * Internally there are two important locks: 371 * <ul> 372 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 373 * and other related state. It is a fine-grained lock that should only be held 374 * momentarily, as it's one of the most contended locks in the system. 375 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 376 * operations typically involve heavy lifting of application data on disk. Since 377 * {@code installd} is single-threaded, and it's operations can often be slow, 378 * this lock should never be acquired while already holding {@link #mPackages}. 379 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 380 * holding {@link #mInstallLock}. 381 * </ul> 382 * Many internal methods rely on the caller to hold the appropriate locks, and 383 * this contract is expressed through method name suffixes: 384 * <ul> 385 * <li>fooLI(): the caller must hold {@link #mInstallLock} 386 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 387 * being modified must be frozen 388 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 389 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 390 * </ul> 391 * <p> 392 * Because this class is very central to the platform's security; please run all 393 * CTS and unit tests whenever making modifications: 394 * 395 * <pre> 396 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 397 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 398 * </pre> 399 */ 400public class PackageManagerService extends IPackageManager.Stub 401 implements PackageSender { 402 static final String TAG = "PackageManager"; 403 public static final boolean DEBUG_SETTINGS = false; 404 static final boolean DEBUG_PREFERRED = false; 405 static final boolean DEBUG_UPGRADE = false; 406 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 407 private static final boolean DEBUG_BACKUP = false; 408 public static final boolean DEBUG_INSTALL = false; 409 public static final boolean DEBUG_REMOVE = false; 410 private static final boolean DEBUG_BROADCASTS = false; 411 private static final boolean DEBUG_SHOW_INFO = false; 412 private static final boolean DEBUG_PACKAGE_INFO = false; 413 private static final boolean DEBUG_INTENT_MATCHING = false; 414 public static final boolean DEBUG_PACKAGE_SCANNING = false; 415 private static final boolean DEBUG_VERIFY = false; 416 private static final boolean DEBUG_FILTERS = false; 417 public static final boolean DEBUG_PERMISSIONS = false; 418 private static final boolean DEBUG_SHARED_LIBRARIES = false; 419 public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE; 420 421 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 422 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 423 // user, but by default initialize to this. 424 public static final boolean DEBUG_DEXOPT = false; 425 426 private static final boolean DEBUG_ABI_SELECTION = false; 427 private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE; 428 private static final boolean DEBUG_TRIAGED_MISSING = false; 429 private static final boolean DEBUG_APP_DATA = false; 430 431 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 432 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 433 434 private static final boolean HIDE_EPHEMERAL_APIS = false; 435 436 private static final boolean ENABLE_FREE_CACHE_V2 = 437 SystemProperties.getBoolean("fw.free_cache_v2", true); 438 439 private static final int RADIO_UID = Process.PHONE_UID; 440 private static final int LOG_UID = Process.LOG_UID; 441 private static final int NFC_UID = Process.NFC_UID; 442 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 443 private static final int SHELL_UID = Process.SHELL_UID; 444 private static final int SE_UID = Process.SE_UID; 445 446 // Suffix used during package installation when copying/moving 447 // package apks to install directory. 448 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 449 450 static final int SCAN_NO_DEX = 1<<0; 451 static final int SCAN_UPDATE_SIGNATURE = 1<<1; 452 static final int SCAN_NEW_INSTALL = 1<<2; 453 static final int SCAN_UPDATE_TIME = 1<<3; 454 static final int SCAN_BOOTING = 1<<4; 455 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6; 456 static final int SCAN_REQUIRE_KNOWN = 1<<7; 457 static final int SCAN_MOVE = 1<<8; 458 static final int SCAN_INITIAL = 1<<9; 459 static final int SCAN_CHECK_ONLY = 1<<10; 460 static final int SCAN_DONT_KILL_APP = 1<<11; 461 static final int SCAN_IGNORE_FROZEN = 1<<12; 462 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13; 463 static final int SCAN_AS_INSTANT_APP = 1<<14; 464 static final int SCAN_AS_FULL_APP = 1<<15; 465 static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16; 466 static final int SCAN_AS_SYSTEM = 1<<17; 467 static final int SCAN_AS_PRIVILEGED = 1<<18; 468 static final int SCAN_AS_OEM = 1<<19; 469 static final int SCAN_AS_VENDOR = 1<<20; 470 static final int SCAN_AS_PRODUCT = 1<<21; 471 472 @IntDef(flag = true, prefix = { "SCAN_" }, value = { 473 SCAN_NO_DEX, 474 SCAN_UPDATE_SIGNATURE, 475 SCAN_NEW_INSTALL, 476 SCAN_UPDATE_TIME, 477 SCAN_BOOTING, 478 SCAN_DELETE_DATA_ON_FAILURES, 479 SCAN_REQUIRE_KNOWN, 480 SCAN_MOVE, 481 SCAN_INITIAL, 482 SCAN_CHECK_ONLY, 483 SCAN_DONT_KILL_APP, 484 SCAN_IGNORE_FROZEN, 485 SCAN_FIRST_BOOT_OR_UPGRADE, 486 SCAN_AS_INSTANT_APP, 487 SCAN_AS_FULL_APP, 488 SCAN_AS_VIRTUAL_PRELOAD, 489 }) 490 @Retention(RetentionPolicy.SOURCE) 491 public @interface ScanFlags {} 492 493 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 494 /** Extension of the compressed packages */ 495 public final static String COMPRESSED_EXTENSION = ".gz"; 496 /** Suffix of stub packages on the system partition */ 497 public final static String STUB_SUFFIX = "-Stub"; 498 499 private static final int[] EMPTY_INT_ARRAY = new int[0]; 500 501 private static final int TYPE_UNKNOWN = 0; 502 private static final int TYPE_ACTIVITY = 1; 503 private static final int TYPE_RECEIVER = 2; 504 private static final int TYPE_SERVICE = 3; 505 private static final int TYPE_PROVIDER = 4; 506 @IntDef(prefix = { "TYPE_" }, value = { 507 TYPE_UNKNOWN, 508 TYPE_ACTIVITY, 509 TYPE_RECEIVER, 510 TYPE_SERVICE, 511 TYPE_PROVIDER, 512 }) 513 @Retention(RetentionPolicy.SOURCE) 514 public @interface ComponentType {} 515 516 /** 517 * Timeout (in milliseconds) after which the watchdog should declare that 518 * our handler thread is wedged. The usual default for such things is one 519 * minute but we sometimes do very lengthy I/O operations on this thread, 520 * such as installing multi-gigabyte applications, so ours needs to be longer. 521 */ 522 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 523 524 /** 525 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 526 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 527 * settings entry if available, otherwise we use the hardcoded default. If it's been 528 * more than this long since the last fstrim, we force one during the boot sequence. 529 * 530 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 531 * one gets run at the next available charging+idle time. This final mandatory 532 * no-fstrim check kicks in only of the other scheduling criteria is never met. 533 */ 534 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 535 536 /** 537 * Whether verification is enabled by default. 538 */ 539 private static final boolean DEFAULT_VERIFY_ENABLE = true; 540 541 /** 542 * The default maximum time to wait for the verification agent to return in 543 * milliseconds. 544 */ 545 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 546 547 /** 548 * The default response for package verification timeout. 549 * 550 * This can be either PackageManager.VERIFICATION_ALLOW or 551 * PackageManager.VERIFICATION_REJECT. 552 */ 553 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 554 555 public static final String PLATFORM_PACKAGE_NAME = "android"; 556 557 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 558 559 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 560 DEFAULT_CONTAINER_PACKAGE, 561 "com.android.defcontainer.DefaultContainerService"); 562 563 private static final String KILL_APP_REASON_GIDS_CHANGED = 564 "permission grant or revoke changed gids"; 565 566 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 567 "permissions revoked"; 568 569 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 570 571 private static final String PACKAGE_SCHEME = "package"; 572 573 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 574 575 private static final String PRODUCT_OVERLAY_DIR = "/product/overlay"; 576 577 private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob"; 578 579 /** Canonical intent used to identify what counts as a "web browser" app */ 580 private static final Intent sBrowserIntent; 581 static { 582 sBrowserIntent = new Intent(); 583 sBrowserIntent.setAction(Intent.ACTION_VIEW); 584 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 585 sBrowserIntent.setData(Uri.parse("http:")); 586 } 587 588 /** 589 * The set of all protected actions [i.e. those actions for which a high priority 590 * intent filter is disallowed]. 591 */ 592 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 593 static { 594 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 595 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 596 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 597 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 598 } 599 600 // Compilation reasons. 601 public static final int REASON_FIRST_BOOT = 0; 602 public static final int REASON_BOOT = 1; 603 public static final int REASON_INSTALL = 2; 604 public static final int REASON_BACKGROUND_DEXOPT = 3; 605 public static final int REASON_AB_OTA = 4; 606 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5; 607 public static final int REASON_SHARED = 6; 608 609 public static final int REASON_LAST = REASON_SHARED; 610 611 /** 612 * Version number for the package parser cache. Increment this whenever the format or 613 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 614 */ 615 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 616 617 /** 618 * Whether the package parser cache is enabled. 619 */ 620 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 621 622 /** 623 * Permissions required in order to receive instant application lifecycle broadcasts. 624 */ 625 private static final String[] INSTANT_APP_BROADCAST_PERMISSION = 626 new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS }; 627 628 final ServiceThread mHandlerThread; 629 630 final PackageHandler mHandler; 631 632 private final ProcessLoggingHandler mProcessLoggingHandler; 633 634 /** 635 * Messages for {@link #mHandler} that need to wait for system ready before 636 * being dispatched. 637 */ 638 private ArrayList<Message> mPostSystemReadyMessages; 639 640 final int mSdkVersion = Build.VERSION.SDK_INT; 641 642 final Context mContext; 643 final boolean mFactoryTest; 644 final boolean mOnlyCore; 645 final DisplayMetrics mMetrics; 646 final int mDefParseFlags; 647 final String[] mSeparateProcesses; 648 final boolean mIsUpgrade; 649 final boolean mIsPreNUpgrade; 650 final boolean mIsPreNMR1Upgrade; 651 652 // Have we told the Activity Manager to whitelist the default container service by uid yet? 653 @GuardedBy("mPackages") 654 boolean mDefaultContainerWhitelisted = false; 655 656 @GuardedBy("mPackages") 657 private boolean mDexOptDialogShown; 658 659 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 660 // LOCK HELD. Can be called with mInstallLock held. 661 @GuardedBy("mInstallLock") 662 final Installer mInstaller; 663 664 /** Directory where installed applications are stored */ 665 private static final File sAppInstallDir = 666 new File(Environment.getDataDirectory(), "app"); 667 /** Directory where installed application's 32-bit native libraries are copied. */ 668 private static final File sAppLib32InstallDir = 669 new File(Environment.getDataDirectory(), "app-lib"); 670 /** Directory where code and non-resource assets of forward-locked applications are stored */ 671 private static final File sDrmAppPrivateInstallDir = 672 new File(Environment.getDataDirectory(), "app-private"); 673 674 // ---------------------------------------------------------------- 675 676 // Lock for state used when installing and doing other long running 677 // operations. Methods that must be called with this lock held have 678 // the suffix "LI". 679 final Object mInstallLock = new Object(); 680 681 // ---------------------------------------------------------------- 682 683 // Keys are String (package name), values are Package. This also serves 684 // as the lock for the global state. Methods that must be called with 685 // this lock held have the prefix "LP". 686 @GuardedBy("mPackages") 687 final ArrayMap<String, PackageParser.Package> mPackages = 688 new ArrayMap<String, PackageParser.Package>(); 689 690 final ArrayMap<String, Set<String>> mKnownCodebase = 691 new ArrayMap<String, Set<String>>(); 692 693 // Keys are isolated uids and values are the uid of the application 694 // that created the isolated proccess. 695 @GuardedBy("mPackages") 696 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 697 698 /** 699 * Tracks new system packages [received in an OTA] that we expect to 700 * find updated user-installed versions. Keys are package name, values 701 * are package location. 702 */ 703 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 704 /** 705 * Tracks high priority intent filters for protected actions. During boot, certain 706 * filter actions are protected and should never be allowed to have a high priority 707 * intent filter for them. However, there is one, and only one exception -- the 708 * setup wizard. It must be able to define a high priority intent filter for these 709 * actions to ensure there are no escapes from the wizard. We need to delay processing 710 * of these during boot as we need to look at all of the system packages in order 711 * to know which component is the setup wizard. 712 */ 713 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 714 /** 715 * Whether or not processing protected filters should be deferred. 716 */ 717 private boolean mDeferProtectedFilters = true; 718 719 /** 720 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 721 */ 722 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 723 /** 724 * Whether or not system app permissions should be promoted from install to runtime. 725 */ 726 boolean mPromoteSystemApps; 727 728 @GuardedBy("mPackages") 729 final Settings mSettings; 730 731 /** 732 * Set of package names that are currently "frozen", which means active 733 * surgery is being done on the code/data for that package. The platform 734 * will refuse to launch frozen packages to avoid race conditions. 735 * 736 * @see PackageFreezer 737 */ 738 @GuardedBy("mPackages") 739 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 740 741 final ProtectedPackages mProtectedPackages; 742 743 @GuardedBy("mLoadedVolumes") 744 final ArraySet<String> mLoadedVolumes = new ArraySet<>(); 745 746 boolean mFirstBoot; 747 748 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 749 750 @GuardedBy("mAvailableFeatures") 751 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 752 753 private final InstantAppRegistry mInstantAppRegistry; 754 755 @GuardedBy("mPackages") 756 int mChangedPackagesSequenceNumber; 757 /** 758 * List of changed [installed, removed or updated] packages. 759 * mapping from user id -> sequence number -> package name 760 */ 761 @GuardedBy("mPackages") 762 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 763 /** 764 * The sequence number of the last change to a package. 765 * mapping from user id -> package name -> sequence number 766 */ 767 @GuardedBy("mPackages") 768 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 769 770 @GuardedBy("mPackages") 771 final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>(); 772 773 class PackageParserCallback implements PackageParser.Callback { 774 @Override public final boolean hasFeature(String feature) { 775 return PackageManagerService.this.hasSystemFeature(feature, 0); 776 } 777 778 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 779 Collection<PackageParser.Package> allPackages, String targetPackageName) { 780 List<PackageParser.Package> overlayPackages = null; 781 for (PackageParser.Package p : allPackages) { 782 if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) { 783 if (overlayPackages == null) { 784 overlayPackages = new ArrayList<PackageParser.Package>(); 785 } 786 overlayPackages.add(p); 787 } 788 } 789 if (overlayPackages != null) { 790 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 791 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 792 return p1.mOverlayPriority - p2.mOverlayPriority; 793 } 794 }; 795 Collections.sort(overlayPackages, cmp); 796 } 797 return overlayPackages; 798 } 799 800 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 801 String targetPackageName, String targetPath) { 802 if ("android".equals(targetPackageName)) { 803 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 804 // native AssetManager. 805 return null; 806 } 807 List<PackageParser.Package> overlayPackages = 808 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 809 if (overlayPackages == null || overlayPackages.isEmpty()) { 810 return null; 811 } 812 List<String> overlayPathList = null; 813 for (PackageParser.Package overlayPackage : overlayPackages) { 814 if (targetPath == null) { 815 if (overlayPathList == null) { 816 overlayPathList = new ArrayList<String>(); 817 } 818 overlayPathList.add(overlayPackage.baseCodePath); 819 continue; 820 } 821 822 try { 823 // Creates idmaps for system to parse correctly the Android manifest of the 824 // target package. 825 // 826 // OverlayManagerService will update each of them with a correct gid from its 827 // target package app id. 828 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 829 UserHandle.getSharedAppGid( 830 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 831 if (overlayPathList == null) { 832 overlayPathList = new ArrayList<String>(); 833 } 834 overlayPathList.add(overlayPackage.baseCodePath); 835 } catch (InstallerException e) { 836 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 837 overlayPackage.baseCodePath); 838 } 839 } 840 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 841 } 842 843 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 844 synchronized (mPackages) { 845 return getStaticOverlayPathsLocked( 846 mPackages.values(), targetPackageName, targetPath); 847 } 848 } 849 850 @Override public final String[] getOverlayApks(String targetPackageName) { 851 return getStaticOverlayPaths(targetPackageName, null); 852 } 853 854 @Override public final String[] getOverlayPaths(String targetPackageName, 855 String targetPath) { 856 return getStaticOverlayPaths(targetPackageName, targetPath); 857 } 858 } 859 860 class ParallelPackageParserCallback extends PackageParserCallback { 861 List<PackageParser.Package> mOverlayPackages = null; 862 863 void findStaticOverlayPackages() { 864 synchronized (mPackages) { 865 for (PackageParser.Package p : mPackages.values()) { 866 if (p.mOverlayIsStatic) { 867 if (mOverlayPackages == null) { 868 mOverlayPackages = new ArrayList<PackageParser.Package>(); 869 } 870 mOverlayPackages.add(p); 871 } 872 } 873 } 874 } 875 876 @Override 877 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 878 // We can trust mOverlayPackages without holding mPackages because package uninstall 879 // can't happen while running parallel parsing. 880 // Moreover holding mPackages on each parsing thread causes dead-lock. 881 return mOverlayPackages == null ? null : 882 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 883 } 884 } 885 886 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 887 final ParallelPackageParserCallback mParallelPackageParserCallback = 888 new ParallelPackageParserCallback(); 889 890 public static final class SharedLibraryEntry { 891 public final @Nullable String path; 892 public final @Nullable String apk; 893 public final @NonNull SharedLibraryInfo info; 894 895 SharedLibraryEntry(String _path, String _apk, String name, long version, int type, 896 String declaringPackageName, long declaringPackageVersionCode) { 897 path = _path; 898 apk = _apk; 899 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 900 declaringPackageName, declaringPackageVersionCode), null); 901 } 902 } 903 904 // Currently known shared libraries. 905 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 906 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 907 new ArrayMap<>(); 908 909 // All available activities, for your resolving pleasure. 910 final ActivityIntentResolver mActivities = 911 new ActivityIntentResolver(); 912 913 // All available receivers, for your resolving pleasure. 914 final ActivityIntentResolver mReceivers = 915 new ActivityIntentResolver(); 916 917 // All available services, for your resolving pleasure. 918 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 919 920 // All available providers, for your resolving pleasure. 921 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 922 923 // Mapping from provider base names (first directory in content URI codePath) 924 // to the provider information. 925 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 926 new ArrayMap<String, PackageParser.Provider>(); 927 928 // Mapping from instrumentation class names to info about them. 929 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 930 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 931 932 // Packages whose data we have transfered into another package, thus 933 // should no longer exist. 934 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 935 936 // Broadcast actions that are only available to the system. 937 @GuardedBy("mProtectedBroadcasts") 938 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>(); 939 940 /** List of packages waiting for verification. */ 941 final SparseArray<PackageVerificationState> mPendingVerification 942 = new SparseArray<PackageVerificationState>(); 943 944 final PackageInstallerService mInstallerService; 945 946 final ArtManagerService mArtManagerService; 947 948 private final PackageDexOptimizer mPackageDexOptimizer; 949 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 950 // is used by other apps). 951 private final DexManager mDexManager; 952 953 private AtomicInteger mNextMoveId = new AtomicInteger(); 954 private final MoveCallbacks mMoveCallbacks; 955 956 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 957 958 // Cache of users who need badging. 959 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 960 961 /** Token for keys in mPendingVerification. */ 962 private int mPendingVerificationToken = 0; 963 964 volatile boolean mSystemReady; 965 volatile boolean mSafeMode; 966 volatile boolean mHasSystemUidErrors; 967 private volatile boolean mEphemeralAppsDisabled; 968 969 ApplicationInfo mAndroidApplication; 970 final ActivityInfo mResolveActivity = new ActivityInfo(); 971 final ResolveInfo mResolveInfo = new ResolveInfo(); 972 ComponentName mResolveComponentName; 973 PackageParser.Package mPlatformPackage; 974 ComponentName mCustomResolverComponentName; 975 976 boolean mResolverReplaced = false; 977 978 private final @Nullable ComponentName mIntentFilterVerifierComponent; 979 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 980 981 private int mIntentFilterVerificationToken = 0; 982 983 /** The service connection to the ephemeral resolver */ 984 final InstantAppResolverConnection mInstantAppResolverConnection; 985 /** Component used to show resolver settings for Instant Apps */ 986 final ComponentName mInstantAppResolverSettingsComponent; 987 988 /** Activity used to install instant applications */ 989 ActivityInfo mInstantAppInstallerActivity; 990 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 991 992 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 993 = new SparseArray<IntentFilterVerificationState>(); 994 995 // TODO remove this and go through mPermissonManager directly 996 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 997 private final PermissionManagerInternal mPermissionManager; 998 999 // List of packages names to keep cached, even if they are uninstalled for all users 1000 private List<String> mKeepUninstalledPackages; 1001 1002 private UserManagerInternal mUserManagerInternal; 1003 private ActivityManagerInternal mActivityManagerInternal; 1004 1005 private DeviceIdleController.LocalService mDeviceIdleController; 1006 1007 private File mCacheDir; 1008 1009 private Future<?> mPrepareAppDataFuture; 1010 1011 private static class IFVerificationParams { 1012 PackageParser.Package pkg; 1013 boolean replacing; 1014 int userId; 1015 int verifierUid; 1016 1017 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1018 int _userId, int _verifierUid) { 1019 pkg = _pkg; 1020 replacing = _replacing; 1021 userId = _userId; 1022 replacing = _replacing; 1023 verifierUid = _verifierUid; 1024 } 1025 } 1026 1027 private interface IntentFilterVerifier<T extends IntentFilter> { 1028 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1029 T filter, String packageName); 1030 void startVerifications(int userId); 1031 void receiveVerificationResponse(int verificationId); 1032 } 1033 1034 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1035 private Context mContext; 1036 private ComponentName mIntentFilterVerifierComponent; 1037 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1038 1039 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1040 mContext = context; 1041 mIntentFilterVerifierComponent = verifierComponent; 1042 } 1043 1044 private String getDefaultScheme() { 1045 return IntentFilter.SCHEME_HTTPS; 1046 } 1047 1048 @Override 1049 public void startVerifications(int userId) { 1050 // Launch verifications requests 1051 int count = mCurrentIntentFilterVerifications.size(); 1052 for (int n=0; n<count; n++) { 1053 int verificationId = mCurrentIntentFilterVerifications.get(n); 1054 final IntentFilterVerificationState ivs = 1055 mIntentFilterVerificationStates.get(verificationId); 1056 1057 String packageName = ivs.getPackageName(); 1058 1059 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1060 final int filterCount = filters.size(); 1061 ArraySet<String> domainsSet = new ArraySet<>(); 1062 for (int m=0; m<filterCount; m++) { 1063 PackageParser.ActivityIntentInfo filter = filters.get(m); 1064 domainsSet.addAll(filter.getHostsList()); 1065 } 1066 synchronized (mPackages) { 1067 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1068 packageName, domainsSet) != null) { 1069 scheduleWriteSettingsLocked(); 1070 } 1071 } 1072 sendVerificationRequest(verificationId, ivs); 1073 } 1074 mCurrentIntentFilterVerifications.clear(); 1075 } 1076 1077 private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) { 1078 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1079 verificationIntent.putExtra( 1080 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1081 verificationId); 1082 verificationIntent.putExtra( 1083 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1084 getDefaultScheme()); 1085 verificationIntent.putExtra( 1086 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1087 ivs.getHostsString()); 1088 verificationIntent.putExtra( 1089 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1090 ivs.getPackageName()); 1091 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1092 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1093 1094 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1095 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1096 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1097 UserHandle.USER_SYSTEM, true, "intent filter verifier"); 1098 1099 mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM); 1100 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1101 "Sending IntentFilter verification broadcast"); 1102 } 1103 1104 public void receiveVerificationResponse(int verificationId) { 1105 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1106 1107 final boolean verified = ivs.isVerified(); 1108 1109 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1110 final int count = filters.size(); 1111 if (DEBUG_DOMAIN_VERIFICATION) { 1112 Slog.i(TAG, "Received verification response " + verificationId 1113 + " for " + count + " filters, verified=" + verified); 1114 } 1115 for (int n=0; n<count; n++) { 1116 PackageParser.ActivityIntentInfo filter = filters.get(n); 1117 filter.setVerified(verified); 1118 1119 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1120 + " verified with result:" + verified + " and hosts:" 1121 + ivs.getHostsString()); 1122 } 1123 1124 mIntentFilterVerificationStates.remove(verificationId); 1125 1126 final String packageName = ivs.getPackageName(); 1127 IntentFilterVerificationInfo ivi = null; 1128 1129 synchronized (mPackages) { 1130 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1131 } 1132 if (ivi == null) { 1133 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1134 + verificationId + " packageName:" + packageName); 1135 return; 1136 } 1137 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1138 "Updating IntentFilterVerificationInfo for package " + packageName 1139 +" verificationId:" + verificationId); 1140 1141 synchronized (mPackages) { 1142 if (verified) { 1143 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1144 } else { 1145 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1146 } 1147 scheduleWriteSettingsLocked(); 1148 1149 final int userId = ivs.getUserId(); 1150 if (userId != UserHandle.USER_ALL) { 1151 final int userStatus = 1152 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1153 1154 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1155 boolean needUpdate = false; 1156 1157 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1158 // already been set by the User thru the Disambiguation dialog 1159 switch (userStatus) { 1160 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1161 if (verified) { 1162 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1163 } else { 1164 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1165 } 1166 needUpdate = true; 1167 break; 1168 1169 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1170 if (verified) { 1171 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1172 needUpdate = true; 1173 } 1174 break; 1175 1176 default: 1177 // Nothing to do 1178 } 1179 1180 if (needUpdate) { 1181 mSettings.updateIntentFilterVerificationStatusLPw( 1182 packageName, updatedStatus, userId); 1183 scheduleWritePackageRestrictionsLocked(userId); 1184 } 1185 } 1186 } 1187 } 1188 1189 @Override 1190 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1191 ActivityIntentInfo filter, String packageName) { 1192 if (!hasValidDomains(filter)) { 1193 return false; 1194 } 1195 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1196 if (ivs == null) { 1197 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1198 packageName); 1199 } 1200 if (DEBUG_DOMAIN_VERIFICATION) { 1201 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1202 } 1203 ivs.addFilter(filter); 1204 return true; 1205 } 1206 1207 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1208 int userId, int verificationId, String packageName) { 1209 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1210 verifierUid, userId, packageName); 1211 ivs.setPendingState(); 1212 synchronized (mPackages) { 1213 mIntentFilterVerificationStates.append(verificationId, ivs); 1214 mCurrentIntentFilterVerifications.add(verificationId); 1215 } 1216 return ivs; 1217 } 1218 } 1219 1220 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1221 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1222 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1223 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1224 } 1225 1226 // Set of pending broadcasts for aggregating enable/disable of components. 1227 static class PendingPackageBroadcasts { 1228 // for each user id, a map of <package name -> components within that package> 1229 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1230 1231 public PendingPackageBroadcasts() { 1232 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1233 } 1234 1235 public ArrayList<String> get(int userId, String packageName) { 1236 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1237 return packages.get(packageName); 1238 } 1239 1240 public void put(int userId, String packageName, ArrayList<String> components) { 1241 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1242 packages.put(packageName, components); 1243 } 1244 1245 public void remove(int userId, String packageName) { 1246 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1247 if (packages != null) { 1248 packages.remove(packageName); 1249 } 1250 } 1251 1252 public void remove(int userId) { 1253 mUidMap.remove(userId); 1254 } 1255 1256 public int userIdCount() { 1257 return mUidMap.size(); 1258 } 1259 1260 public int userIdAt(int n) { 1261 return mUidMap.keyAt(n); 1262 } 1263 1264 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1265 return mUidMap.get(userId); 1266 } 1267 1268 public int size() { 1269 // total number of pending broadcast entries across all userIds 1270 int num = 0; 1271 for (int i = 0; i< mUidMap.size(); i++) { 1272 num += mUidMap.valueAt(i).size(); 1273 } 1274 return num; 1275 } 1276 1277 public void clear() { 1278 mUidMap.clear(); 1279 } 1280 1281 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1282 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1283 if (map == null) { 1284 map = new ArrayMap<String, ArrayList<String>>(); 1285 mUidMap.put(userId, map); 1286 } 1287 return map; 1288 } 1289 } 1290 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1291 1292 // Service Connection to remote media container service to copy 1293 // package uri's from external media onto secure containers 1294 // or internal storage. 1295 private IMediaContainerService mContainerService = null; 1296 1297 static final int SEND_PENDING_BROADCAST = 1; 1298 static final int MCS_BOUND = 3; 1299 static final int END_COPY = 4; 1300 static final int INIT_COPY = 5; 1301 static final int MCS_UNBIND = 6; 1302 static final int START_CLEANING_PACKAGE = 7; 1303 static final int FIND_INSTALL_LOC = 8; 1304 static final int POST_INSTALL = 9; 1305 static final int MCS_RECONNECT = 10; 1306 static final int MCS_GIVE_UP = 11; 1307 static final int WRITE_SETTINGS = 13; 1308 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1309 static final int PACKAGE_VERIFIED = 15; 1310 static final int CHECK_PENDING_VERIFICATION = 16; 1311 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1312 static final int INTENT_FILTER_VERIFIED = 18; 1313 static final int WRITE_PACKAGE_LIST = 19; 1314 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1315 1316 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1317 1318 // Delay time in millisecs 1319 static final int BROADCAST_DELAY = 10 * 1000; 1320 1321 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1322 2 * 60 * 60 * 1000L; /* two hours */ 1323 1324 static UserManagerService sUserManager; 1325 1326 // Stores a list of users whose package restrictions file needs to be updated 1327 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1328 1329 final private DefaultContainerConnection mDefContainerConn = 1330 new DefaultContainerConnection(); 1331 class DefaultContainerConnection implements ServiceConnection { 1332 public void onServiceConnected(ComponentName name, IBinder service) { 1333 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1334 final IMediaContainerService imcs = IMediaContainerService.Stub 1335 .asInterface(Binder.allowBlocking(service)); 1336 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1337 } 1338 1339 public void onServiceDisconnected(ComponentName name) { 1340 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1341 } 1342 } 1343 1344 // Recordkeeping of restore-after-install operations that are currently in flight 1345 // between the Package Manager and the Backup Manager 1346 static class PostInstallData { 1347 public InstallArgs args; 1348 public PackageInstalledInfo res; 1349 1350 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1351 args = _a; 1352 res = _r; 1353 } 1354 } 1355 1356 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1357 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1358 1359 // XML tags for backup/restore of various bits of state 1360 private static final String TAG_PREFERRED_BACKUP = "pa"; 1361 private static final String TAG_DEFAULT_APPS = "da"; 1362 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1363 1364 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1365 private static final String TAG_ALL_GRANTS = "rt-grants"; 1366 private static final String TAG_GRANT = "grant"; 1367 private static final String ATTR_PACKAGE_NAME = "pkg"; 1368 1369 private static final String TAG_PERMISSION = "perm"; 1370 private static final String ATTR_PERMISSION_NAME = "name"; 1371 private static final String ATTR_IS_GRANTED = "g"; 1372 private static final String ATTR_USER_SET = "set"; 1373 private static final String ATTR_USER_FIXED = "fixed"; 1374 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1375 1376 // System/policy permission grants are not backed up 1377 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1378 FLAG_PERMISSION_POLICY_FIXED 1379 | FLAG_PERMISSION_SYSTEM_FIXED 1380 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1381 1382 // And we back up these user-adjusted states 1383 private static final int USER_RUNTIME_GRANT_MASK = 1384 FLAG_PERMISSION_USER_SET 1385 | FLAG_PERMISSION_USER_FIXED 1386 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1387 1388 final @Nullable String mRequiredVerifierPackage; 1389 final @NonNull String mRequiredInstallerPackage; 1390 final @NonNull String mRequiredUninstallerPackage; 1391 final @Nullable String mSetupWizardPackage; 1392 final @Nullable String mStorageManagerPackage; 1393 final @NonNull String mServicesSystemSharedLibraryPackageName; 1394 final @NonNull String mSharedSystemSharedLibraryPackageName; 1395 1396 private final PackageUsage mPackageUsage = new PackageUsage(); 1397 private final CompilerStats mCompilerStats = new CompilerStats(); 1398 1399 class PackageHandler extends Handler { 1400 private boolean mBound = false; 1401 final ArrayList<HandlerParams> mPendingInstalls = 1402 new ArrayList<HandlerParams>(); 1403 1404 private boolean connectToService() { 1405 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1406 " DefaultContainerService"); 1407 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1408 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1409 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1410 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1411 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1412 mBound = true; 1413 return true; 1414 } 1415 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1416 return false; 1417 } 1418 1419 private void disconnectService() { 1420 mContainerService = null; 1421 mBound = false; 1422 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1423 mContext.unbindService(mDefContainerConn); 1424 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1425 } 1426 1427 PackageHandler(Looper looper) { 1428 super(looper); 1429 } 1430 1431 public void handleMessage(Message msg) { 1432 try { 1433 doHandleMessage(msg); 1434 } finally { 1435 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1436 } 1437 } 1438 1439 void doHandleMessage(Message msg) { 1440 switch (msg.what) { 1441 case INIT_COPY: { 1442 HandlerParams params = (HandlerParams) msg.obj; 1443 int idx = mPendingInstalls.size(); 1444 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1445 // If a bind was already initiated we dont really 1446 // need to do anything. The pending install 1447 // will be processed later on. 1448 if (!mBound) { 1449 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1450 System.identityHashCode(mHandler)); 1451 // If this is the only one pending we might 1452 // have to bind to the service again. 1453 if (!connectToService()) { 1454 Slog.e(TAG, "Failed to bind to media container service"); 1455 params.serviceError(); 1456 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1457 System.identityHashCode(mHandler)); 1458 if (params.traceMethod != null) { 1459 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1460 params.traceCookie); 1461 } 1462 return; 1463 } else { 1464 // Once we bind to the service, the first 1465 // pending request will be processed. 1466 mPendingInstalls.add(idx, params); 1467 } 1468 } else { 1469 mPendingInstalls.add(idx, params); 1470 // Already bound to the service. Just make 1471 // sure we trigger off processing the first request. 1472 if (idx == 0) { 1473 mHandler.sendEmptyMessage(MCS_BOUND); 1474 } 1475 } 1476 break; 1477 } 1478 case MCS_BOUND: { 1479 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1480 if (msg.obj != null) { 1481 mContainerService = (IMediaContainerService) msg.obj; 1482 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1483 System.identityHashCode(mHandler)); 1484 } 1485 if (mContainerService == null) { 1486 if (!mBound) { 1487 // Something seriously wrong since we are not bound and we are not 1488 // waiting for connection. Bail out. 1489 Slog.e(TAG, "Cannot bind to media container service"); 1490 for (HandlerParams params : mPendingInstalls) { 1491 // Indicate service bind error 1492 params.serviceError(); 1493 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1494 System.identityHashCode(params)); 1495 if (params.traceMethod != null) { 1496 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1497 params.traceMethod, params.traceCookie); 1498 } 1499 return; 1500 } 1501 mPendingInstalls.clear(); 1502 } else { 1503 Slog.w(TAG, "Waiting to connect to media container service"); 1504 } 1505 } else if (mPendingInstalls.size() > 0) { 1506 HandlerParams params = mPendingInstalls.get(0); 1507 if (params != null) { 1508 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1509 System.identityHashCode(params)); 1510 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1511 if (params.startCopy()) { 1512 // We are done... look for more work or to 1513 // go idle. 1514 if (DEBUG_SD_INSTALL) Log.i(TAG, 1515 "Checking for more work or unbind..."); 1516 // Delete pending install 1517 if (mPendingInstalls.size() > 0) { 1518 mPendingInstalls.remove(0); 1519 } 1520 if (mPendingInstalls.size() == 0) { 1521 if (mBound) { 1522 if (DEBUG_SD_INSTALL) Log.i(TAG, 1523 "Posting delayed MCS_UNBIND"); 1524 removeMessages(MCS_UNBIND); 1525 Message ubmsg = obtainMessage(MCS_UNBIND); 1526 // Unbind after a little delay, to avoid 1527 // continual thrashing. 1528 sendMessageDelayed(ubmsg, 10000); 1529 } 1530 } else { 1531 // There are more pending requests in queue. 1532 // Just post MCS_BOUND message to trigger processing 1533 // of next pending install. 1534 if (DEBUG_SD_INSTALL) Log.i(TAG, 1535 "Posting MCS_BOUND for next work"); 1536 mHandler.sendEmptyMessage(MCS_BOUND); 1537 } 1538 } 1539 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1540 } 1541 } else { 1542 // Should never happen ideally. 1543 Slog.w(TAG, "Empty queue"); 1544 } 1545 break; 1546 } 1547 case MCS_RECONNECT: { 1548 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1549 if (mPendingInstalls.size() > 0) { 1550 if (mBound) { 1551 disconnectService(); 1552 } 1553 if (!connectToService()) { 1554 Slog.e(TAG, "Failed to bind to media container service"); 1555 for (HandlerParams params : mPendingInstalls) { 1556 // Indicate service bind error 1557 params.serviceError(); 1558 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1559 System.identityHashCode(params)); 1560 } 1561 mPendingInstalls.clear(); 1562 } 1563 } 1564 break; 1565 } 1566 case MCS_UNBIND: { 1567 // If there is no actual work left, then time to unbind. 1568 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1569 1570 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1571 if (mBound) { 1572 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1573 1574 disconnectService(); 1575 } 1576 } else if (mPendingInstalls.size() > 0) { 1577 // There are more pending requests in queue. 1578 // Just post MCS_BOUND message to trigger processing 1579 // of next pending install. 1580 mHandler.sendEmptyMessage(MCS_BOUND); 1581 } 1582 1583 break; 1584 } 1585 case MCS_GIVE_UP: { 1586 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1587 HandlerParams params = mPendingInstalls.remove(0); 1588 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1589 System.identityHashCode(params)); 1590 break; 1591 } 1592 case SEND_PENDING_BROADCAST: { 1593 String packages[]; 1594 ArrayList<String> components[]; 1595 int size = 0; 1596 int uids[]; 1597 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1598 synchronized (mPackages) { 1599 if (mPendingBroadcasts == null) { 1600 return; 1601 } 1602 size = mPendingBroadcasts.size(); 1603 if (size <= 0) { 1604 // Nothing to be done. Just return 1605 return; 1606 } 1607 packages = new String[size]; 1608 components = new ArrayList[size]; 1609 uids = new int[size]; 1610 int i = 0; // filling out the above arrays 1611 1612 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1613 int packageUserId = mPendingBroadcasts.userIdAt(n); 1614 Iterator<Map.Entry<String, ArrayList<String>>> it 1615 = mPendingBroadcasts.packagesForUserId(packageUserId) 1616 .entrySet().iterator(); 1617 while (it.hasNext() && i < size) { 1618 Map.Entry<String, ArrayList<String>> ent = it.next(); 1619 packages[i] = ent.getKey(); 1620 components[i] = ent.getValue(); 1621 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1622 uids[i] = (ps != null) 1623 ? UserHandle.getUid(packageUserId, ps.appId) 1624 : -1; 1625 i++; 1626 } 1627 } 1628 size = i; 1629 mPendingBroadcasts.clear(); 1630 } 1631 // Send broadcasts 1632 for (int i = 0; i < size; i++) { 1633 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1634 } 1635 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1636 break; 1637 } 1638 case START_CLEANING_PACKAGE: { 1639 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1640 final String packageName = (String)msg.obj; 1641 final int userId = msg.arg1; 1642 final boolean andCode = msg.arg2 != 0; 1643 synchronized (mPackages) { 1644 if (userId == UserHandle.USER_ALL) { 1645 int[] users = sUserManager.getUserIds(); 1646 for (int user : users) { 1647 mSettings.addPackageToCleanLPw( 1648 new PackageCleanItem(user, packageName, andCode)); 1649 } 1650 } else { 1651 mSettings.addPackageToCleanLPw( 1652 new PackageCleanItem(userId, packageName, andCode)); 1653 } 1654 } 1655 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1656 startCleaningPackages(); 1657 } break; 1658 case POST_INSTALL: { 1659 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1660 1661 PostInstallData data = mRunningInstalls.get(msg.arg1); 1662 final boolean didRestore = (msg.arg2 != 0); 1663 mRunningInstalls.delete(msg.arg1); 1664 1665 if (data != null) { 1666 InstallArgs args = data.args; 1667 PackageInstalledInfo parentRes = data.res; 1668 1669 final boolean grantPermissions = (args.installFlags 1670 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1671 final boolean killApp = (args.installFlags 1672 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1673 final boolean virtualPreload = ((args.installFlags 1674 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 1675 final String[] grantedPermissions = args.installGrantPermissions; 1676 1677 // Handle the parent package 1678 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1679 virtualPreload, grantedPermissions, didRestore, 1680 args.installerPackageName, args.observer); 1681 1682 // Handle the child packages 1683 final int childCount = (parentRes.addedChildPackages != null) 1684 ? parentRes.addedChildPackages.size() : 0; 1685 for (int i = 0; i < childCount; i++) { 1686 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1687 handlePackagePostInstall(childRes, grantPermissions, killApp, 1688 virtualPreload, grantedPermissions, false /*didRestore*/, 1689 args.installerPackageName, args.observer); 1690 } 1691 1692 // Log tracing if needed 1693 if (args.traceMethod != null) { 1694 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1695 args.traceCookie); 1696 } 1697 } else { 1698 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1699 } 1700 1701 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1702 } break; 1703 case WRITE_SETTINGS: { 1704 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1705 synchronized (mPackages) { 1706 removeMessages(WRITE_SETTINGS); 1707 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1708 mSettings.writeLPr(); 1709 mDirtyUsers.clear(); 1710 } 1711 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1712 } break; 1713 case WRITE_PACKAGE_RESTRICTIONS: { 1714 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1715 synchronized (mPackages) { 1716 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1717 for (int userId : mDirtyUsers) { 1718 mSettings.writePackageRestrictionsLPr(userId); 1719 } 1720 mDirtyUsers.clear(); 1721 } 1722 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1723 } break; 1724 case WRITE_PACKAGE_LIST: { 1725 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1726 synchronized (mPackages) { 1727 removeMessages(WRITE_PACKAGE_LIST); 1728 mSettings.writePackageListLPr(msg.arg1); 1729 } 1730 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1731 } break; 1732 case CHECK_PENDING_VERIFICATION: { 1733 final int verificationId = msg.arg1; 1734 final PackageVerificationState state = mPendingVerification.get(verificationId); 1735 1736 if ((state != null) && !state.timeoutExtended()) { 1737 final InstallArgs args = state.getInstallArgs(); 1738 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1739 1740 Slog.i(TAG, "Verification timed out for " + originUri); 1741 mPendingVerification.remove(verificationId); 1742 1743 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1744 1745 final UserHandle user = args.getUser(); 1746 if (getDefaultVerificationResponse(user) 1747 == PackageManager.VERIFICATION_ALLOW) { 1748 Slog.i(TAG, "Continuing with installation of " + originUri); 1749 state.setVerifierResponse(Binder.getCallingUid(), 1750 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1751 broadcastPackageVerified(verificationId, originUri, 1752 PackageManager.VERIFICATION_ALLOW, user); 1753 try { 1754 ret = args.copyApk(mContainerService, true); 1755 } catch (RemoteException e) { 1756 Slog.e(TAG, "Could not contact the ContainerService"); 1757 } 1758 } else { 1759 broadcastPackageVerified(verificationId, originUri, 1760 PackageManager.VERIFICATION_REJECT, user); 1761 } 1762 1763 Trace.asyncTraceEnd( 1764 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1765 1766 processPendingInstall(args, ret); 1767 mHandler.sendEmptyMessage(MCS_UNBIND); 1768 } 1769 break; 1770 } 1771 case PACKAGE_VERIFIED: { 1772 final int verificationId = msg.arg1; 1773 1774 final PackageVerificationState state = mPendingVerification.get(verificationId); 1775 if (state == null) { 1776 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1777 break; 1778 } 1779 1780 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1781 1782 state.setVerifierResponse(response.callerUid, response.code); 1783 1784 if (state.isVerificationComplete()) { 1785 mPendingVerification.remove(verificationId); 1786 1787 final InstallArgs args = state.getInstallArgs(); 1788 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1789 1790 int ret; 1791 if (state.isInstallAllowed()) { 1792 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1793 broadcastPackageVerified(verificationId, originUri, 1794 response.code, state.getInstallArgs().getUser()); 1795 try { 1796 ret = args.copyApk(mContainerService, true); 1797 } catch (RemoteException e) { 1798 Slog.e(TAG, "Could not contact the ContainerService"); 1799 } 1800 } else { 1801 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1802 } 1803 1804 Trace.asyncTraceEnd( 1805 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1806 1807 processPendingInstall(args, ret); 1808 mHandler.sendEmptyMessage(MCS_UNBIND); 1809 } 1810 1811 break; 1812 } 1813 case START_INTENT_FILTER_VERIFICATIONS: { 1814 IFVerificationParams params = (IFVerificationParams) msg.obj; 1815 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1816 params.replacing, params.pkg); 1817 break; 1818 } 1819 case INTENT_FILTER_VERIFIED: { 1820 final int verificationId = msg.arg1; 1821 1822 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1823 verificationId); 1824 if (state == null) { 1825 Slog.w(TAG, "Invalid IntentFilter verification token " 1826 + verificationId + " received"); 1827 break; 1828 } 1829 1830 final int userId = state.getUserId(); 1831 1832 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1833 "Processing IntentFilter verification with token:" 1834 + verificationId + " and userId:" + userId); 1835 1836 final IntentFilterVerificationResponse response = 1837 (IntentFilterVerificationResponse) msg.obj; 1838 1839 state.setVerifierResponse(response.callerUid, response.code); 1840 1841 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1842 "IntentFilter verification with token:" + verificationId 1843 + " and userId:" + userId 1844 + " is settings verifier response with response code:" 1845 + response.code); 1846 1847 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1848 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1849 + response.getFailedDomainsString()); 1850 } 1851 1852 if (state.isVerificationComplete()) { 1853 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1854 } else { 1855 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1856 "IntentFilter verification with token:" + verificationId 1857 + " was not said to be complete"); 1858 } 1859 1860 break; 1861 } 1862 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1863 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1864 mInstantAppResolverConnection, 1865 (InstantAppRequest) msg.obj, 1866 mInstantAppInstallerActivity, 1867 mHandler); 1868 } 1869 } 1870 } 1871 } 1872 1873 private PermissionCallback mPermissionCallback = new PermissionCallback() { 1874 @Override 1875 public void onGidsChanged(int appId, int userId) { 1876 mHandler.post(new Runnable() { 1877 @Override 1878 public void run() { 1879 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 1880 } 1881 }); 1882 } 1883 @Override 1884 public void onPermissionGranted(int uid, int userId) { 1885 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1886 1887 // Not critical; if this is lost, the application has to request again. 1888 synchronized (mPackages) { 1889 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 1890 } 1891 } 1892 @Override 1893 public void onInstallPermissionGranted() { 1894 synchronized (mPackages) { 1895 scheduleWriteSettingsLocked(); 1896 } 1897 } 1898 @Override 1899 public void onPermissionRevoked(int uid, int userId) { 1900 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1901 1902 synchronized (mPackages) { 1903 // Critical; after this call the application should never have the permission 1904 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 1905 } 1906 1907 final int appId = UserHandle.getAppId(uid); 1908 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 1909 } 1910 @Override 1911 public void onInstallPermissionRevoked() { 1912 synchronized (mPackages) { 1913 scheduleWriteSettingsLocked(); 1914 } 1915 } 1916 @Override 1917 public void onPermissionUpdated(int[] updatedUserIds, boolean sync) { 1918 synchronized (mPackages) { 1919 for (int userId : updatedUserIds) { 1920 mSettings.writeRuntimePermissionsForUserLPr(userId, sync); 1921 } 1922 } 1923 } 1924 @Override 1925 public void onInstallPermissionUpdated() { 1926 synchronized (mPackages) { 1927 scheduleWriteSettingsLocked(); 1928 } 1929 } 1930 @Override 1931 public void onPermissionRemoved() { 1932 synchronized (mPackages) { 1933 mSettings.writeLPr(); 1934 } 1935 } 1936 }; 1937 1938 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1939 boolean killApp, boolean virtualPreload, String[] grantedPermissions, 1940 boolean launchedForRestore, String installerPackage, 1941 IPackageInstallObserver2 installObserver) { 1942 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1943 // Send the removed broadcasts 1944 if (res.removedInfo != null) { 1945 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1946 } 1947 1948 // Now that we successfully installed the package, grant runtime 1949 // permissions if requested before broadcasting the install. Also 1950 // for legacy apps in permission review mode we clear the permission 1951 // review flag which is used to emulate runtime permissions for 1952 // legacy apps. 1953 if (grantPermissions) { 1954 final int callingUid = Binder.getCallingUid(); 1955 mPermissionManager.grantRequestedRuntimePermissions( 1956 res.pkg, res.newUsers, grantedPermissions, callingUid, 1957 mPermissionCallback); 1958 } 1959 1960 final boolean update = res.removedInfo != null 1961 && res.removedInfo.removedPackage != null; 1962 final String installerPackageName = 1963 res.installerPackageName != null 1964 ? res.installerPackageName 1965 : res.removedInfo != null 1966 ? res.removedInfo.installerPackageName 1967 : null; 1968 1969 // If this is the first time we have child packages for a disabled privileged 1970 // app that had no children, we grant requested runtime permissions to the new 1971 // children if the parent on the system image had them already granted. 1972 if (res.pkg.parentPackage != null) { 1973 final int callingUid = Binder.getCallingUid(); 1974 mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage( 1975 res.pkg, callingUid, mPermissionCallback); 1976 } 1977 1978 synchronized (mPackages) { 1979 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1980 } 1981 1982 final String packageName = res.pkg.applicationInfo.packageName; 1983 1984 // Determine the set of users who are adding this package for 1985 // the first time vs. those who are seeing an update. 1986 int[] firstUserIds = EMPTY_INT_ARRAY; 1987 int[] firstInstantUserIds = EMPTY_INT_ARRAY; 1988 int[] updateUserIds = EMPTY_INT_ARRAY; 1989 int[] instantUserIds = EMPTY_INT_ARRAY; 1990 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1991 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1992 for (int newUser : res.newUsers) { 1993 final boolean isInstantApp = ps.getInstantApp(newUser); 1994 if (allNewUsers) { 1995 if (isInstantApp) { 1996 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 1997 } else { 1998 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 1999 } 2000 continue; 2001 } 2002 boolean isNew = true; 2003 for (int origUser : res.origUsers) { 2004 if (origUser == newUser) { 2005 isNew = false; 2006 break; 2007 } 2008 } 2009 if (isNew) { 2010 if (isInstantApp) { 2011 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 2012 } else { 2013 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 2014 } 2015 } else { 2016 if (isInstantApp) { 2017 instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser); 2018 } else { 2019 updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser); 2020 } 2021 } 2022 } 2023 2024 // Send installed broadcasts if the package is not a static shared lib. 2025 if (res.pkg.staticSharedLibName == null) { 2026 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 2027 2028 // Send added for users that see the package for the first time 2029 // sendPackageAddedForNewUsers also deals with system apps 2030 int appId = UserHandle.getAppId(res.uid); 2031 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 2032 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload, 2033 virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds); 2034 2035 // Send added for users that don't see the package for the first time 2036 Bundle extras = new Bundle(1); 2037 extras.putInt(Intent.EXTRA_UID, res.uid); 2038 if (update) { 2039 extras.putBoolean(Intent.EXTRA_REPLACING, true); 2040 } 2041 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2042 extras, 0 /*flags*/, 2043 null /*targetPackage*/, null /*finishedReceiver*/, 2044 updateUserIds, instantUserIds); 2045 if (installerPackageName != null) { 2046 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2047 extras, 0 /*flags*/, 2048 installerPackageName, null /*finishedReceiver*/, 2049 updateUserIds, instantUserIds); 2050 } 2051 2052 // Send replaced for users that don't see the package for the first time 2053 if (update) { 2054 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 2055 packageName, extras, 0 /*flags*/, 2056 null /*targetPackage*/, null /*finishedReceiver*/, 2057 updateUserIds, instantUserIds); 2058 if (installerPackageName != null) { 2059 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 2060 extras, 0 /*flags*/, 2061 installerPackageName, null /*finishedReceiver*/, 2062 updateUserIds, instantUserIds); 2063 } 2064 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 2065 null /*package*/, null /*extras*/, 0 /*flags*/, 2066 packageName /*targetPackage*/, 2067 null /*finishedReceiver*/, updateUserIds, instantUserIds); 2068 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 2069 // First-install and we did a restore, so we're responsible for the 2070 // first-launch broadcast. 2071 if (DEBUG_BACKUP) { 2072 Slog.i(TAG, "Post-restore of " + packageName 2073 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds)); 2074 } 2075 sendFirstLaunchBroadcast(packageName, installerPackage, 2076 firstUserIds, firstInstantUserIds); 2077 } 2078 2079 // Send broadcast package appeared if forward locked/external for all users 2080 // treat asec-hosted packages like removable media on upgrade 2081 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 2082 if (DEBUG_INSTALL) { 2083 Slog.i(TAG, "upgrading pkg " + res.pkg 2084 + " is ASEC-hosted -> AVAILABLE"); 2085 } 2086 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2087 ArrayList<String> pkgList = new ArrayList<>(1); 2088 pkgList.add(packageName); 2089 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2090 } 2091 } 2092 2093 // Work that needs to happen on first install within each user 2094 if (firstUserIds != null && firstUserIds.length > 0) { 2095 synchronized (mPackages) { 2096 for (int userId : firstUserIds) { 2097 // If this app is a browser and it's newly-installed for some 2098 // users, clear any default-browser state in those users. The 2099 // app's nature doesn't depend on the user, so we can just check 2100 // its browser nature in any user and generalize. 2101 if (packageIsBrowser(packageName, userId)) { 2102 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2103 } 2104 2105 // We may also need to apply pending (restored) runtime 2106 // permission grants within these users. 2107 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2108 } 2109 } 2110 } 2111 2112 if (allNewUsers && !update) { 2113 notifyPackageAdded(packageName); 2114 } 2115 2116 // Log current value of "unknown sources" setting 2117 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2118 getUnknownSourcesSettings()); 2119 2120 // Remove the replaced package's older resources safely now 2121 // We delete after a gc for applications on sdcard. 2122 if (res.removedInfo != null && res.removedInfo.args != null) { 2123 Runtime.getRuntime().gc(); 2124 synchronized (mInstallLock) { 2125 res.removedInfo.args.doPostDeleteLI(true); 2126 } 2127 } else { 2128 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2129 // and not block here. 2130 VMRuntime.getRuntime().requestConcurrentGC(); 2131 } 2132 2133 // Notify DexManager that the package was installed for new users. 2134 // The updated users should already be indexed and the package code paths 2135 // should not change. 2136 // Don't notify the manager for ephemeral apps as they are not expected to 2137 // survive long enough to benefit of background optimizations. 2138 for (int userId : firstUserIds) { 2139 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2140 // There's a race currently where some install events may interleave with an uninstall. 2141 // This can lead to package info being null (b/36642664). 2142 if (info != null) { 2143 mDexManager.notifyPackageInstalled(info, userId); 2144 } 2145 } 2146 } 2147 2148 // If someone is watching installs - notify them 2149 if (installObserver != null) { 2150 try { 2151 Bundle extras = extrasForInstallResult(res); 2152 installObserver.onPackageInstalled(res.name, res.returnCode, 2153 res.returnMsg, extras); 2154 } catch (RemoteException e) { 2155 Slog.i(TAG, "Observer no longer exists."); 2156 } 2157 } 2158 } 2159 2160 private StorageEventListener mStorageListener = new StorageEventListener() { 2161 @Override 2162 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2163 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2164 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2165 final String volumeUuid = vol.getFsUuid(); 2166 2167 // Clean up any users or apps that were removed or recreated 2168 // while this volume was missing 2169 sUserManager.reconcileUsers(volumeUuid); 2170 reconcileApps(volumeUuid); 2171 2172 // Clean up any install sessions that expired or were 2173 // cancelled while this volume was missing 2174 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2175 2176 loadPrivatePackages(vol); 2177 2178 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2179 unloadPrivatePackages(vol); 2180 } 2181 } 2182 } 2183 2184 @Override 2185 public void onVolumeForgotten(String fsUuid) { 2186 if (TextUtils.isEmpty(fsUuid)) { 2187 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2188 return; 2189 } 2190 2191 // Remove any apps installed on the forgotten volume 2192 synchronized (mPackages) { 2193 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2194 for (PackageSetting ps : packages) { 2195 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2196 deletePackageVersioned(new VersionedPackage(ps.name, 2197 PackageManager.VERSION_CODE_HIGHEST), 2198 new LegacyPackageDeleteObserver(null).getBinder(), 2199 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2200 // Try very hard to release any references to this package 2201 // so we don't risk the system server being killed due to 2202 // open FDs 2203 AttributeCache.instance().removePackage(ps.name); 2204 } 2205 2206 mSettings.onVolumeForgotten(fsUuid); 2207 mSettings.writeLPr(); 2208 } 2209 } 2210 }; 2211 2212 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2213 Bundle extras = null; 2214 switch (res.returnCode) { 2215 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2216 extras = new Bundle(); 2217 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2218 res.origPermission); 2219 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2220 res.origPackage); 2221 break; 2222 } 2223 case PackageManager.INSTALL_SUCCEEDED: { 2224 extras = new Bundle(); 2225 extras.putBoolean(Intent.EXTRA_REPLACING, 2226 res.removedInfo != null && res.removedInfo.removedPackage != null); 2227 break; 2228 } 2229 } 2230 return extras; 2231 } 2232 2233 void scheduleWriteSettingsLocked() { 2234 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2235 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2236 } 2237 } 2238 2239 void scheduleWritePackageListLocked(int userId) { 2240 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2241 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2242 msg.arg1 = userId; 2243 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2244 } 2245 } 2246 2247 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2248 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2249 scheduleWritePackageRestrictionsLocked(userId); 2250 } 2251 2252 void scheduleWritePackageRestrictionsLocked(int userId) { 2253 final int[] userIds = (userId == UserHandle.USER_ALL) 2254 ? sUserManager.getUserIds() : new int[]{userId}; 2255 for (int nextUserId : userIds) { 2256 if (!sUserManager.exists(nextUserId)) return; 2257 mDirtyUsers.add(nextUserId); 2258 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2259 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2260 } 2261 } 2262 } 2263 2264 public static PackageManagerService main(Context context, Installer installer, 2265 boolean factoryTest, boolean onlyCore) { 2266 // Self-check for initial settings. 2267 PackageManagerServiceCompilerMapping.checkProperties(); 2268 2269 PackageManagerService m = new PackageManagerService(context, installer, 2270 factoryTest, onlyCore); 2271 m.enableSystemUserPackages(); 2272 ServiceManager.addService("package", m); 2273 final PackageManagerNative pmn = m.new PackageManagerNative(); 2274 ServiceManager.addService("package_native", pmn); 2275 return m; 2276 } 2277 2278 private void enableSystemUserPackages() { 2279 if (!UserManager.isSplitSystemUser()) { 2280 return; 2281 } 2282 // For system user, enable apps based on the following conditions: 2283 // - app is whitelisted or belong to one of these groups: 2284 // -- system app which has no launcher icons 2285 // -- system app which has INTERACT_ACROSS_USERS permission 2286 // -- system IME app 2287 // - app is not in the blacklist 2288 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2289 Set<String> enableApps = new ArraySet<>(); 2290 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2291 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2292 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2293 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2294 enableApps.addAll(wlApps); 2295 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2296 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2297 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2298 enableApps.removeAll(blApps); 2299 Log.i(TAG, "Applications installed for system user: " + enableApps); 2300 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2301 UserHandle.SYSTEM); 2302 final int allAppsSize = allAps.size(); 2303 synchronized (mPackages) { 2304 for (int i = 0; i < allAppsSize; i++) { 2305 String pName = allAps.get(i); 2306 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2307 // Should not happen, but we shouldn't be failing if it does 2308 if (pkgSetting == null) { 2309 continue; 2310 } 2311 boolean install = enableApps.contains(pName); 2312 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2313 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2314 + " for system user"); 2315 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2316 } 2317 } 2318 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2319 } 2320 } 2321 2322 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2323 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2324 Context.DISPLAY_SERVICE); 2325 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2326 } 2327 2328 /** 2329 * Requests that files preopted on a secondary system partition be copied to the data partition 2330 * if possible. Note that the actual copying of the files is accomplished by init for security 2331 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2332 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2333 */ 2334 private static void requestCopyPreoptedFiles() { 2335 final int WAIT_TIME_MS = 100; 2336 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2337 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2338 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2339 // We will wait for up to 100 seconds. 2340 final long timeStart = SystemClock.uptimeMillis(); 2341 final long timeEnd = timeStart + 100 * 1000; 2342 long timeNow = timeStart; 2343 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2344 try { 2345 Thread.sleep(WAIT_TIME_MS); 2346 } catch (InterruptedException e) { 2347 // Do nothing 2348 } 2349 timeNow = SystemClock.uptimeMillis(); 2350 if (timeNow > timeEnd) { 2351 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2352 Slog.wtf(TAG, "cppreopt did not finish!"); 2353 break; 2354 } 2355 } 2356 2357 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2358 } 2359 } 2360 2361 public PackageManagerService(Context context, Installer installer, 2362 boolean factoryTest, boolean onlyCore) { 2363 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2364 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2365 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2366 SystemClock.uptimeMillis()); 2367 2368 if (mSdkVersion <= 0) { 2369 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2370 } 2371 2372 mContext = context; 2373 2374 mFactoryTest = factoryTest; 2375 mOnlyCore = onlyCore; 2376 mMetrics = new DisplayMetrics(); 2377 mInstaller = installer; 2378 2379 // Create sub-components that provide services / data. Order here is important. 2380 synchronized (mInstallLock) { 2381 synchronized (mPackages) { 2382 // Expose private service for system components to use. 2383 LocalServices.addService( 2384 PackageManagerInternal.class, new PackageManagerInternalImpl()); 2385 sUserManager = new UserManagerService(context, this, 2386 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2387 mPermissionManager = PermissionManagerService.create(context, 2388 new DefaultPermissionGrantedCallback() { 2389 @Override 2390 public void onDefaultRuntimePermissionsGranted(int userId) { 2391 synchronized(mPackages) { 2392 mSettings.onDefaultRuntimePermissionsGrantedLPr(userId); 2393 } 2394 } 2395 }, mPackages /*externalLock*/); 2396 mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy(); 2397 mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages); 2398 } 2399 } 2400 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2401 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2402 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2403 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2404 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2405 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2406 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2407 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2408 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2409 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2410 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2411 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2412 mSettings.addSharedUserLPw("android.uid.se", SE_UID, 2413 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2414 2415 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2416 if (separateProcesses != null && separateProcesses.length() > 0) { 2417 if ("*".equals(separateProcesses)) { 2418 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2419 mSeparateProcesses = null; 2420 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2421 } else { 2422 mDefParseFlags = 0; 2423 mSeparateProcesses = separateProcesses.split(","); 2424 Slog.w(TAG, "Running with debug.separate_processes: " 2425 + separateProcesses); 2426 } 2427 } else { 2428 mDefParseFlags = 0; 2429 mSeparateProcesses = null; 2430 } 2431 2432 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2433 "*dexopt*"); 2434 DexManager.Listener dexManagerListener = DexLogger.getListener(this, 2435 installer, mInstallLock); 2436 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock, 2437 dexManagerListener); 2438 mArtManagerService = new ArtManagerService(this, installer, mInstallLock); 2439 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2440 2441 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2442 FgThread.get().getLooper()); 2443 2444 getDefaultDisplayMetrics(context, mMetrics); 2445 2446 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2447 SystemConfig systemConfig = SystemConfig.getInstance(); 2448 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2449 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2450 2451 mProtectedPackages = new ProtectedPackages(mContext); 2452 2453 synchronized (mInstallLock) { 2454 // writer 2455 synchronized (mPackages) { 2456 mHandlerThread = new ServiceThread(TAG, 2457 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2458 mHandlerThread.start(); 2459 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2460 mProcessLoggingHandler = new ProcessLoggingHandler(); 2461 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2462 mInstantAppRegistry = new InstantAppRegistry(this); 2463 2464 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2465 final int builtInLibCount = libConfig.size(); 2466 for (int i = 0; i < builtInLibCount; i++) { 2467 String name = libConfig.keyAt(i); 2468 String path = libConfig.valueAt(i); 2469 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2470 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2471 } 2472 2473 SELinuxMMAC.readInstallPolicy(); 2474 2475 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2476 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2477 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2478 2479 // Clean up orphaned packages for which the code path doesn't exist 2480 // and they are an update to a system app - caused by bug/32321269 2481 final int packageSettingCount = mSettings.mPackages.size(); 2482 for (int i = packageSettingCount - 1; i >= 0; i--) { 2483 PackageSetting ps = mSettings.mPackages.valueAt(i); 2484 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2485 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2486 mSettings.mPackages.removeAt(i); 2487 mSettings.enableSystemPackageLPw(ps.name); 2488 } 2489 } 2490 2491 if (mFirstBoot) { 2492 requestCopyPreoptedFiles(); 2493 } 2494 2495 String customResolverActivity = Resources.getSystem().getString( 2496 R.string.config_customResolverActivity); 2497 if (TextUtils.isEmpty(customResolverActivity)) { 2498 customResolverActivity = null; 2499 } else { 2500 mCustomResolverComponentName = ComponentName.unflattenFromString( 2501 customResolverActivity); 2502 } 2503 2504 long startTime = SystemClock.uptimeMillis(); 2505 2506 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2507 startTime); 2508 2509 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2510 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2511 2512 if (bootClassPath == null) { 2513 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2514 } 2515 2516 if (systemServerClassPath == null) { 2517 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2518 } 2519 2520 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2521 2522 final VersionInfo ver = mSettings.getInternalVersion(); 2523 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2524 if (mIsUpgrade) { 2525 logCriticalInfo(Log.INFO, 2526 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2527 } 2528 2529 // when upgrading from pre-M, promote system app permissions from install to runtime 2530 mPromoteSystemApps = 2531 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2532 2533 // When upgrading from pre-N, we need to handle package extraction like first boot, 2534 // as there is no profiling data available. 2535 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2536 2537 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2538 2539 // save off the names of pre-existing system packages prior to scanning; we don't 2540 // want to automatically grant runtime permissions for new system apps 2541 if (mPromoteSystemApps) { 2542 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2543 while (pkgSettingIter.hasNext()) { 2544 PackageSetting ps = pkgSettingIter.next(); 2545 if (isSystemApp(ps)) { 2546 mExistingSystemPackages.add(ps.name); 2547 } 2548 } 2549 } 2550 2551 mCacheDir = preparePackageParserCache(mIsUpgrade); 2552 2553 // Set flag to monitor and not change apk file paths when 2554 // scanning install directories. 2555 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2556 2557 if (mIsUpgrade || mFirstBoot) { 2558 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2559 } 2560 2561 // Collect vendor/product overlay packages. (Do this before scanning any apps.) 2562 // For security and version matching reason, only consider 2563 // overlay packages if they reside in the right directory. 2564 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), 2565 mDefParseFlags 2566 | PackageParser.PARSE_IS_SYSTEM_DIR, 2567 scanFlags 2568 | SCAN_AS_SYSTEM 2569 | SCAN_AS_VENDOR, 2570 0); 2571 scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR), 2572 mDefParseFlags 2573 | PackageParser.PARSE_IS_SYSTEM_DIR, 2574 scanFlags 2575 | SCAN_AS_SYSTEM 2576 | SCAN_AS_PRODUCT, 2577 0); 2578 2579 mParallelPackageParserCallback.findStaticOverlayPackages(); 2580 2581 // Find base frameworks (resource packages without code). 2582 scanDirTracedLI(frameworkDir, 2583 mDefParseFlags 2584 | PackageParser.PARSE_IS_SYSTEM_DIR, 2585 scanFlags 2586 | SCAN_NO_DEX 2587 | SCAN_AS_SYSTEM 2588 | SCAN_AS_PRIVILEGED, 2589 0); 2590 2591 // Collected privileged system packages. 2592 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2593 scanDirTracedLI(privilegedAppDir, 2594 mDefParseFlags 2595 | PackageParser.PARSE_IS_SYSTEM_DIR, 2596 scanFlags 2597 | SCAN_AS_SYSTEM 2598 | SCAN_AS_PRIVILEGED, 2599 0); 2600 2601 // Collect ordinary system packages. 2602 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2603 scanDirTracedLI(systemAppDir, 2604 mDefParseFlags 2605 | PackageParser.PARSE_IS_SYSTEM_DIR, 2606 scanFlags 2607 | SCAN_AS_SYSTEM, 2608 0); 2609 2610 // Collected privileged vendor packages. 2611 File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 2612 try { 2613 privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile(); 2614 } catch (IOException e) { 2615 // failed to look up canonical path, continue with original one 2616 } 2617 scanDirTracedLI(privilegedVendorAppDir, 2618 mDefParseFlags 2619 | PackageParser.PARSE_IS_SYSTEM_DIR, 2620 scanFlags 2621 | SCAN_AS_SYSTEM 2622 | SCAN_AS_VENDOR 2623 | SCAN_AS_PRIVILEGED, 2624 0); 2625 2626 // Collect ordinary vendor packages. 2627 File vendorAppDir = new File(Environment.getVendorDirectory(), "app"); 2628 try { 2629 vendorAppDir = vendorAppDir.getCanonicalFile(); 2630 } catch (IOException e) { 2631 // failed to look up canonical path, continue with original one 2632 } 2633 scanDirTracedLI(vendorAppDir, 2634 mDefParseFlags 2635 | PackageParser.PARSE_IS_SYSTEM_DIR, 2636 scanFlags 2637 | SCAN_AS_SYSTEM 2638 | SCAN_AS_VENDOR, 2639 0); 2640 2641 // Collect all OEM packages. 2642 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2643 scanDirTracedLI(oemAppDir, 2644 mDefParseFlags 2645 | PackageParser.PARSE_IS_SYSTEM_DIR, 2646 scanFlags 2647 | SCAN_AS_SYSTEM 2648 | SCAN_AS_OEM, 2649 0); 2650 2651 // Collected privileged product packages. 2652 File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 2653 try { 2654 privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile(); 2655 } catch (IOException e) { 2656 // failed to look up canonical path, continue with original one 2657 } 2658 scanDirTracedLI(privilegedProductAppDir, 2659 mDefParseFlags 2660 | PackageParser.PARSE_IS_SYSTEM_DIR, 2661 scanFlags 2662 | SCAN_AS_SYSTEM 2663 | SCAN_AS_PRODUCT 2664 | SCAN_AS_PRIVILEGED, 2665 0); 2666 2667 // Collect ordinary product packages. 2668 File productAppDir = new File(Environment.getProductDirectory(), "app"); 2669 try { 2670 productAppDir = productAppDir.getCanonicalFile(); 2671 } catch (IOException e) { 2672 // failed to look up canonical path, continue with original one 2673 } 2674 scanDirTracedLI(productAppDir, 2675 mDefParseFlags 2676 | PackageParser.PARSE_IS_SYSTEM_DIR, 2677 scanFlags 2678 | SCAN_AS_SYSTEM 2679 | SCAN_AS_PRODUCT, 2680 0); 2681 2682 // Prune any system packages that no longer exist. 2683 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>(); 2684 // Stub packages must either be replaced with full versions in the /data 2685 // partition or be disabled. 2686 final List<String> stubSystemApps = new ArrayList<>(); 2687 if (!mOnlyCore) { 2688 // do this first before mucking with mPackages for the "expecting better" case 2689 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator(); 2690 while (pkgIterator.hasNext()) { 2691 final PackageParser.Package pkg = pkgIterator.next(); 2692 if (pkg.isStub) { 2693 stubSystemApps.add(pkg.packageName); 2694 } 2695 } 2696 2697 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2698 while (psit.hasNext()) { 2699 PackageSetting ps = psit.next(); 2700 2701 /* 2702 * If this is not a system app, it can't be a 2703 * disable system app. 2704 */ 2705 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2706 continue; 2707 } 2708 2709 /* 2710 * If the package is scanned, it's not erased. 2711 */ 2712 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2713 if (scannedPkg != null) { 2714 /* 2715 * If the system app is both scanned and in the 2716 * disabled packages list, then it must have been 2717 * added via OTA. Remove it from the currently 2718 * scanned package so the previously user-installed 2719 * application can be scanned. 2720 */ 2721 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2722 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2723 + ps.name + "; removing system app. Last known codePath=" 2724 + ps.codePathString + ", installStatus=" + ps.installStatus 2725 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2726 + scannedPkg.getLongVersionCode()); 2727 removePackageLI(scannedPkg, true); 2728 mExpectingBetter.put(ps.name, ps.codePath); 2729 } 2730 2731 continue; 2732 } 2733 2734 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2735 psit.remove(); 2736 logCriticalInfo(Log.WARN, "System package " + ps.name 2737 + " no longer exists; it's data will be wiped"); 2738 // Actual deletion of code and data will be handled by later 2739 // reconciliation step 2740 } else { 2741 // we still have a disabled system package, but, it still might have 2742 // been removed. check the code path still exists and check there's 2743 // still a package. the latter can happen if an OTA keeps the same 2744 // code path, but, changes the package name. 2745 final PackageSetting disabledPs = 2746 mSettings.getDisabledSystemPkgLPr(ps.name); 2747 if (disabledPs.codePath == null || !disabledPs.codePath.exists() 2748 || disabledPs.pkg == null) { 2749if (REFACTOR_DEBUG) { 2750Slog.e("TODD", 2751 "Possibly deleted app: " + ps.dumpState_temp() 2752 + "; path: " + (disabledPs.codePath == null ? "<<NULL>>":disabledPs.codePath) 2753 + "; pkg: " + (disabledPs.pkg==null?"<<NULL>>":disabledPs.pkg.toString())); 2754} 2755 possiblyDeletedUpdatedSystemApps.add(ps.name); 2756 } 2757 } 2758 } 2759 } 2760 2761 //look for any incomplete package installations 2762 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2763 for (int i = 0; i < deletePkgsList.size(); i++) { 2764 // Actual deletion of code and data will be handled by later 2765 // reconciliation step 2766 final String packageName = deletePkgsList.get(i).name; 2767 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2768 synchronized (mPackages) { 2769 mSettings.removePackageLPw(packageName); 2770 } 2771 } 2772 2773 //delete tmp files 2774 deleteTempPackageFiles(); 2775 2776 final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get(); 2777 2778 // Remove any shared userIDs that have no associated packages 2779 mSettings.pruneSharedUsersLPw(); 2780 final long systemScanTime = SystemClock.uptimeMillis() - startTime; 2781 final int systemPackagesCount = mPackages.size(); 2782 Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime 2783 + " ms, packageCount: " + systemPackagesCount 2784 + " , timePerPackage: " 2785 + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount) 2786 + " , cached: " + cachedSystemApps); 2787 if (mIsUpgrade && systemPackagesCount > 0) { 2788 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time", 2789 ((int) systemScanTime) / systemPackagesCount); 2790 } 2791 if (!mOnlyCore) { 2792 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2793 SystemClock.uptimeMillis()); 2794 scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2795 2796 scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags 2797 | PackageParser.PARSE_FORWARD_LOCK, 2798 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2799 2800 // Remove disable package settings for updated system apps that were 2801 // removed via an OTA. If the update is no longer present, remove the 2802 // app completely. Otherwise, revoke their system privileges. 2803 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2804 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2805 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2806if (REFACTOR_DEBUG) { 2807Slog.e("TODD", 2808 "remove update; name: " + deletedAppName + ", exists? " + (deletedPkg != null)); 2809} 2810 final String msg; 2811 if (deletedPkg == null) { 2812 // should have found an update, but, we didn't; remove everything 2813 msg = "Updated system package " + deletedAppName 2814 + " no longer exists; removing its data"; 2815 // Actual deletion of code and data will be handled by later 2816 // reconciliation step 2817 } else { 2818 // found an update; revoke system privileges 2819 msg = "Updated system package + " + deletedAppName 2820 + " no longer exists; revoking system privileges"; 2821 2822 // Don't do anything if a stub is removed from the system image. If 2823 // we were to remove the uncompressed version from the /data partition, 2824 // this is where it'd be done. 2825 2826 final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2827 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2828 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2829 } 2830 logCriticalInfo(Log.WARN, msg); 2831 } 2832 2833 /* 2834 * Make sure all system apps that we expected to appear on 2835 * the userdata partition actually showed up. If they never 2836 * appeared, crawl back and revive the system version. 2837 */ 2838 for (int i = 0; i < mExpectingBetter.size(); i++) { 2839 final String packageName = mExpectingBetter.keyAt(i); 2840 if (!mPackages.containsKey(packageName)) { 2841 final File scanFile = mExpectingBetter.valueAt(i); 2842 2843 logCriticalInfo(Log.WARN, "Expected better " + packageName 2844 + " but never showed up; reverting to system"); 2845 2846 final @ParseFlags int reparseFlags; 2847 final @ScanFlags int rescanFlags; 2848 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2849 reparseFlags = 2850 mDefParseFlags | 2851 PackageParser.PARSE_IS_SYSTEM_DIR; 2852 rescanFlags = 2853 scanFlags 2854 | SCAN_AS_SYSTEM 2855 | SCAN_AS_PRIVILEGED; 2856 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2857 reparseFlags = 2858 mDefParseFlags | 2859 PackageParser.PARSE_IS_SYSTEM_DIR; 2860 rescanFlags = 2861 scanFlags 2862 | SCAN_AS_SYSTEM; 2863 } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) { 2864 reparseFlags = 2865 mDefParseFlags | 2866 PackageParser.PARSE_IS_SYSTEM_DIR; 2867 rescanFlags = 2868 scanFlags 2869 | SCAN_AS_SYSTEM 2870 | SCAN_AS_VENDOR 2871 | SCAN_AS_PRIVILEGED; 2872 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2873 reparseFlags = 2874 mDefParseFlags | 2875 PackageParser.PARSE_IS_SYSTEM_DIR; 2876 rescanFlags = 2877 scanFlags 2878 | SCAN_AS_SYSTEM 2879 | SCAN_AS_VENDOR; 2880 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2881 reparseFlags = 2882 mDefParseFlags | 2883 PackageParser.PARSE_IS_SYSTEM_DIR; 2884 rescanFlags = 2885 scanFlags 2886 | SCAN_AS_SYSTEM 2887 | SCAN_AS_OEM; 2888 } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) { 2889 reparseFlags = 2890 mDefParseFlags | 2891 PackageParser.PARSE_IS_SYSTEM_DIR; 2892 rescanFlags = 2893 scanFlags 2894 | SCAN_AS_SYSTEM 2895 | SCAN_AS_PRODUCT 2896 | SCAN_AS_PRIVILEGED; 2897 } else if (FileUtils.contains(productAppDir, scanFile)) { 2898 reparseFlags = 2899 mDefParseFlags | 2900 PackageParser.PARSE_IS_SYSTEM_DIR; 2901 rescanFlags = 2902 scanFlags 2903 | SCAN_AS_SYSTEM 2904 | SCAN_AS_PRODUCT; 2905 } else { 2906 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2907 continue; 2908 } 2909 2910 mSettings.enableSystemPackageLPw(packageName); 2911 2912 try { 2913 scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null); 2914 } catch (PackageManagerException e) { 2915 Slog.e(TAG, "Failed to parse original system package: " 2916 + e.getMessage()); 2917 } 2918 } 2919 } 2920 2921 // Uncompress and install any stubbed system applications. 2922 // This must be done last to ensure all stubs are replaced or disabled. 2923 decompressSystemApplications(stubSystemApps, scanFlags); 2924 2925 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get() 2926 - cachedSystemApps; 2927 2928 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime; 2929 final int dataPackagesCount = mPackages.size() - systemPackagesCount; 2930 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime 2931 + " ms, packageCount: " + dataPackagesCount 2932 + " , timePerPackage: " 2933 + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) 2934 + " , cached: " + cachedNonSystemApps); 2935 if (mIsUpgrade && dataPackagesCount > 0) { 2936 MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time", 2937 ((int) dataScanTime) / dataPackagesCount); 2938 } 2939 } 2940 mExpectingBetter.clear(); 2941 2942 // Resolve the storage manager. 2943 mStorageManagerPackage = getStorageManagerPackageName(); 2944 2945 // Resolve protected action filters. Only the setup wizard is allowed to 2946 // have a high priority filter for these actions. 2947 mSetupWizardPackage = getSetupWizardPackageName(); 2948 if (mProtectedFilters.size() > 0) { 2949 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2950 Slog.i(TAG, "No setup wizard;" 2951 + " All protected intents capped to priority 0"); 2952 } 2953 for (ActivityIntentInfo filter : mProtectedFilters) { 2954 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2955 if (DEBUG_FILTERS) { 2956 Slog.i(TAG, "Found setup wizard;" 2957 + " allow priority " + filter.getPriority() + ";" 2958 + " package: " + filter.activity.info.packageName 2959 + " activity: " + filter.activity.className 2960 + " priority: " + filter.getPriority()); 2961 } 2962 // skip setup wizard; allow it to keep the high priority filter 2963 continue; 2964 } 2965 if (DEBUG_FILTERS) { 2966 Slog.i(TAG, "Protected action; cap priority to 0;" 2967 + " package: " + filter.activity.info.packageName 2968 + " activity: " + filter.activity.className 2969 + " origPrio: " + filter.getPriority()); 2970 } 2971 filter.setPriority(0); 2972 } 2973 } 2974 mDeferProtectedFilters = false; 2975 mProtectedFilters.clear(); 2976 2977 // Now that we know all of the shared libraries, update all clients to have 2978 // the correct library paths. 2979 updateAllSharedLibrariesLPw(null); 2980 2981 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2982 // NOTE: We ignore potential failures here during a system scan (like 2983 // the rest of the commands above) because there's precious little we 2984 // can do about it. A settings error is reported, though. 2985 final List<String> changedAbiCodePath = 2986 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2987 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 2988 for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) { 2989 final String codePathString = changedAbiCodePath.get(i); 2990 try { 2991 mInstaller.rmdex(codePathString, 2992 getDexCodeInstructionSet(getPreferredInstructionSet())); 2993 } catch (InstallerException ignored) { 2994 } 2995 } 2996 } 2997 } 2998 2999 // Now that we know all the packages we are keeping, 3000 // read and update their last usage times. 3001 mPackageUsage.read(mPackages); 3002 mCompilerStats.read(); 3003 3004 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 3005 SystemClock.uptimeMillis()); 3006 Slog.i(TAG, "Time to scan packages: " 3007 + ((SystemClock.uptimeMillis()-startTime)/1000f) 3008 + " seconds"); 3009 3010 // If the platform SDK has changed since the last time we booted, 3011 // we need to re-grant app permission to catch any new ones that 3012 // appear. This is really a hack, and means that apps can in some 3013 // cases get permissions that the user didn't initially explicitly 3014 // allow... it would be nice to have some better way to handle 3015 // this situation. 3016 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 3017 if (sdkUpdated) { 3018 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 3019 + mSdkVersion + "; regranting permissions for internal storage"); 3020 } 3021 mPermissionManager.updateAllPermissions( 3022 StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(), 3023 mPermissionCallback); 3024 ver.sdkVersion = mSdkVersion; 3025 3026 // If this is the first boot or an update from pre-M, and it is a normal 3027 // boot, then we need to initialize the default preferred apps across 3028 // all defined users. 3029 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 3030 for (UserInfo user : sUserManager.getUsers(true)) { 3031 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 3032 applyFactoryDefaultBrowserLPw(user.id); 3033 primeDomainVerificationsLPw(user.id); 3034 } 3035 } 3036 3037 // Prepare storage for system user really early during boot, 3038 // since core system apps like SettingsProvider and SystemUI 3039 // can't wait for user to start 3040 final int storageFlags; 3041 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3042 storageFlags = StorageManager.FLAG_STORAGE_DE; 3043 } else { 3044 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 3045 } 3046 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 3047 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 3048 true /* onlyCoreApps */); 3049 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 3050 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync", 3051 Trace.TRACE_TAG_PACKAGE_MANAGER); 3052 traceLog.traceBegin("AppDataFixup"); 3053 try { 3054 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 3055 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 3056 } catch (InstallerException e) { 3057 Slog.w(TAG, "Trouble fixing GIDs", e); 3058 } 3059 traceLog.traceEnd(); 3060 3061 traceLog.traceBegin("AppDataPrepare"); 3062 if (deferPackages == null || deferPackages.isEmpty()) { 3063 return; 3064 } 3065 int count = 0; 3066 for (String pkgName : deferPackages) { 3067 PackageParser.Package pkg = null; 3068 synchronized (mPackages) { 3069 PackageSetting ps = mSettings.getPackageLPr(pkgName); 3070 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 3071 pkg = ps.pkg; 3072 } 3073 } 3074 if (pkg != null) { 3075 synchronized (mInstallLock) { 3076 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 3077 true /* maybeMigrateAppData */); 3078 } 3079 count++; 3080 } 3081 } 3082 traceLog.traceEnd(); 3083 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 3084 }, "prepareAppData"); 3085 3086 // If this is first boot after an OTA, and a normal boot, then 3087 // we need to clear code cache directories. 3088 // Note that we do *not* clear the application profiles. These remain valid 3089 // across OTAs and are used to drive profile verification (post OTA) and 3090 // profile compilation (without waiting to collect a fresh set of profiles). 3091 if (mIsUpgrade && !onlyCore) { 3092 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 3093 for (int i = 0; i < mSettings.mPackages.size(); i++) { 3094 final PackageSetting ps = mSettings.mPackages.valueAt(i); 3095 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 3096 // No apps are running this early, so no need to freeze 3097 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 3098 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 3099 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 3100 } 3101 } 3102 ver.fingerprint = Build.FINGERPRINT; 3103 } 3104 3105 checkDefaultBrowser(); 3106 3107 // clear only after permissions and other defaults have been updated 3108 mExistingSystemPackages.clear(); 3109 mPromoteSystemApps = false; 3110 3111 // All the changes are done during package scanning. 3112 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 3113 3114 // can downgrade to reader 3115 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 3116 mSettings.writeLPr(); 3117 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3118 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 3119 SystemClock.uptimeMillis()); 3120 3121 if (!mOnlyCore) { 3122 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 3123 mRequiredInstallerPackage = getRequiredInstallerLPr(); 3124 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 3125 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 3126 if (mIntentFilterVerifierComponent != null) { 3127 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 3128 mIntentFilterVerifierComponent); 3129 } else { 3130 mIntentFilterVerifier = null; 3131 } 3132 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3133 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 3134 SharedLibraryInfo.VERSION_UNDEFINED); 3135 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3136 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 3137 SharedLibraryInfo.VERSION_UNDEFINED); 3138 } else { 3139 mRequiredVerifierPackage = null; 3140 mRequiredInstallerPackage = null; 3141 mRequiredUninstallerPackage = null; 3142 mIntentFilterVerifierComponent = null; 3143 mIntentFilterVerifier = null; 3144 mServicesSystemSharedLibraryPackageName = null; 3145 mSharedSystemSharedLibraryPackageName = null; 3146 } 3147 3148 mInstallerService = new PackageInstallerService(context, this); 3149 final Pair<ComponentName, String> instantAppResolverComponent = 3150 getInstantAppResolverLPr(); 3151 if (instantAppResolverComponent != null) { 3152 if (DEBUG_INSTANT) { 3153 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 3154 } 3155 mInstantAppResolverConnection = new InstantAppResolverConnection( 3156 mContext, instantAppResolverComponent.first, 3157 instantAppResolverComponent.second); 3158 mInstantAppResolverSettingsComponent = 3159 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 3160 } else { 3161 mInstantAppResolverConnection = null; 3162 mInstantAppResolverSettingsComponent = null; 3163 } 3164 updateInstantAppInstallerLocked(null); 3165 3166 // Read and update the usage of dex files. 3167 // Do this at the end of PM init so that all the packages have their 3168 // data directory reconciled. 3169 // At this point we know the code paths of the packages, so we can validate 3170 // the disk file and build the internal cache. 3171 // The usage file is expected to be small so loading and verifying it 3172 // should take a fairly small time compare to the other activities (e.g. package 3173 // scanning). 3174 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3175 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 3176 for (int userId : currentUserIds) { 3177 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3178 } 3179 mDexManager.load(userPackages); 3180 if (mIsUpgrade) { 3181 MetricsLogger.histogram(null, "ota_package_manager_init_time", 3182 (int) (SystemClock.uptimeMillis() - startTime)); 3183 } 3184 } // synchronized (mPackages) 3185 } // synchronized (mInstallLock) 3186 3187 // Now after opening every single application zip, make sure they 3188 // are all flushed. Not really needed, but keeps things nice and 3189 // tidy. 3190 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3191 Runtime.getRuntime().gc(); 3192 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3193 3194 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 3195 FallbackCategoryProvider.loadFallbacks(); 3196 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3197 3198 // The initial scanning above does many calls into installd while 3199 // holding the mPackages lock, but we're mostly interested in yelling 3200 // once we have a booted system. 3201 mInstaller.setWarnIfHeld(mPackages); 3202 3203 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3204 } 3205 3206 /** 3207 * Uncompress and install stub applications. 3208 * <p>In order to save space on the system partition, some applications are shipped in a 3209 * compressed form. In addition the compressed bits for the full application, the 3210 * system image contains a tiny stub comprised of only the Android manifest. 3211 * <p>During the first boot, attempt to uncompress and install the full application. If 3212 * the application can't be installed for any reason, disable the stub and prevent 3213 * uncompressing the full application during future boots. 3214 * <p>In order to forcefully attempt an installation of a full application, go to app 3215 * settings and enable the application. 3216 */ 3217 private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) { 3218 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3219 final String pkgName = stubSystemApps.get(i); 3220 // skip if the system package is already disabled 3221 if (mSettings.isDisabledSystemPackageLPr(pkgName)) { 3222 stubSystemApps.remove(i); 3223 continue; 3224 } 3225 // skip if the package isn't installed (?!); this should never happen 3226 final PackageParser.Package pkg = mPackages.get(pkgName); 3227 if (pkg == null) { 3228 stubSystemApps.remove(i); 3229 continue; 3230 } 3231 // skip if the package has been disabled by the user 3232 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3233 if (ps != null) { 3234 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM); 3235 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) { 3236 stubSystemApps.remove(i); 3237 continue; 3238 } 3239 } 3240 3241 if (DEBUG_COMPRESSION) { 3242 Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName); 3243 } 3244 3245 // uncompress the binary to its eventual destination on /data 3246 final File scanFile = decompressPackage(pkg); 3247 if (scanFile == null) { 3248 continue; 3249 } 3250 3251 // install the package to replace the stub on /system 3252 try { 3253 mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/); 3254 removePackageLI(pkg, true /*chatty*/); 3255 scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null); 3256 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 3257 UserHandle.USER_SYSTEM, "android"); 3258 stubSystemApps.remove(i); 3259 continue; 3260 } catch (PackageManagerException e) { 3261 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage()); 3262 } 3263 3264 // any failed attempt to install the package will be cleaned up later 3265 } 3266 3267 // disable any stub still left; these failed to install the full application 3268 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3269 final String pkgName = stubSystemApps.get(i); 3270 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3271 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 3272 UserHandle.USER_SYSTEM, "android"); 3273 logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName); 3274 } 3275 } 3276 3277 /** 3278 * Decompresses the given package on the system image onto 3279 * the /data partition. 3280 * @return The directory the package was decompressed into. Otherwise, {@code null}. 3281 */ 3282 private File decompressPackage(PackageParser.Package pkg) { 3283 final File[] compressedFiles = getCompressedFiles(pkg.codePath); 3284 if (compressedFiles == null || compressedFiles.length == 0) { 3285 if (DEBUG_COMPRESSION) { 3286 Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath); 3287 } 3288 return null; 3289 } 3290 final File dstCodePath = 3291 getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName); 3292 int ret = PackageManager.INSTALL_SUCCEEDED; 3293 try { 3294 Os.mkdir(dstCodePath.getAbsolutePath(), 0755); 3295 Os.chmod(dstCodePath.getAbsolutePath(), 0755); 3296 for (File srcFile : compressedFiles) { 3297 final String srcFileName = srcFile.getName(); 3298 final String dstFileName = srcFileName.substring( 3299 0, srcFileName.length() - COMPRESSED_EXTENSION.length()); 3300 final File dstFile = new File(dstCodePath, dstFileName); 3301 ret = decompressFile(srcFile, dstFile); 3302 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3303 logCriticalInfo(Log.ERROR, "Failed to decompress" 3304 + "; pkg: " + pkg.packageName 3305 + ", file: " + dstFileName); 3306 break; 3307 } 3308 } 3309 } catch (ErrnoException e) { 3310 logCriticalInfo(Log.ERROR, "Failed to decompress" 3311 + "; pkg: " + pkg.packageName 3312 + ", err: " + e.errno); 3313 } 3314 if (ret == PackageManager.INSTALL_SUCCEEDED) { 3315 final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME); 3316 NativeLibraryHelper.Handle handle = null; 3317 try { 3318 handle = NativeLibraryHelper.Handle.create(dstCodePath); 3319 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 3320 null /*abiOverride*/); 3321 } catch (IOException e) { 3322 logCriticalInfo(Log.ERROR, "Failed to extract native libraries" 3323 + "; pkg: " + pkg.packageName); 3324 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3325 } finally { 3326 IoUtils.closeQuietly(handle); 3327 } 3328 } 3329 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3330 if (dstCodePath == null || !dstCodePath.exists()) { 3331 return null; 3332 } 3333 removeCodePathLI(dstCodePath); 3334 return null; 3335 } 3336 3337 return dstCodePath; 3338 } 3339 3340 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3341 // we're only interested in updating the installer appliction when 1) it's not 3342 // already set or 2) the modified package is the installer 3343 if (mInstantAppInstallerActivity != null 3344 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3345 .equals(modifiedPackage)) { 3346 return; 3347 } 3348 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3349 } 3350 3351 private static File preparePackageParserCache(boolean isUpgrade) { 3352 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3353 return null; 3354 } 3355 3356 // Disable package parsing on eng builds to allow for faster incremental development. 3357 if (Build.IS_ENG) { 3358 return null; 3359 } 3360 3361 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3362 Slog.i(TAG, "Disabling package parser cache due to system property."); 3363 return null; 3364 } 3365 3366 // The base directory for the package parser cache lives under /data/system/. 3367 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3368 "package_cache"); 3369 if (cacheBaseDir == null) { 3370 return null; 3371 } 3372 3373 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3374 // This also serves to "GC" unused entries when the package cache version changes (which 3375 // can only happen during upgrades). 3376 if (isUpgrade) { 3377 FileUtils.deleteContents(cacheBaseDir); 3378 } 3379 3380 3381 // Return the versioned package cache directory. This is something like 3382 // "/data/system/package_cache/1" 3383 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3384 3385 // The following is a workaround to aid development on non-numbered userdebug 3386 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3387 // the system partition is newer. 3388 // 3389 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3390 // that starts with "eng." to signify that this is an engineering build and not 3391 // destined for release. 3392 if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3393 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3394 3395 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3396 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3397 // in general and should not be used for production changes. In this specific case, 3398 // we know that they will work. 3399 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3400 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3401 FileUtils.deleteContents(cacheBaseDir); 3402 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3403 } 3404 } 3405 3406 return cacheDir; 3407 } 3408 3409 @Override 3410 public boolean isFirstBoot() { 3411 // allow instant applications 3412 return mFirstBoot; 3413 } 3414 3415 @Override 3416 public boolean isOnlyCoreApps() { 3417 // allow instant applications 3418 return mOnlyCore; 3419 } 3420 3421 @Override 3422 public boolean isUpgrade() { 3423 // allow instant applications 3424 // The system property allows testing ota flow when upgraded to the same image. 3425 return mIsUpgrade || SystemProperties.getBoolean( 3426 "persist.pm.mock-upgrade", false /* default */); 3427 } 3428 3429 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3430 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3431 3432 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3433 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3434 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3435 if (matches.size() == 1) { 3436 return matches.get(0).getComponentInfo().packageName; 3437 } else if (matches.size() == 0) { 3438 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3439 return null; 3440 } 3441 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3442 } 3443 3444 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3445 synchronized (mPackages) { 3446 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3447 if (libraryEntry == null) { 3448 throw new IllegalStateException("Missing required shared library:" + name); 3449 } 3450 return libraryEntry.apk; 3451 } 3452 } 3453 3454 private @NonNull String getRequiredInstallerLPr() { 3455 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3456 intent.addCategory(Intent.CATEGORY_DEFAULT); 3457 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3458 3459 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3460 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3461 UserHandle.USER_SYSTEM); 3462 if (matches.size() == 1) { 3463 ResolveInfo resolveInfo = matches.get(0); 3464 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3465 throw new RuntimeException("The installer must be a privileged app"); 3466 } 3467 return matches.get(0).getComponentInfo().packageName; 3468 } else { 3469 throw new RuntimeException("There must be exactly one installer; found " + matches); 3470 } 3471 } 3472 3473 private @NonNull String getRequiredUninstallerLPr() { 3474 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3475 intent.addCategory(Intent.CATEGORY_DEFAULT); 3476 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3477 3478 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3479 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3480 UserHandle.USER_SYSTEM); 3481 if (resolveInfo == null || 3482 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3483 throw new RuntimeException("There must be exactly one uninstaller; found " 3484 + resolveInfo); 3485 } 3486 return resolveInfo.getComponentInfo().packageName; 3487 } 3488 3489 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3490 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3491 3492 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3493 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3494 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3495 ResolveInfo best = null; 3496 final int N = matches.size(); 3497 for (int i = 0; i < N; i++) { 3498 final ResolveInfo cur = matches.get(i); 3499 final String packageName = cur.getComponentInfo().packageName; 3500 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3501 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3502 continue; 3503 } 3504 3505 if (best == null || cur.priority > best.priority) { 3506 best = cur; 3507 } 3508 } 3509 3510 if (best != null) { 3511 return best.getComponentInfo().getComponentName(); 3512 } 3513 Slog.w(TAG, "Intent filter verifier not found"); 3514 return null; 3515 } 3516 3517 @Override 3518 public @Nullable ComponentName getInstantAppResolverComponent() { 3519 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3520 return null; 3521 } 3522 synchronized (mPackages) { 3523 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3524 if (instantAppResolver == null) { 3525 return null; 3526 } 3527 return instantAppResolver.first; 3528 } 3529 } 3530 3531 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3532 final String[] packageArray = 3533 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3534 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3535 if (DEBUG_INSTANT) { 3536 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3537 } 3538 return null; 3539 } 3540 3541 final int callingUid = Binder.getCallingUid(); 3542 final int resolveFlags = 3543 MATCH_DIRECT_BOOT_AWARE 3544 | MATCH_DIRECT_BOOT_UNAWARE 3545 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3546 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3547 final Intent resolverIntent = new Intent(actionName); 3548 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3549 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3550 final int N = resolvers.size(); 3551 if (N == 0) { 3552 if (DEBUG_INSTANT) { 3553 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3554 } 3555 return null; 3556 } 3557 3558 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3559 for (int i = 0; i < N; i++) { 3560 final ResolveInfo info = resolvers.get(i); 3561 3562 if (info.serviceInfo == null) { 3563 continue; 3564 } 3565 3566 final String packageName = info.serviceInfo.packageName; 3567 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3568 if (DEBUG_INSTANT) { 3569 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3570 + " pkg: " + packageName + ", info:" + info); 3571 } 3572 continue; 3573 } 3574 3575 if (DEBUG_INSTANT) { 3576 Slog.v(TAG, "Ephemeral resolver found;" 3577 + " pkg: " + packageName + ", info:" + info); 3578 } 3579 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3580 } 3581 if (DEBUG_INSTANT) { 3582 Slog.v(TAG, "Ephemeral resolver NOT found"); 3583 } 3584 return null; 3585 } 3586 3587 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3588 String[] orderedActions = Build.IS_ENG 3589 ? new String[]{ 3590 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST", 3591 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE} 3592 : new String[]{ 3593 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}; 3594 3595 final int resolveFlags = 3596 MATCH_DIRECT_BOOT_AWARE 3597 | MATCH_DIRECT_BOOT_UNAWARE 3598 | Intent.FLAG_IGNORE_EPHEMERAL 3599 | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0); 3600 final Intent intent = new Intent(); 3601 intent.addCategory(Intent.CATEGORY_DEFAULT); 3602 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3603 List<ResolveInfo> matches = null; 3604 for (String action : orderedActions) { 3605 intent.setAction(action); 3606 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3607 resolveFlags, UserHandle.USER_SYSTEM); 3608 if (matches.isEmpty()) { 3609 if (DEBUG_INSTANT) { 3610 Slog.d(TAG, "Instant App installer not found with " + action); 3611 } 3612 } else { 3613 break; 3614 } 3615 } 3616 Iterator<ResolveInfo> iter = matches.iterator(); 3617 while (iter.hasNext()) { 3618 final ResolveInfo rInfo = iter.next(); 3619 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3620 if (ps != null) { 3621 final PermissionsState permissionsState = ps.getPermissionsState(); 3622 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0) 3623 || Build.IS_ENG) { 3624 continue; 3625 } 3626 } 3627 iter.remove(); 3628 } 3629 if (matches.size() == 0) { 3630 return null; 3631 } else if (matches.size() == 1) { 3632 return (ActivityInfo) matches.get(0).getComponentInfo(); 3633 } else { 3634 throw new RuntimeException( 3635 "There must be at most one ephemeral installer; found " + matches); 3636 } 3637 } 3638 3639 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3640 @NonNull ComponentName resolver) { 3641 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3642 .addCategory(Intent.CATEGORY_DEFAULT) 3643 .setPackage(resolver.getPackageName()); 3644 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3645 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3646 UserHandle.USER_SYSTEM); 3647 if (matches.isEmpty()) { 3648 return null; 3649 } 3650 return matches.get(0).getComponentInfo().getComponentName(); 3651 } 3652 3653 private void primeDomainVerificationsLPw(int userId) { 3654 if (DEBUG_DOMAIN_VERIFICATION) { 3655 Slog.d(TAG, "Priming domain verifications in user " + userId); 3656 } 3657 3658 SystemConfig systemConfig = SystemConfig.getInstance(); 3659 ArraySet<String> packages = systemConfig.getLinkedApps(); 3660 3661 for (String packageName : packages) { 3662 PackageParser.Package pkg = mPackages.get(packageName); 3663 if (pkg != null) { 3664 if (!pkg.isSystem()) { 3665 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3666 continue; 3667 } 3668 3669 ArraySet<String> domains = null; 3670 for (PackageParser.Activity a : pkg.activities) { 3671 for (ActivityIntentInfo filter : a.intents) { 3672 if (hasValidDomains(filter)) { 3673 if (domains == null) { 3674 domains = new ArraySet<String>(); 3675 } 3676 domains.addAll(filter.getHostsList()); 3677 } 3678 } 3679 } 3680 3681 if (domains != null && domains.size() > 0) { 3682 if (DEBUG_DOMAIN_VERIFICATION) { 3683 Slog.v(TAG, " + " + packageName); 3684 } 3685 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3686 // state w.r.t. the formal app-linkage "no verification attempted" state; 3687 // and then 'always' in the per-user state actually used for intent resolution. 3688 final IntentFilterVerificationInfo ivi; 3689 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3690 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3691 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3692 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3693 } else { 3694 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3695 + "' does not handle web links"); 3696 } 3697 } else { 3698 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3699 } 3700 } 3701 3702 scheduleWritePackageRestrictionsLocked(userId); 3703 scheduleWriteSettingsLocked(); 3704 } 3705 3706 private void applyFactoryDefaultBrowserLPw(int userId) { 3707 // The default browser app's package name is stored in a string resource, 3708 // with a product-specific overlay used for vendor customization. 3709 String browserPkg = mContext.getResources().getString( 3710 com.android.internal.R.string.default_browser); 3711 if (!TextUtils.isEmpty(browserPkg)) { 3712 // non-empty string => required to be a known package 3713 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3714 if (ps == null) { 3715 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3716 browserPkg = null; 3717 } else { 3718 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3719 } 3720 } 3721 3722 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3723 // default. If there's more than one, just leave everything alone. 3724 if (browserPkg == null) { 3725 calculateDefaultBrowserLPw(userId); 3726 } 3727 } 3728 3729 private void calculateDefaultBrowserLPw(int userId) { 3730 List<String> allBrowsers = resolveAllBrowserApps(userId); 3731 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3732 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3733 } 3734 3735 private List<String> resolveAllBrowserApps(int userId) { 3736 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3737 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3738 PackageManager.MATCH_ALL, userId); 3739 3740 final int count = list.size(); 3741 List<String> result = new ArrayList<String>(count); 3742 for (int i=0; i<count; i++) { 3743 ResolveInfo info = list.get(i); 3744 if (info.activityInfo == null 3745 || !info.handleAllWebDataURI 3746 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3747 || result.contains(info.activityInfo.packageName)) { 3748 continue; 3749 } 3750 result.add(info.activityInfo.packageName); 3751 } 3752 3753 return result; 3754 } 3755 3756 private boolean packageIsBrowser(String packageName, int userId) { 3757 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3758 PackageManager.MATCH_ALL, userId); 3759 final int N = list.size(); 3760 for (int i = 0; i < N; i++) { 3761 ResolveInfo info = list.get(i); 3762 if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) { 3763 return true; 3764 } 3765 } 3766 return false; 3767 } 3768 3769 private void checkDefaultBrowser() { 3770 final int myUserId = UserHandle.myUserId(); 3771 final String packageName = getDefaultBrowserPackageName(myUserId); 3772 if (packageName != null) { 3773 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3774 if (info == null) { 3775 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3776 synchronized (mPackages) { 3777 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3778 } 3779 } 3780 } 3781 } 3782 3783 @Override 3784 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3785 throws RemoteException { 3786 try { 3787 return super.onTransact(code, data, reply, flags); 3788 } catch (RuntimeException e) { 3789 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3790 Slog.wtf(TAG, "Package Manager Crash", e); 3791 } 3792 throw e; 3793 } 3794 } 3795 3796 static int[] appendInts(int[] cur, int[] add) { 3797 if (add == null) return cur; 3798 if (cur == null) return add; 3799 final int N = add.length; 3800 for (int i=0; i<N; i++) { 3801 cur = appendInt(cur, add[i]); 3802 } 3803 return cur; 3804 } 3805 3806 /** 3807 * Returns whether or not a full application can see an instant application. 3808 * <p> 3809 * Currently, there are three cases in which this can occur: 3810 * <ol> 3811 * <li>The calling application is a "special" process. Special processes 3812 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 3813 * <li>The calling application has the permission 3814 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 3815 * <li>The calling application is the default launcher on the 3816 * system partition.</li> 3817 * </ol> 3818 */ 3819 private boolean canViewInstantApps(int callingUid, int userId) { 3820 if (callingUid < Process.FIRST_APPLICATION_UID) { 3821 return true; 3822 } 3823 if (mContext.checkCallingOrSelfPermission( 3824 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3825 return true; 3826 } 3827 if (mContext.checkCallingOrSelfPermission( 3828 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3829 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3830 if (homeComponent != null 3831 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3832 return true; 3833 } 3834 } 3835 return false; 3836 } 3837 3838 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3839 if (!sUserManager.exists(userId)) return null; 3840 if (ps == null) { 3841 return null; 3842 } 3843 PackageParser.Package p = ps.pkg; 3844 if (p == null) { 3845 return null; 3846 } 3847 final int callingUid = Binder.getCallingUid(); 3848 // Filter out ephemeral app metadata: 3849 // * The system/shell/root can see metadata for any app 3850 // * An installed app can see metadata for 1) other installed apps 3851 // and 2) ephemeral apps that have explicitly interacted with it 3852 // * Ephemeral apps can only see their own data and exposed installed apps 3853 // * Holding a signature permission allows seeing instant apps 3854 if (filterAppAccessLPr(ps, callingUid, userId)) { 3855 return null; 3856 } 3857 3858 final PermissionsState permissionsState = ps.getPermissionsState(); 3859 3860 // Compute GIDs only if requested 3861 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3862 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3863 // Compute granted permissions only if package has requested permissions 3864 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3865 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3866 final PackageUserState state = ps.readUserState(userId); 3867 3868 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3869 && ps.isSystem()) { 3870 flags |= MATCH_ANY_USER; 3871 } 3872 3873 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3874 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3875 3876 if (packageInfo == null) { 3877 return null; 3878 } 3879 3880 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3881 resolveExternalPackageNameLPr(p); 3882 3883 return packageInfo; 3884 } 3885 3886 @Override 3887 public void checkPackageStartable(String packageName, int userId) { 3888 final int callingUid = Binder.getCallingUid(); 3889 if (getInstantAppPackageName(callingUid) != null) { 3890 throw new SecurityException("Instant applications don't have access to this method"); 3891 } 3892 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3893 synchronized (mPackages) { 3894 final PackageSetting ps = mSettings.mPackages.get(packageName); 3895 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 3896 throw new SecurityException("Package " + packageName + " was not found!"); 3897 } 3898 3899 if (!ps.getInstalled(userId)) { 3900 throw new SecurityException( 3901 "Package " + packageName + " was not installed for user " + userId + "!"); 3902 } 3903 3904 if (mSafeMode && !ps.isSystem()) { 3905 throw new SecurityException("Package " + packageName + " not a system app!"); 3906 } 3907 3908 if (mFrozenPackages.contains(packageName)) { 3909 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3910 } 3911 3912 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) { 3913 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3914 } 3915 } 3916 } 3917 3918 @Override 3919 public boolean isPackageAvailable(String packageName, int userId) { 3920 if (!sUserManager.exists(userId)) return false; 3921 final int callingUid = Binder.getCallingUid(); 3922 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 3923 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 3924 synchronized (mPackages) { 3925 PackageParser.Package p = mPackages.get(packageName); 3926 if (p != null) { 3927 final PackageSetting ps = (PackageSetting) p.mExtras; 3928 if (filterAppAccessLPr(ps, callingUid, userId)) { 3929 return false; 3930 } 3931 if (ps != null) { 3932 final PackageUserState state = ps.readUserState(userId); 3933 if (state != null) { 3934 return PackageParser.isAvailable(state); 3935 } 3936 } 3937 } 3938 } 3939 return false; 3940 } 3941 3942 @Override 3943 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3944 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3945 flags, Binder.getCallingUid(), userId); 3946 } 3947 3948 @Override 3949 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3950 int flags, int userId) { 3951 return getPackageInfoInternal(versionedPackage.getPackageName(), 3952 versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId); 3953 } 3954 3955 /** 3956 * Important: The provided filterCallingUid is used exclusively to filter out packages 3957 * that can be seen based on user state. It's typically the original caller uid prior 3958 * to clearing. Because it can only be provided by trusted code, it's value can be 3959 * trusted and will be used as-is; unlike userId which will be validated by this method. 3960 */ 3961 private PackageInfo getPackageInfoInternal(String packageName, long versionCode, 3962 int flags, int filterCallingUid, int userId) { 3963 if (!sUserManager.exists(userId)) return null; 3964 flags = updateFlagsForPackage(flags, userId, packageName); 3965 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 3966 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3967 3968 // reader 3969 synchronized (mPackages) { 3970 // Normalize package name to handle renamed packages and static libs 3971 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3972 3973 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3974 if (matchFactoryOnly) { 3975 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3976 if (ps != null) { 3977 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3978 return null; 3979 } 3980 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3981 return null; 3982 } 3983 return generatePackageInfo(ps, flags, userId); 3984 } 3985 } 3986 3987 PackageParser.Package p = mPackages.get(packageName); 3988 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3989 return null; 3990 } 3991 if (DEBUG_PACKAGE_INFO) 3992 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3993 if (p != null) { 3994 final PackageSetting ps = (PackageSetting) p.mExtras; 3995 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3996 return null; 3997 } 3998 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 3999 return null; 4000 } 4001 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 4002 } 4003 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 4004 final PackageSetting ps = mSettings.mPackages.get(packageName); 4005 if (ps == null) return null; 4006 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4007 return null; 4008 } 4009 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4010 return null; 4011 } 4012 return generatePackageInfo(ps, flags, userId); 4013 } 4014 } 4015 return null; 4016 } 4017 4018 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 4019 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 4020 return true; 4021 } 4022 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 4023 return true; 4024 } 4025 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 4026 return true; 4027 } 4028 return false; 4029 } 4030 4031 private boolean isComponentVisibleToInstantApp( 4032 @Nullable ComponentName component, @ComponentType int type) { 4033 if (type == TYPE_ACTIVITY) { 4034 final PackageParser.Activity activity = mActivities.mActivities.get(component); 4035 return activity != null 4036 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4037 : false; 4038 } else if (type == TYPE_RECEIVER) { 4039 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 4040 return activity != null 4041 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4042 : false; 4043 } else if (type == TYPE_SERVICE) { 4044 final PackageParser.Service service = mServices.mServices.get(component); 4045 return service != null 4046 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4047 : false; 4048 } else if (type == TYPE_PROVIDER) { 4049 final PackageParser.Provider provider = mProviders.mProviders.get(component); 4050 return provider != null 4051 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4052 : false; 4053 } else if (type == TYPE_UNKNOWN) { 4054 return isComponentVisibleToInstantApp(component); 4055 } 4056 return false; 4057 } 4058 4059 /** 4060 * Returns whether or not access to the application should be filtered. 4061 * <p> 4062 * Access may be limited based upon whether the calling or target applications 4063 * are instant applications. 4064 * 4065 * @see #canAccessInstantApps(int) 4066 */ 4067 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 4068 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 4069 // if we're in an isolated process, get the real calling UID 4070 if (Process.isIsolated(callingUid)) { 4071 callingUid = mIsolatedOwners.get(callingUid); 4072 } 4073 final String instantAppPkgName = getInstantAppPackageName(callingUid); 4074 final boolean callerIsInstantApp = instantAppPkgName != null; 4075 if (ps == null) { 4076 if (callerIsInstantApp) { 4077 // pretend the application exists, but, needs to be filtered 4078 return true; 4079 } 4080 return false; 4081 } 4082 // if the target and caller are the same application, don't filter 4083 if (isCallerSameApp(ps.name, callingUid)) { 4084 return false; 4085 } 4086 if (callerIsInstantApp) { 4087 // request for a specific component; if it hasn't been explicitly exposed, filter 4088 if (component != null) { 4089 return !isComponentVisibleToInstantApp(component, componentType); 4090 } 4091 // request for application; if no components have been explicitly exposed, filter 4092 return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps; 4093 } 4094 if (ps.getInstantApp(userId)) { 4095 // caller can see all components of all instant applications, don't filter 4096 if (canViewInstantApps(callingUid, userId)) { 4097 return false; 4098 } 4099 // request for a specific instant application component, filter 4100 if (component != null) { 4101 return true; 4102 } 4103 // request for an instant application; if the caller hasn't been granted access, filter 4104 return !mInstantAppRegistry.isInstantAccessGranted( 4105 userId, UserHandle.getAppId(callingUid), ps.appId); 4106 } 4107 return false; 4108 } 4109 4110 /** 4111 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 4112 */ 4113 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 4114 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 4115 } 4116 4117 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 4118 int flags) { 4119 // Callers can access only the libs they depend on, otherwise they need to explicitly 4120 // ask for the shared libraries given the caller is allowed to access all static libs. 4121 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 4122 // System/shell/root get to see all static libs 4123 final int appId = UserHandle.getAppId(uid); 4124 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 4125 || appId == Process.ROOT_UID) { 4126 return false; 4127 } 4128 } 4129 4130 // No package means no static lib as it is always on internal storage 4131 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4132 return false; 4133 } 4134 4135 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 4136 ps.pkg.staticSharedLibVersion); 4137 if (libEntry == null) { 4138 return false; 4139 } 4140 4141 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 4142 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 4143 if (uidPackageNames == null) { 4144 return true; 4145 } 4146 4147 for (String uidPackageName : uidPackageNames) { 4148 if (ps.name.equals(uidPackageName)) { 4149 return false; 4150 } 4151 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 4152 if (uidPs != null) { 4153 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 4154 libEntry.info.getName()); 4155 if (index < 0) { 4156 continue; 4157 } 4158 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) { 4159 return false; 4160 } 4161 } 4162 } 4163 return true; 4164 } 4165 4166 @Override 4167 public String[] currentToCanonicalPackageNames(String[] names) { 4168 final int callingUid = Binder.getCallingUid(); 4169 if (getInstantAppPackageName(callingUid) != null) { 4170 return names; 4171 } 4172 final String[] out = new String[names.length]; 4173 // reader 4174 synchronized (mPackages) { 4175 final int callingUserId = UserHandle.getUserId(callingUid); 4176 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4177 for (int i=names.length-1; i>=0; i--) { 4178 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4179 boolean translateName = false; 4180 if (ps != null && ps.realName != null) { 4181 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 4182 translateName = !targetIsInstantApp 4183 || canViewInstantApps 4184 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4185 UserHandle.getAppId(callingUid), ps.appId); 4186 } 4187 out[i] = translateName ? ps.realName : names[i]; 4188 } 4189 } 4190 return out; 4191 } 4192 4193 @Override 4194 public String[] canonicalToCurrentPackageNames(String[] names) { 4195 final int callingUid = Binder.getCallingUid(); 4196 if (getInstantAppPackageName(callingUid) != null) { 4197 return names; 4198 } 4199 final String[] out = new String[names.length]; 4200 // reader 4201 synchronized (mPackages) { 4202 final int callingUserId = UserHandle.getUserId(callingUid); 4203 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4204 for (int i=names.length-1; i>=0; i--) { 4205 final String cur = mSettings.getRenamedPackageLPr(names[i]); 4206 boolean translateName = false; 4207 if (cur != null) { 4208 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4209 final boolean targetIsInstantApp = 4210 ps != null && ps.getInstantApp(callingUserId); 4211 translateName = !targetIsInstantApp 4212 || canViewInstantApps 4213 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4214 UserHandle.getAppId(callingUid), ps.appId); 4215 } 4216 out[i] = translateName ? cur : names[i]; 4217 } 4218 } 4219 return out; 4220 } 4221 4222 @Override 4223 public int getPackageUid(String packageName, int flags, int userId) { 4224 if (!sUserManager.exists(userId)) return -1; 4225 final int callingUid = Binder.getCallingUid(); 4226 flags = updateFlagsForPackage(flags, userId, packageName); 4227 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4228 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 4229 4230 // reader 4231 synchronized (mPackages) { 4232 final PackageParser.Package p = mPackages.get(packageName); 4233 if (p != null && p.isMatch(flags)) { 4234 PackageSetting ps = (PackageSetting) p.mExtras; 4235 if (filterAppAccessLPr(ps, callingUid, userId)) { 4236 return -1; 4237 } 4238 return UserHandle.getUid(userId, p.applicationInfo.uid); 4239 } 4240 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4241 final PackageSetting ps = mSettings.mPackages.get(packageName); 4242 if (ps != null && ps.isMatch(flags) 4243 && !filterAppAccessLPr(ps, callingUid, userId)) { 4244 return UserHandle.getUid(userId, ps.appId); 4245 } 4246 } 4247 } 4248 4249 return -1; 4250 } 4251 4252 @Override 4253 public int[] getPackageGids(String packageName, int flags, int userId) { 4254 if (!sUserManager.exists(userId)) return null; 4255 final int callingUid = Binder.getCallingUid(); 4256 flags = updateFlagsForPackage(flags, userId, packageName); 4257 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4258 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 4259 4260 // reader 4261 synchronized (mPackages) { 4262 final PackageParser.Package p = mPackages.get(packageName); 4263 if (p != null && p.isMatch(flags)) { 4264 PackageSetting ps = (PackageSetting) p.mExtras; 4265 if (filterAppAccessLPr(ps, callingUid, userId)) { 4266 return null; 4267 } 4268 // TODO: Shouldn't this be checking for package installed state for userId and 4269 // return null? 4270 return ps.getPermissionsState().computeGids(userId); 4271 } 4272 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4273 final PackageSetting ps = mSettings.mPackages.get(packageName); 4274 if (ps != null && ps.isMatch(flags) 4275 && !filterAppAccessLPr(ps, callingUid, userId)) { 4276 return ps.getPermissionsState().computeGids(userId); 4277 } 4278 } 4279 } 4280 4281 return null; 4282 } 4283 4284 @Override 4285 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4286 return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid()); 4287 } 4288 4289 @Override 4290 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName, 4291 int flags) { 4292 final List<PermissionInfo> permissionList = 4293 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()); 4294 return (permissionList == null) ? null : new ParceledListSlice<>(permissionList); 4295 } 4296 4297 @Override 4298 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) { 4299 return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid()); 4300 } 4301 4302 @Override 4303 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4304 final List<PermissionGroupInfo> permissionList = 4305 mPermissionManager.getAllPermissionGroups(flags, getCallingUid()); 4306 return (permissionList == null) 4307 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList); 4308 } 4309 4310 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4311 int filterCallingUid, int userId) { 4312 if (!sUserManager.exists(userId)) return null; 4313 PackageSetting ps = mSettings.mPackages.get(packageName); 4314 if (ps != null) { 4315 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4316 return null; 4317 } 4318 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4319 return null; 4320 } 4321 if (ps.pkg == null) { 4322 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4323 if (pInfo != null) { 4324 return pInfo.applicationInfo; 4325 } 4326 return null; 4327 } 4328 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4329 ps.readUserState(userId), userId); 4330 if (ai != null) { 4331 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4332 } 4333 return ai; 4334 } 4335 return null; 4336 } 4337 4338 @Override 4339 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4340 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4341 } 4342 4343 /** 4344 * Important: The provided filterCallingUid is used exclusively to filter out applications 4345 * that can be seen based on user state. It's typically the original caller uid prior 4346 * to clearing. Because it can only be provided by trusted code, it's value can be 4347 * trusted and will be used as-is; unlike userId which will be validated by this method. 4348 */ 4349 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4350 int filterCallingUid, int userId) { 4351 if (!sUserManager.exists(userId)) return null; 4352 flags = updateFlagsForApplication(flags, userId, packageName); 4353 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4354 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4355 4356 // writer 4357 synchronized (mPackages) { 4358 // Normalize package name to handle renamed packages and static libs 4359 packageName = resolveInternalPackageNameLPr(packageName, 4360 PackageManager.VERSION_CODE_HIGHEST); 4361 4362 PackageParser.Package p = mPackages.get(packageName); 4363 if (DEBUG_PACKAGE_INFO) Log.v( 4364 TAG, "getApplicationInfo " + packageName 4365 + ": " + p); 4366 if (p != null) { 4367 PackageSetting ps = mSettings.mPackages.get(packageName); 4368 if (ps == null) return null; 4369 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4370 return null; 4371 } 4372 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4373 return null; 4374 } 4375 // Note: isEnabledLP() does not apply here - always return info 4376 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4377 p, flags, ps.readUserState(userId), userId); 4378 if (ai != null) { 4379 ai.packageName = resolveExternalPackageNameLPr(p); 4380 } 4381 return ai; 4382 } 4383 if ("android".equals(packageName)||"system".equals(packageName)) { 4384 return mAndroidApplication; 4385 } 4386 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4387 // Already generates the external package name 4388 return generateApplicationInfoFromSettingsLPw(packageName, 4389 flags, filterCallingUid, userId); 4390 } 4391 } 4392 return null; 4393 } 4394 4395 private String normalizePackageNameLPr(String packageName) { 4396 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4397 return normalizedPackageName != null ? normalizedPackageName : packageName; 4398 } 4399 4400 @Override 4401 public void deletePreloadsFileCache() { 4402 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4403 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4404 } 4405 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4406 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4407 FileUtils.deleteContents(dir); 4408 } 4409 4410 @Override 4411 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4412 final int storageFlags, final IPackageDataObserver observer) { 4413 mContext.enforceCallingOrSelfPermission( 4414 android.Manifest.permission.CLEAR_APP_CACHE, null); 4415 mHandler.post(() -> { 4416 boolean success = false; 4417 try { 4418 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4419 success = true; 4420 } catch (IOException e) { 4421 Slog.w(TAG, e); 4422 } 4423 if (observer != null) { 4424 try { 4425 observer.onRemoveCompleted(null, success); 4426 } catch (RemoteException e) { 4427 Slog.w(TAG, e); 4428 } 4429 } 4430 }); 4431 } 4432 4433 @Override 4434 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4435 final int storageFlags, final IntentSender pi) { 4436 mContext.enforceCallingOrSelfPermission( 4437 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4438 mHandler.post(() -> { 4439 boolean success = false; 4440 try { 4441 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4442 success = true; 4443 } catch (IOException e) { 4444 Slog.w(TAG, e); 4445 } 4446 if (pi != null) { 4447 try { 4448 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4449 } catch (SendIntentException e) { 4450 Slog.w(TAG, e); 4451 } 4452 } 4453 }); 4454 } 4455 4456 /** 4457 * Blocking call to clear various types of cached data across the system 4458 * until the requested bytes are available. 4459 */ 4460 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4461 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4462 final File file = storage.findPathForUuid(volumeUuid); 4463 if (file.getUsableSpace() >= bytes) return; 4464 4465 if (ENABLE_FREE_CACHE_V2) { 4466 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4467 volumeUuid); 4468 final boolean aggressive = (storageFlags 4469 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4470 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags); 4471 4472 // 1. Pre-flight to determine if we have any chance to succeed 4473 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4474 if (internalVolume && (aggressive || SystemProperties 4475 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4476 deletePreloadsFileCache(); 4477 if (file.getUsableSpace() >= bytes) return; 4478 } 4479 4480 // 3. Consider parsed APK data (aggressive only) 4481 if (internalVolume && aggressive) { 4482 FileUtils.deleteContents(mCacheDir); 4483 if (file.getUsableSpace() >= bytes) return; 4484 } 4485 4486 // 4. Consider cached app data (above quotas) 4487 try { 4488 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4489 Installer.FLAG_FREE_CACHE_V2); 4490 } catch (InstallerException ignored) { 4491 } 4492 if (file.getUsableSpace() >= bytes) return; 4493 4494 // 5. Consider shared libraries with refcount=0 and age>min cache period 4495 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4496 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4497 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4498 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4499 return; 4500 } 4501 4502 // 6. Consider dexopt output (aggressive only) 4503 // TODO: Implement 4504 4505 // 7. Consider installed instant apps unused longer than min cache period 4506 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4507 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4508 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4509 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4510 return; 4511 } 4512 4513 // 8. Consider cached app data (below quotas) 4514 try { 4515 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4516 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4517 } catch (InstallerException ignored) { 4518 } 4519 if (file.getUsableSpace() >= bytes) return; 4520 4521 // 9. Consider DropBox entries 4522 // TODO: Implement 4523 4524 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4525 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4526 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4527 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4528 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4529 return; 4530 } 4531 } else { 4532 try { 4533 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4534 } catch (InstallerException ignored) { 4535 } 4536 if (file.getUsableSpace() >= bytes) return; 4537 } 4538 4539 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4540 } 4541 4542 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4543 throws IOException { 4544 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4545 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4546 4547 List<VersionedPackage> packagesToDelete = null; 4548 final long now = System.currentTimeMillis(); 4549 4550 synchronized (mPackages) { 4551 final int[] allUsers = sUserManager.getUserIds(); 4552 final int libCount = mSharedLibraries.size(); 4553 for (int i = 0; i < libCount; i++) { 4554 final LongSparseArray<SharedLibraryEntry> versionedLib 4555 = mSharedLibraries.valueAt(i); 4556 if (versionedLib == null) { 4557 continue; 4558 } 4559 final int versionCount = versionedLib.size(); 4560 for (int j = 0; j < versionCount; j++) { 4561 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4562 // Skip packages that are not static shared libs. 4563 if (!libInfo.isStatic()) { 4564 break; 4565 } 4566 // Important: We skip static shared libs used for some user since 4567 // in such a case we need to keep the APK on the device. The check for 4568 // a lib being used for any user is performed by the uninstall call. 4569 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4570 // Resolve the package name - we use synthetic package names internally 4571 final String internalPackageName = resolveInternalPackageNameLPr( 4572 declaringPackage.getPackageName(), 4573 declaringPackage.getLongVersionCode()); 4574 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4575 // Skip unused static shared libs cached less than the min period 4576 // to prevent pruning a lib needed by a subsequently installed package. 4577 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4578 continue; 4579 } 4580 if (packagesToDelete == null) { 4581 packagesToDelete = new ArrayList<>(); 4582 } 4583 packagesToDelete.add(new VersionedPackage(internalPackageName, 4584 declaringPackage.getLongVersionCode())); 4585 } 4586 } 4587 } 4588 4589 if (packagesToDelete != null) { 4590 final int packageCount = packagesToDelete.size(); 4591 for (int i = 0; i < packageCount; i++) { 4592 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4593 // Delete the package synchronously (will fail of the lib used for any user). 4594 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(), 4595 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4596 == PackageManager.DELETE_SUCCEEDED) { 4597 if (volume.getUsableSpace() >= neededSpace) { 4598 return true; 4599 } 4600 } 4601 } 4602 } 4603 4604 return false; 4605 } 4606 4607 /** 4608 * Update given flags based on encryption status of current user. 4609 */ 4610 private int updateFlags(int flags, int userId) { 4611 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4612 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4613 // Caller expressed an explicit opinion about what encryption 4614 // aware/unaware components they want to see, so fall through and 4615 // give them what they want 4616 } else { 4617 // Caller expressed no opinion, so match based on user state 4618 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4619 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4620 } else { 4621 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4622 } 4623 } 4624 return flags; 4625 } 4626 4627 private UserManagerInternal getUserManagerInternal() { 4628 if (mUserManagerInternal == null) { 4629 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4630 } 4631 return mUserManagerInternal; 4632 } 4633 4634 private ActivityManagerInternal getActivityManagerInternal() { 4635 if (mActivityManagerInternal == null) { 4636 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class); 4637 } 4638 return mActivityManagerInternal; 4639 } 4640 4641 4642 private DeviceIdleController.LocalService getDeviceIdleController() { 4643 if (mDeviceIdleController == null) { 4644 mDeviceIdleController = 4645 LocalServices.getService(DeviceIdleController.LocalService.class); 4646 } 4647 return mDeviceIdleController; 4648 } 4649 4650 /** 4651 * Update given flags when being used to request {@link PackageInfo}. 4652 */ 4653 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4654 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4655 boolean triaged = true; 4656 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4657 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4658 // Caller is asking for component details, so they'd better be 4659 // asking for specific encryption matching behavior, or be triaged 4660 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4661 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4662 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4663 triaged = false; 4664 } 4665 } 4666 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4667 | PackageManager.MATCH_SYSTEM_ONLY 4668 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4669 triaged = false; 4670 } 4671 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4672 mPermissionManager.enforceCrossUserPermission( 4673 Binder.getCallingUid(), userId, false, false, 4674 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4675 + Debug.getCallers(5)); 4676 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4677 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4678 // If the caller wants all packages and has a restricted profile associated with it, 4679 // then match all users. This is to make sure that launchers that need to access work 4680 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4681 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4682 flags |= PackageManager.MATCH_ANY_USER; 4683 } 4684 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4685 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4686 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4687 } 4688 return updateFlags(flags, userId); 4689 } 4690 4691 /** 4692 * Update given flags when being used to request {@link ApplicationInfo}. 4693 */ 4694 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4695 return updateFlagsForPackage(flags, userId, cookie); 4696 } 4697 4698 /** 4699 * Update given flags when being used to request {@link ComponentInfo}. 4700 */ 4701 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4702 if (cookie instanceof Intent) { 4703 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4704 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4705 } 4706 } 4707 4708 boolean triaged = true; 4709 // Caller is asking for component details, so they'd better be 4710 // asking for specific encryption matching behavior, or be triaged 4711 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4712 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4713 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4714 triaged = false; 4715 } 4716 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4717 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4718 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4719 } 4720 4721 return updateFlags(flags, userId); 4722 } 4723 4724 /** 4725 * Update given intent when being used to request {@link ResolveInfo}. 4726 */ 4727 private Intent updateIntentForResolve(Intent intent) { 4728 if (intent.getSelector() != null) { 4729 intent = intent.getSelector(); 4730 } 4731 if (DEBUG_PREFERRED) { 4732 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4733 } 4734 return intent; 4735 } 4736 4737 /** 4738 * Update given flags when being used to request {@link ResolveInfo}. 4739 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4740 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4741 * flag set. However, this flag is only honoured in three circumstances: 4742 * <ul> 4743 * <li>when called from a system process</li> 4744 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4745 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4746 * action and a {@code android.intent.category.BROWSABLE} category</li> 4747 * </ul> 4748 */ 4749 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4750 return updateFlagsForResolve(flags, userId, intent, callingUid, 4751 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4752 } 4753 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4754 boolean wantInstantApps) { 4755 return updateFlagsForResolve(flags, userId, intent, callingUid, 4756 wantInstantApps, false /*onlyExposedExplicitly*/); 4757 } 4758 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4759 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4760 // Safe mode means we shouldn't match any third-party components 4761 if (mSafeMode) { 4762 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4763 } 4764 if (getInstantAppPackageName(callingUid) != null) { 4765 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4766 if (onlyExposedExplicitly) { 4767 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4768 } 4769 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4770 flags |= PackageManager.MATCH_INSTANT; 4771 } else { 4772 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 4773 final boolean allowMatchInstant = wantInstantApps 4774 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 4775 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4776 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4777 if (!allowMatchInstant) { 4778 flags &= ~PackageManager.MATCH_INSTANT; 4779 } 4780 } 4781 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4782 } 4783 4784 @Override 4785 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4786 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 4787 } 4788 4789 /** 4790 * Important: The provided filterCallingUid is used exclusively to filter out activities 4791 * that can be seen based on user state. It's typically the original caller uid prior 4792 * to clearing. Because it can only be provided by trusted code, it's value can be 4793 * trusted and will be used as-is; unlike userId which will be validated by this method. 4794 */ 4795 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 4796 int filterCallingUid, int userId) { 4797 if (!sUserManager.exists(userId)) return null; 4798 flags = updateFlagsForComponent(flags, userId, component); 4799 4800 if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) { 4801 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4802 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4803 } 4804 4805 synchronized (mPackages) { 4806 PackageParser.Activity a = mActivities.mActivities.get(component); 4807 4808 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4809 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4810 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4811 if (ps == null) return null; 4812 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 4813 return null; 4814 } 4815 return PackageParser.generateActivityInfo( 4816 a, flags, ps.readUserState(userId), userId); 4817 } 4818 if (mResolveComponentName.equals(component)) { 4819 return PackageParser.generateActivityInfo( 4820 mResolveActivity, flags, new PackageUserState(), userId); 4821 } 4822 } 4823 return null; 4824 } 4825 4826 private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) { 4827 if (!getActivityManagerInternal().isCallerRecents(callingUid)) { 4828 return false; 4829 } 4830 final long token = Binder.clearCallingIdentity(); 4831 try { 4832 final int callingUserId = UserHandle.getUserId(callingUid); 4833 if (ActivityManager.getCurrentUser() != callingUserId) { 4834 return false; 4835 } 4836 return sUserManager.isSameProfileGroup(callingUserId, targetUserId); 4837 } finally { 4838 Binder.restoreCallingIdentity(token); 4839 } 4840 } 4841 4842 @Override 4843 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4844 String resolvedType) { 4845 synchronized (mPackages) { 4846 if (component.equals(mResolveComponentName)) { 4847 // The resolver supports EVERYTHING! 4848 return true; 4849 } 4850 final int callingUid = Binder.getCallingUid(); 4851 final int callingUserId = UserHandle.getUserId(callingUid); 4852 PackageParser.Activity a = mActivities.mActivities.get(component); 4853 if (a == null) { 4854 return false; 4855 } 4856 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4857 if (ps == null) { 4858 return false; 4859 } 4860 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4861 return false; 4862 } 4863 for (int i=0; i<a.intents.size(); i++) { 4864 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4865 intent.getData(), intent.getCategories(), TAG) >= 0) { 4866 return true; 4867 } 4868 } 4869 return false; 4870 } 4871 } 4872 4873 @Override 4874 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4875 if (!sUserManager.exists(userId)) return null; 4876 final int callingUid = Binder.getCallingUid(); 4877 flags = updateFlagsForComponent(flags, userId, component); 4878 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4879 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4880 synchronized (mPackages) { 4881 PackageParser.Activity a = mReceivers.mActivities.get(component); 4882 if (DEBUG_PACKAGE_INFO) Log.v( 4883 TAG, "getReceiverInfo " + component + ": " + a); 4884 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4885 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4886 if (ps == null) return null; 4887 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4888 return null; 4889 } 4890 return PackageParser.generateActivityInfo( 4891 a, flags, ps.readUserState(userId), userId); 4892 } 4893 } 4894 return null; 4895 } 4896 4897 @Override 4898 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4899 int flags, int userId) { 4900 if (!sUserManager.exists(userId)) return null; 4901 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4902 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4903 return null; 4904 } 4905 4906 flags = updateFlagsForPackage(flags, userId, null); 4907 4908 final boolean canSeeStaticLibraries = 4909 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4910 == PERMISSION_GRANTED 4911 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4912 == PERMISSION_GRANTED 4913 || canRequestPackageInstallsInternal(packageName, 4914 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 4915 false /* throwIfPermNotDeclared*/) 4916 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4917 == PERMISSION_GRANTED; 4918 4919 synchronized (mPackages) { 4920 List<SharedLibraryInfo> result = null; 4921 4922 final int libCount = mSharedLibraries.size(); 4923 for (int i = 0; i < libCount; i++) { 4924 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4925 if (versionedLib == null) { 4926 continue; 4927 } 4928 4929 final int versionCount = versionedLib.size(); 4930 for (int j = 0; j < versionCount; j++) { 4931 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4932 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4933 break; 4934 } 4935 final long identity = Binder.clearCallingIdentity(); 4936 try { 4937 PackageInfo packageInfo = getPackageInfoVersioned( 4938 libInfo.getDeclaringPackage(), flags 4939 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 4940 if (packageInfo == null) { 4941 continue; 4942 } 4943 } finally { 4944 Binder.restoreCallingIdentity(identity); 4945 } 4946 4947 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4948 libInfo.getLongVersion(), libInfo.getType(), 4949 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 4950 flags, userId)); 4951 4952 if (result == null) { 4953 result = new ArrayList<>(); 4954 } 4955 result.add(resLibInfo); 4956 } 4957 } 4958 4959 return result != null ? new ParceledListSlice<>(result) : null; 4960 } 4961 } 4962 4963 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4964 SharedLibraryInfo libInfo, int flags, int userId) { 4965 List<VersionedPackage> versionedPackages = null; 4966 final int packageCount = mSettings.mPackages.size(); 4967 for (int i = 0; i < packageCount; i++) { 4968 PackageSetting ps = mSettings.mPackages.valueAt(i); 4969 4970 if (ps == null) { 4971 continue; 4972 } 4973 4974 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4975 continue; 4976 } 4977 4978 final String libName = libInfo.getName(); 4979 if (libInfo.isStatic()) { 4980 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4981 if (libIdx < 0) { 4982 continue; 4983 } 4984 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) { 4985 continue; 4986 } 4987 if (versionedPackages == null) { 4988 versionedPackages = new ArrayList<>(); 4989 } 4990 // If the dependent is a static shared lib, use the public package name 4991 String dependentPackageName = ps.name; 4992 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4993 dependentPackageName = ps.pkg.manifestPackageName; 4994 } 4995 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4996 } else if (ps.pkg != null) { 4997 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4998 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4999 if (versionedPackages == null) { 5000 versionedPackages = new ArrayList<>(); 5001 } 5002 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 5003 } 5004 } 5005 } 5006 5007 return versionedPackages; 5008 } 5009 5010 @Override 5011 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 5012 if (!sUserManager.exists(userId)) return null; 5013 final int callingUid = Binder.getCallingUid(); 5014 flags = updateFlagsForComponent(flags, userId, component); 5015 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5016 false /* requireFullPermission */, false /* checkShell */, "get service info"); 5017 synchronized (mPackages) { 5018 PackageParser.Service s = mServices.mServices.get(component); 5019 if (DEBUG_PACKAGE_INFO) Log.v( 5020 TAG, "getServiceInfo " + component + ": " + s); 5021 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 5022 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5023 if (ps == null) return null; 5024 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 5025 return null; 5026 } 5027 return PackageParser.generateServiceInfo( 5028 s, flags, ps.readUserState(userId), userId); 5029 } 5030 } 5031 return null; 5032 } 5033 5034 @Override 5035 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 5036 if (!sUserManager.exists(userId)) return null; 5037 final int callingUid = Binder.getCallingUid(); 5038 flags = updateFlagsForComponent(flags, userId, component); 5039 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5040 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 5041 synchronized (mPackages) { 5042 PackageParser.Provider p = mProviders.mProviders.get(component); 5043 if (DEBUG_PACKAGE_INFO) Log.v( 5044 TAG, "getProviderInfo " + component + ": " + p); 5045 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 5046 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5047 if (ps == null) return null; 5048 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 5049 return null; 5050 } 5051 return PackageParser.generateProviderInfo( 5052 p, flags, ps.readUserState(userId), userId); 5053 } 5054 } 5055 return null; 5056 } 5057 5058 @Override 5059 public String[] getSystemSharedLibraryNames() { 5060 // allow instant applications 5061 synchronized (mPackages) { 5062 Set<String> libs = null; 5063 final int libCount = mSharedLibraries.size(); 5064 for (int i = 0; i < libCount; i++) { 5065 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 5066 if (versionedLib == null) { 5067 continue; 5068 } 5069 final int versionCount = versionedLib.size(); 5070 for (int j = 0; j < versionCount; j++) { 5071 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 5072 if (!libEntry.info.isStatic()) { 5073 if (libs == null) { 5074 libs = new ArraySet<>(); 5075 } 5076 libs.add(libEntry.info.getName()); 5077 break; 5078 } 5079 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 5080 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 5081 UserHandle.getUserId(Binder.getCallingUid()), 5082 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 5083 if (libs == null) { 5084 libs = new ArraySet<>(); 5085 } 5086 libs.add(libEntry.info.getName()); 5087 break; 5088 } 5089 } 5090 } 5091 5092 if (libs != null) { 5093 String[] libsArray = new String[libs.size()]; 5094 libs.toArray(libsArray); 5095 return libsArray; 5096 } 5097 5098 return null; 5099 } 5100 } 5101 5102 @Override 5103 public @NonNull String getServicesSystemSharedLibraryPackageName() { 5104 // allow instant applications 5105 synchronized (mPackages) { 5106 return mServicesSystemSharedLibraryPackageName; 5107 } 5108 } 5109 5110 @Override 5111 public @NonNull String getSharedSystemSharedLibraryPackageName() { 5112 // allow instant applications 5113 synchronized (mPackages) { 5114 return mSharedSystemSharedLibraryPackageName; 5115 } 5116 } 5117 5118 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 5119 for (int i = userList.length - 1; i >= 0; --i) { 5120 final int userId = userList[i]; 5121 // don't add instant app to the list of updates 5122 if (pkgSetting.getInstantApp(userId)) { 5123 continue; 5124 } 5125 SparseArray<String> changedPackages = mChangedPackages.get(userId); 5126 if (changedPackages == null) { 5127 changedPackages = new SparseArray<>(); 5128 mChangedPackages.put(userId, changedPackages); 5129 } 5130 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 5131 if (sequenceNumbers == null) { 5132 sequenceNumbers = new HashMap<>(); 5133 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 5134 } 5135 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 5136 if (sequenceNumber != null) { 5137 changedPackages.remove(sequenceNumber); 5138 } 5139 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 5140 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 5141 } 5142 mChangedPackagesSequenceNumber++; 5143 } 5144 5145 @Override 5146 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5147 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5148 return null; 5149 } 5150 synchronized (mPackages) { 5151 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 5152 return null; 5153 } 5154 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 5155 if (changedPackages == null) { 5156 return null; 5157 } 5158 final List<String> packageNames = 5159 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 5160 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 5161 final String packageName = changedPackages.get(i); 5162 if (packageName != null) { 5163 packageNames.add(packageName); 5164 } 5165 } 5166 return packageNames.isEmpty() 5167 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 5168 } 5169 } 5170 5171 @Override 5172 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5173 // allow instant applications 5174 ArrayList<FeatureInfo> res; 5175 synchronized (mAvailableFeatures) { 5176 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5177 res.addAll(mAvailableFeatures.values()); 5178 } 5179 final FeatureInfo fi = new FeatureInfo(); 5180 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5181 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5182 res.add(fi); 5183 5184 return new ParceledListSlice<>(res); 5185 } 5186 5187 @Override 5188 public boolean hasSystemFeature(String name, int version) { 5189 // allow instant applications 5190 synchronized (mAvailableFeatures) { 5191 final FeatureInfo feat = mAvailableFeatures.get(name); 5192 if (feat == null) { 5193 return false; 5194 } else { 5195 return feat.version >= version; 5196 } 5197 } 5198 } 5199 5200 @Override 5201 public int checkPermission(String permName, String pkgName, int userId) { 5202 return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId); 5203 } 5204 5205 @Override 5206 public int checkUidPermission(String permName, int uid) { 5207 return mPermissionManager.checkUidPermission(permName, uid, getCallingUid()); 5208 } 5209 5210 @Override 5211 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5212 if (UserHandle.getCallingUserId() != userId) { 5213 mContext.enforceCallingPermission( 5214 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5215 "isPermissionRevokedByPolicy for user " + userId); 5216 } 5217 5218 if (checkPermission(permission, packageName, userId) 5219 == PackageManager.PERMISSION_GRANTED) { 5220 return false; 5221 } 5222 5223 final int callingUid = Binder.getCallingUid(); 5224 if (getInstantAppPackageName(callingUid) != null) { 5225 if (!isCallerSameApp(packageName, callingUid)) { 5226 return false; 5227 } 5228 } else { 5229 if (isInstantApp(packageName, userId)) { 5230 return false; 5231 } 5232 } 5233 5234 final long identity = Binder.clearCallingIdentity(); 5235 try { 5236 final int flags = getPermissionFlags(permission, packageName, userId); 5237 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5238 } finally { 5239 Binder.restoreCallingIdentity(identity); 5240 } 5241 } 5242 5243 @Override 5244 public String getPermissionControllerPackageName() { 5245 synchronized (mPackages) { 5246 return mRequiredInstallerPackage; 5247 } 5248 } 5249 5250 private boolean addDynamicPermission(PermissionInfo info, final boolean async) { 5251 return mPermissionManager.addDynamicPermission( 5252 info, async, getCallingUid(), new PermissionCallback() { 5253 @Override 5254 public void onPermissionChanged() { 5255 if (!async) { 5256 mSettings.writeLPr(); 5257 } else { 5258 scheduleWriteSettingsLocked(); 5259 } 5260 } 5261 }); 5262 } 5263 5264 @Override 5265 public boolean addPermission(PermissionInfo info) { 5266 synchronized (mPackages) { 5267 return addDynamicPermission(info, false); 5268 } 5269 } 5270 5271 @Override 5272 public boolean addPermissionAsync(PermissionInfo info) { 5273 synchronized (mPackages) { 5274 return addDynamicPermission(info, true); 5275 } 5276 } 5277 5278 @Override 5279 public void removePermission(String permName) { 5280 mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback); 5281 } 5282 5283 @Override 5284 public void grantRuntimePermission(String packageName, String permName, final int userId) { 5285 mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/, 5286 getCallingUid(), userId, mPermissionCallback); 5287 } 5288 5289 @Override 5290 public void revokeRuntimePermission(String packageName, String permName, int userId) { 5291 mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/, 5292 getCallingUid(), userId, mPermissionCallback); 5293 } 5294 5295 @Override 5296 public void resetRuntimePermissions() { 5297 mContext.enforceCallingOrSelfPermission( 5298 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5299 "revokeRuntimePermission"); 5300 5301 int callingUid = Binder.getCallingUid(); 5302 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5303 mContext.enforceCallingOrSelfPermission( 5304 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5305 "resetRuntimePermissions"); 5306 } 5307 5308 synchronized (mPackages) { 5309 mPermissionManager.updateAllPermissions( 5310 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 5311 mPermissionCallback); 5312 for (int userId : UserManagerService.getInstance().getUserIds()) { 5313 final int packageCount = mPackages.size(); 5314 for (int i = 0; i < packageCount; i++) { 5315 PackageParser.Package pkg = mPackages.valueAt(i); 5316 if (!(pkg.mExtras instanceof PackageSetting)) { 5317 continue; 5318 } 5319 PackageSetting ps = (PackageSetting) pkg.mExtras; 5320 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5321 } 5322 } 5323 } 5324 } 5325 5326 @Override 5327 public int getPermissionFlags(String permName, String packageName, int userId) { 5328 return mPermissionManager.getPermissionFlags( 5329 permName, packageName, getCallingUid(), userId); 5330 } 5331 5332 @Override 5333 public void updatePermissionFlags(String permName, String packageName, int flagMask, 5334 int flagValues, int userId) { 5335 mPermissionManager.updatePermissionFlags( 5336 permName, packageName, flagMask, flagValues, getCallingUid(), userId, 5337 mPermissionCallback); 5338 } 5339 5340 /** 5341 * Update the permission flags for all packages and runtime permissions of a user in order 5342 * to allow device or profile owner to remove POLICY_FIXED. 5343 */ 5344 @Override 5345 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5346 synchronized (mPackages) { 5347 final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps( 5348 flagMask, flagValues, getCallingUid(), userId, mPackages.values(), 5349 mPermissionCallback); 5350 if (changed) { 5351 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5352 } 5353 } 5354 } 5355 5356 @Override 5357 public boolean shouldShowRequestPermissionRationale(String permissionName, 5358 String packageName, int userId) { 5359 if (UserHandle.getCallingUserId() != userId) { 5360 mContext.enforceCallingPermission( 5361 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5362 "canShowRequestPermissionRationale for user " + userId); 5363 } 5364 5365 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5366 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5367 return false; 5368 } 5369 5370 if (checkPermission(permissionName, packageName, userId) 5371 == PackageManager.PERMISSION_GRANTED) { 5372 return false; 5373 } 5374 5375 final int flags; 5376 5377 final long identity = Binder.clearCallingIdentity(); 5378 try { 5379 flags = getPermissionFlags(permissionName, 5380 packageName, userId); 5381 } finally { 5382 Binder.restoreCallingIdentity(identity); 5383 } 5384 5385 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5386 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5387 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5388 5389 if ((flags & fixedFlags) != 0) { 5390 return false; 5391 } 5392 5393 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5394 } 5395 5396 @Override 5397 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5398 mContext.enforceCallingOrSelfPermission( 5399 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5400 "addOnPermissionsChangeListener"); 5401 5402 synchronized (mPackages) { 5403 mOnPermissionChangeListeners.addListenerLocked(listener); 5404 } 5405 } 5406 5407 @Override 5408 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5409 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5410 throw new SecurityException("Instant applications don't have access to this method"); 5411 } 5412 synchronized (mPackages) { 5413 mOnPermissionChangeListeners.removeListenerLocked(listener); 5414 } 5415 } 5416 5417 @Override 5418 public boolean isProtectedBroadcast(String actionName) { 5419 // allow instant applications 5420 synchronized (mProtectedBroadcasts) { 5421 if (mProtectedBroadcasts.contains(actionName)) { 5422 return true; 5423 } else if (actionName != null) { 5424 // TODO: remove these terrible hacks 5425 if (actionName.startsWith("android.net.netmon.lingerExpired") 5426 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5427 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5428 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5429 return true; 5430 } 5431 } 5432 } 5433 return false; 5434 } 5435 5436 @Override 5437 public int checkSignatures(String pkg1, String pkg2) { 5438 synchronized (mPackages) { 5439 final PackageParser.Package p1 = mPackages.get(pkg1); 5440 final PackageParser.Package p2 = mPackages.get(pkg2); 5441 if (p1 == null || p1.mExtras == null 5442 || p2 == null || p2.mExtras == null) { 5443 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5444 } 5445 final int callingUid = Binder.getCallingUid(); 5446 final int callingUserId = UserHandle.getUserId(callingUid); 5447 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 5448 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 5449 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 5450 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 5451 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5452 } 5453 return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures); 5454 } 5455 } 5456 5457 @Override 5458 public int checkUidSignatures(int uid1, int uid2) { 5459 final int callingUid = Binder.getCallingUid(); 5460 final int callingUserId = UserHandle.getUserId(callingUid); 5461 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5462 // Map to base uids. 5463 uid1 = UserHandle.getAppId(uid1); 5464 uid2 = UserHandle.getAppId(uid2); 5465 // reader 5466 synchronized (mPackages) { 5467 Signature[] s1; 5468 Signature[] s2; 5469 Object obj = mSettings.getUserIdLPr(uid1); 5470 if (obj != null) { 5471 if (obj instanceof SharedUserSetting) { 5472 if (isCallerInstantApp) { 5473 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5474 } 5475 s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5476 } else if (obj instanceof PackageSetting) { 5477 final PackageSetting ps = (PackageSetting) obj; 5478 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5479 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5480 } 5481 s1 = ps.signatures.mSigningDetails.signatures; 5482 } else { 5483 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5484 } 5485 } else { 5486 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5487 } 5488 obj = mSettings.getUserIdLPr(uid2); 5489 if (obj != null) { 5490 if (obj instanceof SharedUserSetting) { 5491 if (isCallerInstantApp) { 5492 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5493 } 5494 s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5495 } else if (obj instanceof PackageSetting) { 5496 final PackageSetting ps = (PackageSetting) obj; 5497 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5498 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5499 } 5500 s2 = ps.signatures.mSigningDetails.signatures; 5501 } else { 5502 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5503 } 5504 } else { 5505 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5506 } 5507 return compareSignatures(s1, s2); 5508 } 5509 } 5510 5511 @Override 5512 public boolean hasSigningCertificate( 5513 String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) { 5514 5515 synchronized (mPackages) { 5516 final PackageParser.Package p = mPackages.get(packageName); 5517 if (p == null || p.mExtras == null) { 5518 return false; 5519 } 5520 final int callingUid = Binder.getCallingUid(); 5521 final int callingUserId = UserHandle.getUserId(callingUid); 5522 final PackageSetting ps = (PackageSetting) p.mExtras; 5523 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5524 return false; 5525 } 5526 switch (type) { 5527 case CERT_INPUT_RAW_X509: 5528 return signingDetailsHasCertificate(certificate, p.mSigningDetails); 5529 case CERT_INPUT_SHA256: 5530 return signingDetailsHasSha256Certificate(certificate, p.mSigningDetails); 5531 default: 5532 return false; 5533 } 5534 } 5535 } 5536 5537 @Override 5538 public boolean hasUidSigningCertificate( 5539 int uid, byte[] certificate, @PackageManager.CertificateInputType int type) { 5540 final int callingUid = Binder.getCallingUid(); 5541 final int callingUserId = UserHandle.getUserId(callingUid); 5542 // Map to base uids. 5543 uid = UserHandle.getAppId(uid); 5544 // reader 5545 synchronized (mPackages) { 5546 final PackageParser.SigningDetails signingDetails; 5547 final Object obj = mSettings.getUserIdLPr(uid); 5548 if (obj != null) { 5549 if (obj instanceof SharedUserSetting) { 5550 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5551 if (isCallerInstantApp) { 5552 return false; 5553 } 5554 signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails; 5555 } else if (obj instanceof PackageSetting) { 5556 final PackageSetting ps = (PackageSetting) obj; 5557 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5558 return false; 5559 } 5560 signingDetails = ps.signatures.mSigningDetails; 5561 } else { 5562 return false; 5563 } 5564 } else { 5565 return false; 5566 } 5567 switch (type) { 5568 case CERT_INPUT_RAW_X509: 5569 return signingDetailsHasCertificate(certificate, signingDetails); 5570 case CERT_INPUT_SHA256: 5571 return signingDetailsHasSha256Certificate(certificate, signingDetails); 5572 default: 5573 return false; 5574 } 5575 } 5576 } 5577 5578 /** 5579 * This method should typically only be used when granting or revoking 5580 * permissions, since the app may immediately restart after this call. 5581 * <p> 5582 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5583 * guard your work against the app being relaunched. 5584 */ 5585 private void killUid(int appId, int userId, String reason) { 5586 final long identity = Binder.clearCallingIdentity(); 5587 try { 5588 IActivityManager am = ActivityManager.getService(); 5589 if (am != null) { 5590 try { 5591 am.killUid(appId, userId, reason); 5592 } catch (RemoteException e) { 5593 /* ignore - same process */ 5594 } 5595 } 5596 } finally { 5597 Binder.restoreCallingIdentity(identity); 5598 } 5599 } 5600 5601 /** 5602 * If the database version for this type of package (internal storage or 5603 * external storage) is less than the version where package signatures 5604 * were updated, return true. 5605 */ 5606 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5607 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5608 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5609 } 5610 5611 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5612 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5613 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5614 } 5615 5616 @Override 5617 public List<String> getAllPackages() { 5618 final int callingUid = Binder.getCallingUid(); 5619 final int callingUserId = UserHandle.getUserId(callingUid); 5620 synchronized (mPackages) { 5621 if (canViewInstantApps(callingUid, callingUserId)) { 5622 return new ArrayList<String>(mPackages.keySet()); 5623 } 5624 final String instantAppPkgName = getInstantAppPackageName(callingUid); 5625 final List<String> result = new ArrayList<>(); 5626 if (instantAppPkgName != null) { 5627 // caller is an instant application; filter unexposed applications 5628 for (PackageParser.Package pkg : mPackages.values()) { 5629 if (!pkg.visibleToInstantApps) { 5630 continue; 5631 } 5632 result.add(pkg.packageName); 5633 } 5634 } else { 5635 // caller is a normal application; filter instant applications 5636 for (PackageParser.Package pkg : mPackages.values()) { 5637 final PackageSetting ps = 5638 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 5639 if (ps != null 5640 && ps.getInstantApp(callingUserId) 5641 && !mInstantAppRegistry.isInstantAccessGranted( 5642 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 5643 continue; 5644 } 5645 result.add(pkg.packageName); 5646 } 5647 } 5648 return result; 5649 } 5650 } 5651 5652 @Override 5653 public String[] getPackagesForUid(int uid) { 5654 final int callingUid = Binder.getCallingUid(); 5655 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5656 final int userId = UserHandle.getUserId(uid); 5657 uid = UserHandle.getAppId(uid); 5658 // reader 5659 synchronized (mPackages) { 5660 Object obj = mSettings.getUserIdLPr(uid); 5661 if (obj instanceof SharedUserSetting) { 5662 if (isCallerInstantApp) { 5663 return null; 5664 } 5665 final SharedUserSetting sus = (SharedUserSetting) obj; 5666 final int N = sus.packages.size(); 5667 String[] res = new String[N]; 5668 final Iterator<PackageSetting> it = sus.packages.iterator(); 5669 int i = 0; 5670 while (it.hasNext()) { 5671 PackageSetting ps = it.next(); 5672 if (ps.getInstalled(userId)) { 5673 res[i++] = ps.name; 5674 } else { 5675 res = ArrayUtils.removeElement(String.class, res, res[i]); 5676 } 5677 } 5678 return res; 5679 } else if (obj instanceof PackageSetting) { 5680 final PackageSetting ps = (PackageSetting) obj; 5681 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 5682 return new String[]{ps.name}; 5683 } 5684 } 5685 } 5686 return null; 5687 } 5688 5689 @Override 5690 public String getNameForUid(int uid) { 5691 final int callingUid = Binder.getCallingUid(); 5692 if (getInstantAppPackageName(callingUid) != null) { 5693 return null; 5694 } 5695 synchronized (mPackages) { 5696 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5697 if (obj instanceof SharedUserSetting) { 5698 final SharedUserSetting sus = (SharedUserSetting) obj; 5699 return sus.name + ":" + sus.userId; 5700 } else if (obj instanceof PackageSetting) { 5701 final PackageSetting ps = (PackageSetting) obj; 5702 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5703 return null; 5704 } 5705 return ps.name; 5706 } 5707 return null; 5708 } 5709 } 5710 5711 @Override 5712 public String[] getNamesForUids(int[] uids) { 5713 if (uids == null || uids.length == 0) { 5714 return null; 5715 } 5716 final int callingUid = Binder.getCallingUid(); 5717 if (getInstantAppPackageName(callingUid) != null) { 5718 return null; 5719 } 5720 final String[] names = new String[uids.length]; 5721 synchronized (mPackages) { 5722 for (int i = uids.length - 1; i >= 0; i--) { 5723 final int uid = uids[i]; 5724 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5725 if (obj instanceof SharedUserSetting) { 5726 final SharedUserSetting sus = (SharedUserSetting) obj; 5727 names[i] = "shared:" + sus.name; 5728 } else if (obj instanceof PackageSetting) { 5729 final PackageSetting ps = (PackageSetting) obj; 5730 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5731 names[i] = null; 5732 } else { 5733 names[i] = ps.name; 5734 } 5735 } else { 5736 names[i] = null; 5737 } 5738 } 5739 } 5740 return names; 5741 } 5742 5743 @Override 5744 public int getUidForSharedUser(String sharedUserName) { 5745 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5746 return -1; 5747 } 5748 if (sharedUserName == null) { 5749 return -1; 5750 } 5751 // reader 5752 synchronized (mPackages) { 5753 SharedUserSetting suid; 5754 try { 5755 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5756 if (suid != null) { 5757 return suid.userId; 5758 } 5759 } catch (PackageManagerException ignore) { 5760 // can't happen, but, still need to catch it 5761 } 5762 return -1; 5763 } 5764 } 5765 5766 @Override 5767 public int getFlagsForUid(int uid) { 5768 final int callingUid = Binder.getCallingUid(); 5769 if (getInstantAppPackageName(callingUid) != null) { 5770 return 0; 5771 } 5772 synchronized (mPackages) { 5773 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5774 if (obj instanceof SharedUserSetting) { 5775 final SharedUserSetting sus = (SharedUserSetting) obj; 5776 return sus.pkgFlags; 5777 } else if (obj instanceof PackageSetting) { 5778 final PackageSetting ps = (PackageSetting) obj; 5779 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5780 return 0; 5781 } 5782 return ps.pkgFlags; 5783 } 5784 } 5785 return 0; 5786 } 5787 5788 @Override 5789 public int getPrivateFlagsForUid(int uid) { 5790 final int callingUid = Binder.getCallingUid(); 5791 if (getInstantAppPackageName(callingUid) != null) { 5792 return 0; 5793 } 5794 synchronized (mPackages) { 5795 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5796 if (obj instanceof SharedUserSetting) { 5797 final SharedUserSetting sus = (SharedUserSetting) obj; 5798 return sus.pkgPrivateFlags; 5799 } else if (obj instanceof PackageSetting) { 5800 final PackageSetting ps = (PackageSetting) obj; 5801 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5802 return 0; 5803 } 5804 return ps.pkgPrivateFlags; 5805 } 5806 } 5807 return 0; 5808 } 5809 5810 @Override 5811 public boolean isUidPrivileged(int uid) { 5812 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5813 return false; 5814 } 5815 uid = UserHandle.getAppId(uid); 5816 // reader 5817 synchronized (mPackages) { 5818 Object obj = mSettings.getUserIdLPr(uid); 5819 if (obj instanceof SharedUserSetting) { 5820 final SharedUserSetting sus = (SharedUserSetting) obj; 5821 final Iterator<PackageSetting> it = sus.packages.iterator(); 5822 while (it.hasNext()) { 5823 if (it.next().isPrivileged()) { 5824 return true; 5825 } 5826 } 5827 } else if (obj instanceof PackageSetting) { 5828 final PackageSetting ps = (PackageSetting) obj; 5829 return ps.isPrivileged(); 5830 } 5831 } 5832 return false; 5833 } 5834 5835 @Override 5836 public String[] getAppOpPermissionPackages(String permName) { 5837 return mPermissionManager.getAppOpPermissionPackages(permName); 5838 } 5839 5840 @Override 5841 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5842 int flags, int userId) { 5843 return resolveIntentInternal( 5844 intent, resolvedType, flags, userId, false /*resolveForStart*/); 5845 } 5846 5847 /** 5848 * Normally instant apps can only be resolved when they're visible to the caller. 5849 * However, if {@code resolveForStart} is {@code true}, all instant apps are visible 5850 * since we need to allow the system to start any installed application. 5851 */ 5852 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5853 int flags, int userId, boolean resolveForStart) { 5854 try { 5855 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5856 5857 if (!sUserManager.exists(userId)) return null; 5858 final int callingUid = Binder.getCallingUid(); 5859 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 5860 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5861 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5862 5863 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5864 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5865 flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/); 5866 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5867 5868 final ResolveInfo bestChoice = 5869 chooseBestActivity(intent, resolvedType, flags, query, userId); 5870 return bestChoice; 5871 } finally { 5872 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5873 } 5874 } 5875 5876 @Override 5877 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5878 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5879 throw new SecurityException( 5880 "findPersistentPreferredActivity can only be run by the system"); 5881 } 5882 if (!sUserManager.exists(userId)) { 5883 return null; 5884 } 5885 final int callingUid = Binder.getCallingUid(); 5886 intent = updateIntentForResolve(intent); 5887 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5888 final int flags = updateFlagsForResolve( 5889 0, userId, intent, callingUid, false /*includeInstantApps*/); 5890 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5891 userId); 5892 synchronized (mPackages) { 5893 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5894 userId); 5895 } 5896 } 5897 5898 @Override 5899 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5900 IntentFilter filter, int match, ComponentName activity) { 5901 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5902 return; 5903 } 5904 final int userId = UserHandle.getCallingUserId(); 5905 if (DEBUG_PREFERRED) { 5906 Log.v(TAG, "setLastChosenActivity intent=" + intent 5907 + " resolvedType=" + resolvedType 5908 + " flags=" + flags 5909 + " filter=" + filter 5910 + " match=" + match 5911 + " activity=" + activity); 5912 filter.dump(new PrintStreamPrinter(System.out), " "); 5913 } 5914 intent.setComponent(null); 5915 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5916 userId); 5917 // Find any earlier preferred or last chosen entries and nuke them 5918 findPreferredActivity(intent, resolvedType, 5919 flags, query, 0, false, true, false, userId); 5920 // Add the new activity as the last chosen for this filter 5921 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5922 "Setting last chosen"); 5923 } 5924 5925 @Override 5926 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5927 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5928 return null; 5929 } 5930 final int userId = UserHandle.getCallingUserId(); 5931 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5932 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5933 userId); 5934 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5935 false, false, false, userId); 5936 } 5937 5938 /** 5939 * Returns whether or not instant apps have been disabled remotely. 5940 */ 5941 private boolean isEphemeralDisabled() { 5942 return mEphemeralAppsDisabled; 5943 } 5944 5945 private boolean isInstantAppAllowed( 5946 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5947 boolean skipPackageCheck) { 5948 if (mInstantAppResolverConnection == null) { 5949 return false; 5950 } 5951 if (mInstantAppInstallerActivity == null) { 5952 return false; 5953 } 5954 if (intent.getComponent() != null) { 5955 return false; 5956 } 5957 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5958 return false; 5959 } 5960 if (!skipPackageCheck && intent.getPackage() != null) { 5961 return false; 5962 } 5963 if (!intent.isBrowsableWebIntent()) { 5964 // for non web intents, we should not resolve externally if an app already exists to 5965 // handle it or if the caller didn't explicitly request it. 5966 if ((resolvedActivities != null && resolvedActivities.size() != 0) 5967 || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) { 5968 return false; 5969 } 5970 } else if (intent.getData() == null) { 5971 return false; 5972 } 5973 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5974 // Or if there's already an ephemeral app installed that handles the action 5975 synchronized (mPackages) { 5976 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5977 for (int n = 0; n < count; n++) { 5978 final ResolveInfo info = resolvedActivities.get(n); 5979 final String packageName = info.activityInfo.packageName; 5980 final PackageSetting ps = mSettings.mPackages.get(packageName); 5981 if (ps != null) { 5982 // only check domain verification status if the app is not a browser 5983 if (!info.handleAllWebDataURI) { 5984 // Try to get the status from User settings first 5985 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5986 final int status = (int) (packedStatus >> 32); 5987 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5988 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5989 if (DEBUG_INSTANT) { 5990 Slog.v(TAG, "DENY instant app;" 5991 + " pkg: " + packageName + ", status: " + status); 5992 } 5993 return false; 5994 } 5995 } 5996 if (ps.getInstantApp(userId)) { 5997 if (DEBUG_INSTANT) { 5998 Slog.v(TAG, "DENY instant app installed;" 5999 + " pkg: " + packageName); 6000 } 6001 return false; 6002 } 6003 } 6004 } 6005 } 6006 // We've exhausted all ways to deny ephemeral application; let the system look for them. 6007 return true; 6008 } 6009 6010 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 6011 Intent origIntent, String resolvedType, String callingPackage, 6012 Bundle verificationBundle, int userId) { 6013 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 6014 new InstantAppRequest(responseObj, origIntent, resolvedType, 6015 callingPackage, userId, verificationBundle, false /*resolveForStart*/)); 6016 mHandler.sendMessage(msg); 6017 } 6018 6019 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 6020 int flags, List<ResolveInfo> query, int userId) { 6021 if (query != null) { 6022 final int N = query.size(); 6023 if (N == 1) { 6024 return query.get(0); 6025 } else if (N > 1) { 6026 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 6027 // If there is more than one activity with the same priority, 6028 // then let the user decide between them. 6029 ResolveInfo r0 = query.get(0); 6030 ResolveInfo r1 = query.get(1); 6031 if (DEBUG_INTENT_MATCHING || debug) { 6032 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 6033 + r1.activityInfo.name + "=" + r1.priority); 6034 } 6035 // If the first activity has a higher priority, or a different 6036 // default, then it is always desirable to pick it. 6037 if (r0.priority != r1.priority 6038 || r0.preferredOrder != r1.preferredOrder 6039 || r0.isDefault != r1.isDefault) { 6040 return query.get(0); 6041 } 6042 // If we have saved a preference for a preferred activity for 6043 // this Intent, use that. 6044 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 6045 flags, query, r0.priority, true, false, debug, userId); 6046 if (ri != null) { 6047 return ri; 6048 } 6049 // If we have an ephemeral app, use it 6050 for (int i = 0; i < N; i++) { 6051 ri = query.get(i); 6052 if (ri.activityInfo.applicationInfo.isInstantApp()) { 6053 final String packageName = ri.activityInfo.packageName; 6054 final PackageSetting ps = mSettings.mPackages.get(packageName); 6055 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6056 final int status = (int)(packedStatus >> 32); 6057 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6058 return ri; 6059 } 6060 } 6061 } 6062 ri = new ResolveInfo(mResolveInfo); 6063 ri.activityInfo = new ActivityInfo(ri.activityInfo); 6064 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 6065 // If all of the options come from the same package, show the application's 6066 // label and icon instead of the generic resolver's. 6067 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 6068 // and then throw away the ResolveInfo itself, meaning that the caller loses 6069 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 6070 // a fallback for this case; we only set the target package's resources on 6071 // the ResolveInfo, not the ActivityInfo. 6072 final String intentPackage = intent.getPackage(); 6073 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 6074 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 6075 ri.resolvePackageName = intentPackage; 6076 if (userNeedsBadging(userId)) { 6077 ri.noResourceId = true; 6078 } else { 6079 ri.icon = appi.icon; 6080 } 6081 ri.iconResourceId = appi.icon; 6082 ri.labelRes = appi.labelRes; 6083 } 6084 ri.activityInfo.applicationInfo = new ApplicationInfo( 6085 ri.activityInfo.applicationInfo); 6086 if (userId != 0) { 6087 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6088 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6089 } 6090 // Make sure that the resolver is displayable in car mode 6091 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6092 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6093 return ri; 6094 } 6095 } 6096 return null; 6097 } 6098 6099 /** 6100 * Return true if the given list is not empty and all of its contents have 6101 * an activityInfo with the given package name. 6102 */ 6103 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6104 if (ArrayUtils.isEmpty(list)) { 6105 return false; 6106 } 6107 for (int i = 0, N = list.size(); i < N; i++) { 6108 final ResolveInfo ri = list.get(i); 6109 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6110 if (ai == null || !packageName.equals(ai.packageName)) { 6111 return false; 6112 } 6113 } 6114 return true; 6115 } 6116 6117 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6118 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6119 final int N = query.size(); 6120 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6121 .get(userId); 6122 // Get the list of persistent preferred activities that handle the intent 6123 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6124 List<PersistentPreferredActivity> pprefs = ppir != null 6125 ? ppir.queryIntent(intent, resolvedType, 6126 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6127 userId) 6128 : null; 6129 if (pprefs != null && pprefs.size() > 0) { 6130 final int M = pprefs.size(); 6131 for (int i=0; i<M; i++) { 6132 final PersistentPreferredActivity ppa = pprefs.get(i); 6133 if (DEBUG_PREFERRED || debug) { 6134 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6135 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6136 + "\n component=" + ppa.mComponent); 6137 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6138 } 6139 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6140 flags | MATCH_DISABLED_COMPONENTS, userId); 6141 if (DEBUG_PREFERRED || debug) { 6142 Slog.v(TAG, "Found persistent preferred activity:"); 6143 if (ai != null) { 6144 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6145 } else { 6146 Slog.v(TAG, " null"); 6147 } 6148 } 6149 if (ai == null) { 6150 // This previously registered persistent preferred activity 6151 // component is no longer known. Ignore it and do NOT remove it. 6152 continue; 6153 } 6154 for (int j=0; j<N; j++) { 6155 final ResolveInfo ri = query.get(j); 6156 if (!ri.activityInfo.applicationInfo.packageName 6157 .equals(ai.applicationInfo.packageName)) { 6158 continue; 6159 } 6160 if (!ri.activityInfo.name.equals(ai.name)) { 6161 continue; 6162 } 6163 // Found a persistent preference that can handle the intent. 6164 if (DEBUG_PREFERRED || debug) { 6165 Slog.v(TAG, "Returning persistent preferred activity: " + 6166 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6167 } 6168 return ri; 6169 } 6170 } 6171 } 6172 return null; 6173 } 6174 6175 // TODO: handle preferred activities missing while user has amnesia 6176 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6177 List<ResolveInfo> query, int priority, boolean always, 6178 boolean removeMatches, boolean debug, int userId) { 6179 if (!sUserManager.exists(userId)) return null; 6180 final int callingUid = Binder.getCallingUid(); 6181 flags = updateFlagsForResolve( 6182 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6183 intent = updateIntentForResolve(intent); 6184 // writer 6185 synchronized (mPackages) { 6186 // Try to find a matching persistent preferred activity. 6187 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6188 debug, userId); 6189 6190 // If a persistent preferred activity matched, use it. 6191 if (pri != null) { 6192 return pri; 6193 } 6194 6195 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6196 // Get the list of preferred activities that handle the intent 6197 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6198 List<PreferredActivity> prefs = pir != null 6199 ? pir.queryIntent(intent, resolvedType, 6200 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6201 userId) 6202 : null; 6203 if (prefs != null && prefs.size() > 0) { 6204 boolean changed = false; 6205 try { 6206 // First figure out how good the original match set is. 6207 // We will only allow preferred activities that came 6208 // from the same match quality. 6209 int match = 0; 6210 6211 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6212 6213 final int N = query.size(); 6214 for (int j=0; j<N; j++) { 6215 final ResolveInfo ri = query.get(j); 6216 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6217 + ": 0x" + Integer.toHexString(match)); 6218 if (ri.match > match) { 6219 match = ri.match; 6220 } 6221 } 6222 6223 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6224 + Integer.toHexString(match)); 6225 6226 match &= IntentFilter.MATCH_CATEGORY_MASK; 6227 final int M = prefs.size(); 6228 for (int i=0; i<M; i++) { 6229 final PreferredActivity pa = prefs.get(i); 6230 if (DEBUG_PREFERRED || debug) { 6231 Slog.v(TAG, "Checking PreferredActivity ds=" 6232 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6233 + "\n component=" + pa.mPref.mComponent); 6234 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6235 } 6236 if (pa.mPref.mMatch != match) { 6237 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6238 + Integer.toHexString(pa.mPref.mMatch)); 6239 continue; 6240 } 6241 // If it's not an "always" type preferred activity and that's what we're 6242 // looking for, skip it. 6243 if (always && !pa.mPref.mAlways) { 6244 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6245 continue; 6246 } 6247 final ActivityInfo ai = getActivityInfo( 6248 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6249 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6250 userId); 6251 if (DEBUG_PREFERRED || debug) { 6252 Slog.v(TAG, "Found preferred activity:"); 6253 if (ai != null) { 6254 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6255 } else { 6256 Slog.v(TAG, " null"); 6257 } 6258 } 6259 if (ai == null) { 6260 // This previously registered preferred activity 6261 // component is no longer known. Most likely an update 6262 // to the app was installed and in the new version this 6263 // component no longer exists. Clean it up by removing 6264 // it from the preferred activities list, and skip it. 6265 Slog.w(TAG, "Removing dangling preferred activity: " 6266 + pa.mPref.mComponent); 6267 pir.removeFilter(pa); 6268 changed = true; 6269 continue; 6270 } 6271 for (int j=0; j<N; j++) { 6272 final ResolveInfo ri = query.get(j); 6273 if (!ri.activityInfo.applicationInfo.packageName 6274 .equals(ai.applicationInfo.packageName)) { 6275 continue; 6276 } 6277 if (!ri.activityInfo.name.equals(ai.name)) { 6278 continue; 6279 } 6280 6281 if (removeMatches) { 6282 pir.removeFilter(pa); 6283 changed = true; 6284 if (DEBUG_PREFERRED) { 6285 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6286 } 6287 break; 6288 } 6289 6290 // Okay we found a previously set preferred or last chosen app. 6291 // If the result set is different from when this 6292 // was created, and is not a subset of the preferred set, we need to 6293 // clear it and re-ask the user their preference, if we're looking for 6294 // an "always" type entry. 6295 if (always && !pa.mPref.sameSet(query)) { 6296 if (pa.mPref.isSuperset(query)) { 6297 // some components of the set are no longer present in 6298 // the query, but the preferred activity can still be reused 6299 if (DEBUG_PREFERRED) { 6300 Slog.i(TAG, "Result set changed, but PreferredActivity is" 6301 + " still valid as only non-preferred components" 6302 + " were removed for " + intent + " type " 6303 + resolvedType); 6304 } 6305 // remove obsolete components and re-add the up-to-date filter 6306 PreferredActivity freshPa = new PreferredActivity(pa, 6307 pa.mPref.mMatch, 6308 pa.mPref.discardObsoleteComponents(query), 6309 pa.mPref.mComponent, 6310 pa.mPref.mAlways); 6311 pir.removeFilter(pa); 6312 pir.addFilter(freshPa); 6313 changed = true; 6314 } else { 6315 Slog.i(TAG, 6316 "Result set changed, dropping preferred activity for " 6317 + intent + " type " + resolvedType); 6318 if (DEBUG_PREFERRED) { 6319 Slog.v(TAG, "Removing preferred activity since set changed " 6320 + pa.mPref.mComponent); 6321 } 6322 pir.removeFilter(pa); 6323 // Re-add the filter as a "last chosen" entry (!always) 6324 PreferredActivity lastChosen = new PreferredActivity( 6325 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6326 pir.addFilter(lastChosen); 6327 changed = true; 6328 return null; 6329 } 6330 } 6331 6332 // Yay! Either the set matched or we're looking for the last chosen 6333 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6334 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6335 return ri; 6336 } 6337 } 6338 } finally { 6339 if (changed) { 6340 if (DEBUG_PREFERRED) { 6341 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6342 } 6343 scheduleWritePackageRestrictionsLocked(userId); 6344 } 6345 } 6346 } 6347 } 6348 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6349 return null; 6350 } 6351 6352 /* 6353 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6354 */ 6355 @Override 6356 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6357 int targetUserId) { 6358 mContext.enforceCallingOrSelfPermission( 6359 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6360 List<CrossProfileIntentFilter> matches = 6361 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6362 if (matches != null) { 6363 int size = matches.size(); 6364 for (int i = 0; i < size; i++) { 6365 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6366 } 6367 } 6368 if (intent.hasWebURI()) { 6369 // cross-profile app linking works only towards the parent. 6370 final int callingUid = Binder.getCallingUid(); 6371 final UserInfo parent = getProfileParent(sourceUserId); 6372 synchronized(mPackages) { 6373 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6374 false /*includeInstantApps*/); 6375 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6376 intent, resolvedType, flags, sourceUserId, parent.id); 6377 return xpDomainInfo != null; 6378 } 6379 } 6380 return false; 6381 } 6382 6383 private UserInfo getProfileParent(int userId) { 6384 final long identity = Binder.clearCallingIdentity(); 6385 try { 6386 return sUserManager.getProfileParent(userId); 6387 } finally { 6388 Binder.restoreCallingIdentity(identity); 6389 } 6390 } 6391 6392 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6393 String resolvedType, int userId) { 6394 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6395 if (resolver != null) { 6396 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6397 } 6398 return null; 6399 } 6400 6401 @Override 6402 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6403 String resolvedType, int flags, int userId) { 6404 try { 6405 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6406 6407 return new ParceledListSlice<>( 6408 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6409 } finally { 6410 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6411 } 6412 } 6413 6414 /** 6415 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6416 * instant, returns {@code null}. 6417 */ 6418 private String getInstantAppPackageName(int callingUid) { 6419 synchronized (mPackages) { 6420 // If the caller is an isolated app use the owner's uid for the lookup. 6421 if (Process.isIsolated(callingUid)) { 6422 callingUid = mIsolatedOwners.get(callingUid); 6423 } 6424 final int appId = UserHandle.getAppId(callingUid); 6425 final Object obj = mSettings.getUserIdLPr(appId); 6426 if (obj instanceof PackageSetting) { 6427 final PackageSetting ps = (PackageSetting) obj; 6428 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6429 return isInstantApp ? ps.pkg.packageName : null; 6430 } 6431 } 6432 return null; 6433 } 6434 6435 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6436 String resolvedType, int flags, int userId) { 6437 return queryIntentActivitiesInternal( 6438 intent, resolvedType, flags, Binder.getCallingUid(), userId, 6439 false /*resolveForStart*/, true /*allowDynamicSplits*/); 6440 } 6441 6442 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6443 String resolvedType, int flags, int filterCallingUid, int userId, 6444 boolean resolveForStart, boolean allowDynamicSplits) { 6445 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6446 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 6447 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 6448 false /* requireFullPermission */, false /* checkShell */, 6449 "query intent activities"); 6450 final String pkgName = intent.getPackage(); 6451 ComponentName comp = intent.getComponent(); 6452 if (comp == null) { 6453 if (intent.getSelector() != null) { 6454 intent = intent.getSelector(); 6455 comp = intent.getComponent(); 6456 } 6457 } 6458 6459 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 6460 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6461 if (comp != null) { 6462 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6463 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6464 if (ai != null) { 6465 // When specifying an explicit component, we prevent the activity from being 6466 // used when either 1) the calling package is normal and the activity is within 6467 // an ephemeral application or 2) the calling package is ephemeral and the 6468 // activity is not visible to ephemeral applications. 6469 final boolean matchInstantApp = 6470 (flags & PackageManager.MATCH_INSTANT) != 0; 6471 final boolean matchVisibleToInstantAppOnly = 6472 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6473 final boolean matchExplicitlyVisibleOnly = 6474 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6475 final boolean isCallerInstantApp = 6476 instantAppPkgName != null; 6477 final boolean isTargetSameInstantApp = 6478 comp.getPackageName().equals(instantAppPkgName); 6479 final boolean isTargetInstantApp = 6480 (ai.applicationInfo.privateFlags 6481 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6482 final boolean isTargetVisibleToInstantApp = 6483 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6484 final boolean isTargetExplicitlyVisibleToInstantApp = 6485 isTargetVisibleToInstantApp 6486 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6487 final boolean isTargetHiddenFromInstantApp = 6488 !isTargetVisibleToInstantApp 6489 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6490 final boolean blockResolution = 6491 !isTargetSameInstantApp 6492 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6493 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6494 && isTargetHiddenFromInstantApp)); 6495 if (!blockResolution) { 6496 final ResolveInfo ri = new ResolveInfo(); 6497 ri.activityInfo = ai; 6498 list.add(ri); 6499 } 6500 } 6501 return applyPostResolutionFilter( 6502 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6503 } 6504 6505 // reader 6506 boolean sortResult = false; 6507 boolean addEphemeral = false; 6508 List<ResolveInfo> result; 6509 final boolean ephemeralDisabled = isEphemeralDisabled(); 6510 synchronized (mPackages) { 6511 if (pkgName == null) { 6512 List<CrossProfileIntentFilter> matchingFilters = 6513 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6514 // Check for results that need to skip the current profile. 6515 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6516 resolvedType, flags, userId); 6517 if (xpResolveInfo != null) { 6518 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6519 xpResult.add(xpResolveInfo); 6520 return applyPostResolutionFilter( 6521 filterIfNotSystemUser(xpResult, userId), instantAppPkgName, 6522 allowDynamicSplits, filterCallingUid, userId); 6523 } 6524 6525 // Check for results in the current profile. 6526 result = filterIfNotSystemUser(mActivities.queryIntent( 6527 intent, resolvedType, flags, userId), userId); 6528 addEphemeral = !ephemeralDisabled 6529 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/); 6530 // Check for cross profile results. 6531 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6532 xpResolveInfo = queryCrossProfileIntents( 6533 matchingFilters, intent, resolvedType, flags, userId, 6534 hasNonNegativePriorityResult); 6535 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6536 boolean isVisibleToUser = filterIfNotSystemUser( 6537 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6538 if (isVisibleToUser) { 6539 result.add(xpResolveInfo); 6540 sortResult = true; 6541 } 6542 } 6543 if (intent.hasWebURI()) { 6544 CrossProfileDomainInfo xpDomainInfo = null; 6545 final UserInfo parent = getProfileParent(userId); 6546 if (parent != null) { 6547 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6548 flags, userId, parent.id); 6549 } 6550 if (xpDomainInfo != null) { 6551 if (xpResolveInfo != null) { 6552 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6553 // in the result. 6554 result.remove(xpResolveInfo); 6555 } 6556 if (result.size() == 0 && !addEphemeral) { 6557 // No result in current profile, but found candidate in parent user. 6558 // And we are not going to add emphemeral app, so we can return the 6559 // result straight away. 6560 result.add(xpDomainInfo.resolveInfo); 6561 return applyPostResolutionFilter(result, instantAppPkgName, 6562 allowDynamicSplits, filterCallingUid, userId); 6563 } 6564 } else if (result.size() <= 1 && !addEphemeral) { 6565 // No result in parent user and <= 1 result in current profile, and we 6566 // are not going to add emphemeral app, so we can return the result without 6567 // further processing. 6568 return applyPostResolutionFilter(result, instantAppPkgName, 6569 allowDynamicSplits, filterCallingUid, userId); 6570 } 6571 // We have more than one candidate (combining results from current and parent 6572 // profile), so we need filtering and sorting. 6573 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6574 intent, flags, result, xpDomainInfo, userId); 6575 sortResult = true; 6576 } 6577 } else { 6578 final PackageParser.Package pkg = mPackages.get(pkgName); 6579 result = null; 6580 if (pkg != null) { 6581 result = filterIfNotSystemUser( 6582 mActivities.queryIntentForPackage( 6583 intent, resolvedType, flags, pkg.activities, userId), 6584 userId); 6585 } 6586 if (result == null || result.size() == 0) { 6587 // the caller wants to resolve for a particular package; however, there 6588 // were no installed results, so, try to find an ephemeral result 6589 addEphemeral = !ephemeralDisabled 6590 && isInstantAppAllowed( 6591 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6592 if (result == null) { 6593 result = new ArrayList<>(); 6594 } 6595 } 6596 } 6597 } 6598 if (addEphemeral) { 6599 result = maybeAddInstantAppInstaller( 6600 result, intent, resolvedType, flags, userId, resolveForStart); 6601 } 6602 if (sortResult) { 6603 Collections.sort(result, mResolvePrioritySorter); 6604 } 6605 return applyPostResolutionFilter( 6606 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6607 } 6608 6609 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 6610 String resolvedType, int flags, int userId, boolean resolveForStart) { 6611 // first, check to see if we've got an instant app already installed 6612 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 6613 ResolveInfo localInstantApp = null; 6614 boolean blockResolution = false; 6615 if (!alreadyResolvedLocally) { 6616 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 6617 flags 6618 | PackageManager.GET_RESOLVED_FILTER 6619 | PackageManager.MATCH_INSTANT 6620 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 6621 userId); 6622 for (int i = instantApps.size() - 1; i >= 0; --i) { 6623 final ResolveInfo info = instantApps.get(i); 6624 final String packageName = info.activityInfo.packageName; 6625 final PackageSetting ps = mSettings.mPackages.get(packageName); 6626 if (ps.getInstantApp(userId)) { 6627 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6628 final int status = (int)(packedStatus >> 32); 6629 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6630 // there's a local instant application installed, but, the user has 6631 // chosen to never use it; skip resolution and don't acknowledge 6632 // an instant application is even available 6633 if (DEBUG_INSTANT) { 6634 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 6635 } 6636 blockResolution = true; 6637 break; 6638 } else { 6639 // we have a locally installed instant application; skip resolution 6640 // but acknowledge there's an instant application available 6641 if (DEBUG_INSTANT) { 6642 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 6643 } 6644 localInstantApp = info; 6645 break; 6646 } 6647 } 6648 } 6649 } 6650 // no app installed, let's see if one's available 6651 AuxiliaryResolveInfo auxiliaryResponse = null; 6652 if (!blockResolution) { 6653 if (localInstantApp == null) { 6654 // we don't have an instant app locally, resolve externally 6655 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6656 final InstantAppRequest requestObject = new InstantAppRequest( 6657 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6658 null /*callingPackage*/, userId, null /*verificationBundle*/, 6659 resolveForStart); 6660 auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne( 6661 mInstantAppResolverConnection, requestObject); 6662 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6663 } else { 6664 // we have an instant application locally, but, we can't admit that since 6665 // callers shouldn't be able to determine prior browsing. create a dummy 6666 // auxiliary response so the downstream code behaves as if there's an 6667 // instant application available externally. when it comes time to start 6668 // the instant application, we'll do the right thing. 6669 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 6670 auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */, 6671 ai.packageName, ai.versionCode, null /* splitName */); 6672 } 6673 } 6674 if (intent.isBrowsableWebIntent() && auxiliaryResponse == null) { 6675 return result; 6676 } 6677 final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6678 if (ps == null) { 6679 return result; 6680 } 6681 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6682 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6683 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6684 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6685 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6686 // add a non-generic filter 6687 ephemeralInstaller.filter = new IntentFilter(); 6688 if (intent.getAction() != null) { 6689 ephemeralInstaller.filter.addAction(intent.getAction()); 6690 } 6691 if (intent.getData() != null && intent.getData().getPath() != null) { 6692 ephemeralInstaller.filter.addDataPath( 6693 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6694 } 6695 ephemeralInstaller.isInstantAppAvailable = true; 6696 // make sure this resolver is the default 6697 ephemeralInstaller.isDefault = true; 6698 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6699 if (DEBUG_INSTANT) { 6700 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6701 } 6702 6703 result.add(ephemeralInstaller); 6704 return result; 6705 } 6706 6707 private static class CrossProfileDomainInfo { 6708 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6709 ResolveInfo resolveInfo; 6710 /* Best domain verification status of the activities found in the other profile */ 6711 int bestDomainVerificationStatus; 6712 } 6713 6714 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6715 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6716 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6717 sourceUserId)) { 6718 return null; 6719 } 6720 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6721 resolvedType, flags, parentUserId); 6722 6723 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6724 return null; 6725 } 6726 CrossProfileDomainInfo result = null; 6727 int size = resultTargetUser.size(); 6728 for (int i = 0; i < size; i++) { 6729 ResolveInfo riTargetUser = resultTargetUser.get(i); 6730 // Intent filter verification is only for filters that specify a host. So don't return 6731 // those that handle all web uris. 6732 if (riTargetUser.handleAllWebDataURI) { 6733 continue; 6734 } 6735 String packageName = riTargetUser.activityInfo.packageName; 6736 PackageSetting ps = mSettings.mPackages.get(packageName); 6737 if (ps == null) { 6738 continue; 6739 } 6740 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6741 int status = (int)(verificationState >> 32); 6742 if (result == null) { 6743 result = new CrossProfileDomainInfo(); 6744 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6745 sourceUserId, parentUserId); 6746 result.bestDomainVerificationStatus = status; 6747 } else { 6748 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6749 result.bestDomainVerificationStatus); 6750 } 6751 } 6752 // Don't consider matches with status NEVER across profiles. 6753 if (result != null && result.bestDomainVerificationStatus 6754 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6755 return null; 6756 } 6757 return result; 6758 } 6759 6760 /** 6761 * Verification statuses are ordered from the worse to the best, except for 6762 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6763 */ 6764 private int bestDomainVerificationStatus(int status1, int status2) { 6765 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6766 return status2; 6767 } 6768 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6769 return status1; 6770 } 6771 return (int) MathUtils.max(status1, status2); 6772 } 6773 6774 private boolean isUserEnabled(int userId) { 6775 long callingId = Binder.clearCallingIdentity(); 6776 try { 6777 UserInfo userInfo = sUserManager.getUserInfo(userId); 6778 return userInfo != null && userInfo.isEnabled(); 6779 } finally { 6780 Binder.restoreCallingIdentity(callingId); 6781 } 6782 } 6783 6784 /** 6785 * Filter out activities with systemUserOnly flag set, when current user is not System. 6786 * 6787 * @return filtered list 6788 */ 6789 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6790 if (userId == UserHandle.USER_SYSTEM) { 6791 return resolveInfos; 6792 } 6793 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6794 ResolveInfo info = resolveInfos.get(i); 6795 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6796 resolveInfos.remove(i); 6797 } 6798 } 6799 return resolveInfos; 6800 } 6801 6802 /** 6803 * Filters out ephemeral activities. 6804 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6805 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6806 * 6807 * @param resolveInfos The pre-filtered list of resolved activities 6808 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6809 * is performed. 6810 * @return A filtered list of resolved activities. 6811 */ 6812 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6813 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) { 6814 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6815 final ResolveInfo info = resolveInfos.get(i); 6816 // allow activities that are defined in the provided package 6817 if (allowDynamicSplits 6818 && info.activityInfo != null 6819 && info.activityInfo.splitName != null 6820 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6821 info.activityInfo.splitName)) { 6822 if (mInstantAppInstallerActivity == null) { 6823 if (DEBUG_INSTALL) { 6824 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 6825 } 6826 resolveInfos.remove(i); 6827 continue; 6828 } 6829 // requested activity is defined in a split that hasn't been installed yet. 6830 // add the installer to the resolve list 6831 if (DEBUG_INSTALL) { 6832 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 6833 } 6834 final ResolveInfo installerInfo = new ResolveInfo( 6835 mInstantAppInstallerInfo); 6836 final ComponentName installFailureActivity = findInstallFailureActivity( 6837 info.activityInfo.packageName, filterCallingUid, userId); 6838 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6839 installFailureActivity, 6840 info.activityInfo.packageName, 6841 info.activityInfo.applicationInfo.versionCode, 6842 info.activityInfo.splitName); 6843 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6844 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6845 // add a non-generic filter 6846 installerInfo.filter = new IntentFilter(); 6847 6848 // This resolve info may appear in the chooser UI, so let us make it 6849 // look as the one it replaces as far as the user is concerned which 6850 // requires loading the correct label and icon for the resolve info. 6851 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6852 installerInfo.labelRes = info.resolveLabelResId(); 6853 installerInfo.icon = info.resolveIconResId(); 6854 6855 // propagate priority/preferred order/default 6856 installerInfo.priority = info.priority; 6857 installerInfo.preferredOrder = info.preferredOrder; 6858 installerInfo.isDefault = info.isDefault; 6859 installerInfo.isInstantAppAvailable = true; 6860 resolveInfos.set(i, installerInfo); 6861 continue; 6862 } 6863 // caller is a full app, don't need to apply any other filtering 6864 if (ephemeralPkgName == null) { 6865 continue; 6866 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 6867 // caller is same app; don't need to apply any other filtering 6868 continue; 6869 } 6870 // allow activities that have been explicitly exposed to ephemeral apps 6871 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6872 if (!isEphemeralApp 6873 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 6874 continue; 6875 } 6876 resolveInfos.remove(i); 6877 } 6878 return resolveInfos; 6879 } 6880 6881 /** 6882 * Returns the activity component that can handle install failures. 6883 * <p>By default, the instant application installer handles failures. However, an 6884 * application may want to handle failures on its own. Applications do this by 6885 * creating an activity with an intent filter that handles the action 6886 * {@link Intent#ACTION_INSTALL_FAILURE}. 6887 */ 6888 private @Nullable ComponentName findInstallFailureActivity( 6889 String packageName, int filterCallingUid, int userId) { 6890 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 6891 failureActivityIntent.setPackage(packageName); 6892 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 6893 final List<ResolveInfo> result = queryIntentActivitiesInternal( 6894 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId, 6895 false /*resolveForStart*/, false /*allowDynamicSplits*/); 6896 final int NR = result.size(); 6897 if (NR > 0) { 6898 for (int i = 0; i < NR; i++) { 6899 final ResolveInfo info = result.get(i); 6900 if (info.activityInfo.splitName != null) { 6901 continue; 6902 } 6903 return new ComponentName(packageName, info.activityInfo.name); 6904 } 6905 } 6906 return null; 6907 } 6908 6909 /** 6910 * @param resolveInfos list of resolve infos in descending priority order 6911 * @return if the list contains a resolve info with non-negative priority 6912 */ 6913 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6914 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6915 } 6916 6917 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6918 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6919 int userId) { 6920 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6921 6922 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6923 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6924 candidates.size()); 6925 } 6926 6927 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6928 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6929 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6930 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6931 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6932 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6933 6934 synchronized (mPackages) { 6935 final int count = candidates.size(); 6936 // First, try to use linked apps. Partition the candidates into four lists: 6937 // one for the final results, one for the "do not use ever", one for "undefined status" 6938 // and finally one for "browser app type". 6939 for (int n=0; n<count; n++) { 6940 ResolveInfo info = candidates.get(n); 6941 String packageName = info.activityInfo.packageName; 6942 PackageSetting ps = mSettings.mPackages.get(packageName); 6943 if (ps != null) { 6944 // Add to the special match all list (Browser use case) 6945 if (info.handleAllWebDataURI) { 6946 matchAllList.add(info); 6947 continue; 6948 } 6949 // Try to get the status from User settings first 6950 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6951 int status = (int)(packedStatus >> 32); 6952 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6953 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6954 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6955 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6956 + " : linkgen=" + linkGeneration); 6957 } 6958 // Use link-enabled generation as preferredOrder, i.e. 6959 // prefer newly-enabled over earlier-enabled. 6960 info.preferredOrder = linkGeneration; 6961 alwaysList.add(info); 6962 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6963 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6964 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6965 } 6966 neverList.add(info); 6967 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6968 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6969 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6970 } 6971 alwaysAskList.add(info); 6972 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6973 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6974 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6975 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6976 } 6977 undefinedList.add(info); 6978 } 6979 } 6980 } 6981 6982 // We'll want to include browser possibilities in a few cases 6983 boolean includeBrowser = false; 6984 6985 // First try to add the "always" resolution(s) for the current user, if any 6986 if (alwaysList.size() > 0) { 6987 result.addAll(alwaysList); 6988 } else { 6989 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6990 result.addAll(undefinedList); 6991 // Maybe add one for the other profile. 6992 if (xpDomainInfo != null && ( 6993 xpDomainInfo.bestDomainVerificationStatus 6994 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6995 result.add(xpDomainInfo.resolveInfo); 6996 } 6997 includeBrowser = true; 6998 } 6999 7000 // The presence of any 'always ask' alternatives means we'll also offer browsers. 7001 // If there were 'always' entries their preferred order has been set, so we also 7002 // back that off to make the alternatives equivalent 7003 if (alwaysAskList.size() > 0) { 7004 for (ResolveInfo i : result) { 7005 i.preferredOrder = 0; 7006 } 7007 result.addAll(alwaysAskList); 7008 includeBrowser = true; 7009 } 7010 7011 if (includeBrowser) { 7012 // Also add browsers (all of them or only the default one) 7013 if (DEBUG_DOMAIN_VERIFICATION) { 7014 Slog.v(TAG, " ...including browsers in candidate set"); 7015 } 7016 if ((matchFlags & MATCH_ALL) != 0) { 7017 result.addAll(matchAllList); 7018 } else { 7019 // Browser/generic handling case. If there's a default browser, go straight 7020 // to that (but only if there is no other higher-priority match). 7021 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 7022 int maxMatchPrio = 0; 7023 ResolveInfo defaultBrowserMatch = null; 7024 final int numCandidates = matchAllList.size(); 7025 for (int n = 0; n < numCandidates; n++) { 7026 ResolveInfo info = matchAllList.get(n); 7027 // track the highest overall match priority... 7028 if (info.priority > maxMatchPrio) { 7029 maxMatchPrio = info.priority; 7030 } 7031 // ...and the highest-priority default browser match 7032 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 7033 if (defaultBrowserMatch == null 7034 || (defaultBrowserMatch.priority < info.priority)) { 7035 if (debug) { 7036 Slog.v(TAG, "Considering default browser match " + info); 7037 } 7038 defaultBrowserMatch = info; 7039 } 7040 } 7041 } 7042 if (defaultBrowserMatch != null 7043 && defaultBrowserMatch.priority >= maxMatchPrio 7044 && !TextUtils.isEmpty(defaultBrowserPackageName)) 7045 { 7046 if (debug) { 7047 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 7048 } 7049 result.add(defaultBrowserMatch); 7050 } else { 7051 result.addAll(matchAllList); 7052 } 7053 } 7054 7055 // If there is nothing selected, add all candidates and remove the ones that the user 7056 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 7057 if (result.size() == 0) { 7058 result.addAll(candidates); 7059 result.removeAll(neverList); 7060 } 7061 } 7062 } 7063 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7064 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 7065 result.size()); 7066 for (ResolveInfo info : result) { 7067 Slog.v(TAG, " + " + info.activityInfo); 7068 } 7069 } 7070 return result; 7071 } 7072 7073 // Returns a packed value as a long: 7074 // 7075 // high 'int'-sized word: link status: undefined/ask/never/always. 7076 // low 'int'-sized word: relative priority among 'always' results. 7077 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 7078 long result = ps.getDomainVerificationStatusForUser(userId); 7079 // if none available, get the master status 7080 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 7081 if (ps.getIntentFilterVerificationInfo() != null) { 7082 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 7083 } 7084 } 7085 return result; 7086 } 7087 7088 private ResolveInfo querySkipCurrentProfileIntents( 7089 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7090 int flags, int sourceUserId) { 7091 if (matchingFilters != null) { 7092 int size = matchingFilters.size(); 7093 for (int i = 0; i < size; i ++) { 7094 CrossProfileIntentFilter filter = matchingFilters.get(i); 7095 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 7096 // Checking if there are activities in the target user that can handle the 7097 // intent. 7098 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7099 resolvedType, flags, sourceUserId); 7100 if (resolveInfo != null) { 7101 return resolveInfo; 7102 } 7103 } 7104 } 7105 } 7106 return null; 7107 } 7108 7109 // Return matching ResolveInfo in target user if any. 7110 private ResolveInfo queryCrossProfileIntents( 7111 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7112 int flags, int sourceUserId, boolean matchInCurrentProfile) { 7113 if (matchingFilters != null) { 7114 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 7115 // match the same intent. For performance reasons, it is better not to 7116 // run queryIntent twice for the same userId 7117 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 7118 int size = matchingFilters.size(); 7119 for (int i = 0; i < size; i++) { 7120 CrossProfileIntentFilter filter = matchingFilters.get(i); 7121 int targetUserId = filter.getTargetUserId(); 7122 boolean skipCurrentProfile = 7123 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 7124 boolean skipCurrentProfileIfNoMatchFound = 7125 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 7126 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 7127 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 7128 // Checking if there are activities in the target user that can handle the 7129 // intent. 7130 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7131 resolvedType, flags, sourceUserId); 7132 if (resolveInfo != null) return resolveInfo; 7133 alreadyTriedUserIds.put(targetUserId, true); 7134 } 7135 } 7136 } 7137 return null; 7138 } 7139 7140 /** 7141 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 7142 * will forward the intent to the filter's target user. 7143 * Otherwise, returns null. 7144 */ 7145 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 7146 String resolvedType, int flags, int sourceUserId) { 7147 int targetUserId = filter.getTargetUserId(); 7148 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7149 resolvedType, flags, targetUserId); 7150 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7151 // If all the matches in the target profile are suspended, return null. 7152 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7153 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7154 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7155 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7156 targetUserId); 7157 } 7158 } 7159 } 7160 return null; 7161 } 7162 7163 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7164 int sourceUserId, int targetUserId) { 7165 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7166 long ident = Binder.clearCallingIdentity(); 7167 boolean targetIsProfile; 7168 try { 7169 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7170 } finally { 7171 Binder.restoreCallingIdentity(ident); 7172 } 7173 String className; 7174 if (targetIsProfile) { 7175 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7176 } else { 7177 className = FORWARD_INTENT_TO_PARENT; 7178 } 7179 ComponentName forwardingActivityComponentName = new ComponentName( 7180 mAndroidApplication.packageName, className); 7181 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7182 sourceUserId); 7183 if (!targetIsProfile) { 7184 forwardingActivityInfo.showUserIcon = targetUserId; 7185 forwardingResolveInfo.noResourceId = true; 7186 } 7187 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7188 forwardingResolveInfo.priority = 0; 7189 forwardingResolveInfo.preferredOrder = 0; 7190 forwardingResolveInfo.match = 0; 7191 forwardingResolveInfo.isDefault = true; 7192 forwardingResolveInfo.filter = filter; 7193 forwardingResolveInfo.targetUserId = targetUserId; 7194 return forwardingResolveInfo; 7195 } 7196 7197 @Override 7198 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7199 Intent[] specifics, String[] specificTypes, Intent intent, 7200 String resolvedType, int flags, int userId) { 7201 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7202 specificTypes, intent, resolvedType, flags, userId)); 7203 } 7204 7205 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7206 Intent[] specifics, String[] specificTypes, Intent intent, 7207 String resolvedType, int flags, int userId) { 7208 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7209 final int callingUid = Binder.getCallingUid(); 7210 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7211 false /*includeInstantApps*/); 7212 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7213 false /*requireFullPermission*/, false /*checkShell*/, 7214 "query intent activity options"); 7215 final String resultsAction = intent.getAction(); 7216 7217 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7218 | PackageManager.GET_RESOLVED_FILTER, userId); 7219 7220 if (DEBUG_INTENT_MATCHING) { 7221 Log.v(TAG, "Query " + intent + ": " + results); 7222 } 7223 7224 int specificsPos = 0; 7225 int N; 7226 7227 // todo: note that the algorithm used here is O(N^2). This 7228 // isn't a problem in our current environment, but if we start running 7229 // into situations where we have more than 5 or 10 matches then this 7230 // should probably be changed to something smarter... 7231 7232 // First we go through and resolve each of the specific items 7233 // that were supplied, taking care of removing any corresponding 7234 // duplicate items in the generic resolve list. 7235 if (specifics != null) { 7236 for (int i=0; i<specifics.length; i++) { 7237 final Intent sintent = specifics[i]; 7238 if (sintent == null) { 7239 continue; 7240 } 7241 7242 if (DEBUG_INTENT_MATCHING) { 7243 Log.v(TAG, "Specific #" + i + ": " + sintent); 7244 } 7245 7246 String action = sintent.getAction(); 7247 if (resultsAction != null && resultsAction.equals(action)) { 7248 // If this action was explicitly requested, then don't 7249 // remove things that have it. 7250 action = null; 7251 } 7252 7253 ResolveInfo ri = null; 7254 ActivityInfo ai = null; 7255 7256 ComponentName comp = sintent.getComponent(); 7257 if (comp == null) { 7258 ri = resolveIntent( 7259 sintent, 7260 specificTypes != null ? specificTypes[i] : null, 7261 flags, userId); 7262 if (ri == null) { 7263 continue; 7264 } 7265 if (ri == mResolveInfo) { 7266 // ACK! Must do something better with this. 7267 } 7268 ai = ri.activityInfo; 7269 comp = new ComponentName(ai.applicationInfo.packageName, 7270 ai.name); 7271 } else { 7272 ai = getActivityInfo(comp, flags, userId); 7273 if (ai == null) { 7274 continue; 7275 } 7276 } 7277 7278 // Look for any generic query activities that are duplicates 7279 // of this specific one, and remove them from the results. 7280 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7281 N = results.size(); 7282 int j; 7283 for (j=specificsPos; j<N; j++) { 7284 ResolveInfo sri = results.get(j); 7285 if ((sri.activityInfo.name.equals(comp.getClassName()) 7286 && sri.activityInfo.applicationInfo.packageName.equals( 7287 comp.getPackageName())) 7288 || (action != null && sri.filter.matchAction(action))) { 7289 results.remove(j); 7290 if (DEBUG_INTENT_MATCHING) Log.v( 7291 TAG, "Removing duplicate item from " + j 7292 + " due to specific " + specificsPos); 7293 if (ri == null) { 7294 ri = sri; 7295 } 7296 j--; 7297 N--; 7298 } 7299 } 7300 7301 // Add this specific item to its proper place. 7302 if (ri == null) { 7303 ri = new ResolveInfo(); 7304 ri.activityInfo = ai; 7305 } 7306 results.add(specificsPos, ri); 7307 ri.specificIndex = i; 7308 specificsPos++; 7309 } 7310 } 7311 7312 // Now we go through the remaining generic results and remove any 7313 // duplicate actions that are found here. 7314 N = results.size(); 7315 for (int i=specificsPos; i<N-1; i++) { 7316 final ResolveInfo rii = results.get(i); 7317 if (rii.filter == null) { 7318 continue; 7319 } 7320 7321 // Iterate over all of the actions of this result's intent 7322 // filter... typically this should be just one. 7323 final Iterator<String> it = rii.filter.actionsIterator(); 7324 if (it == null) { 7325 continue; 7326 } 7327 while (it.hasNext()) { 7328 final String action = it.next(); 7329 if (resultsAction != null && resultsAction.equals(action)) { 7330 // If this action was explicitly requested, then don't 7331 // remove things that have it. 7332 continue; 7333 } 7334 for (int j=i+1; j<N; j++) { 7335 final ResolveInfo rij = results.get(j); 7336 if (rij.filter != null && rij.filter.hasAction(action)) { 7337 results.remove(j); 7338 if (DEBUG_INTENT_MATCHING) Log.v( 7339 TAG, "Removing duplicate item from " + j 7340 + " due to action " + action + " at " + i); 7341 j--; 7342 N--; 7343 } 7344 } 7345 } 7346 7347 // If the caller didn't request filter information, drop it now 7348 // so we don't have to marshall/unmarshall it. 7349 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7350 rii.filter = null; 7351 } 7352 } 7353 7354 // Filter out the caller activity if so requested. 7355 if (caller != null) { 7356 N = results.size(); 7357 for (int i=0; i<N; i++) { 7358 ActivityInfo ainfo = results.get(i).activityInfo; 7359 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7360 && caller.getClassName().equals(ainfo.name)) { 7361 results.remove(i); 7362 break; 7363 } 7364 } 7365 } 7366 7367 // If the caller didn't request filter information, 7368 // drop them now so we don't have to 7369 // marshall/unmarshall it. 7370 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7371 N = results.size(); 7372 for (int i=0; i<N; i++) { 7373 results.get(i).filter = null; 7374 } 7375 } 7376 7377 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7378 return results; 7379 } 7380 7381 @Override 7382 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7383 String resolvedType, int flags, int userId) { 7384 return new ParceledListSlice<>( 7385 queryIntentReceiversInternal(intent, resolvedType, flags, userId, 7386 false /*allowDynamicSplits*/)); 7387 } 7388 7389 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7390 String resolvedType, int flags, int userId, boolean allowDynamicSplits) { 7391 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7392 final int callingUid = Binder.getCallingUid(); 7393 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7394 false /*requireFullPermission*/, false /*checkShell*/, 7395 "query intent receivers"); 7396 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7397 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7398 false /*includeInstantApps*/); 7399 ComponentName comp = intent.getComponent(); 7400 if (comp == null) { 7401 if (intent.getSelector() != null) { 7402 intent = intent.getSelector(); 7403 comp = intent.getComponent(); 7404 } 7405 } 7406 if (comp != null) { 7407 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7408 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7409 if (ai != null) { 7410 // When specifying an explicit component, we prevent the activity from being 7411 // used when either 1) the calling package is normal and the activity is within 7412 // an instant application or 2) the calling package is ephemeral and the 7413 // activity is not visible to instant applications. 7414 final boolean matchInstantApp = 7415 (flags & PackageManager.MATCH_INSTANT) != 0; 7416 final boolean matchVisibleToInstantAppOnly = 7417 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7418 final boolean matchExplicitlyVisibleOnly = 7419 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7420 final boolean isCallerInstantApp = 7421 instantAppPkgName != null; 7422 final boolean isTargetSameInstantApp = 7423 comp.getPackageName().equals(instantAppPkgName); 7424 final boolean isTargetInstantApp = 7425 (ai.applicationInfo.privateFlags 7426 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7427 final boolean isTargetVisibleToInstantApp = 7428 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7429 final boolean isTargetExplicitlyVisibleToInstantApp = 7430 isTargetVisibleToInstantApp 7431 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7432 final boolean isTargetHiddenFromInstantApp = 7433 !isTargetVisibleToInstantApp 7434 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7435 final boolean blockResolution = 7436 !isTargetSameInstantApp 7437 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7438 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7439 && isTargetHiddenFromInstantApp)); 7440 if (!blockResolution) { 7441 ResolveInfo ri = new ResolveInfo(); 7442 ri.activityInfo = ai; 7443 list.add(ri); 7444 } 7445 } 7446 return applyPostResolutionFilter( 7447 list, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7448 } 7449 7450 // reader 7451 synchronized (mPackages) { 7452 String pkgName = intent.getPackage(); 7453 if (pkgName == null) { 7454 final List<ResolveInfo> result = 7455 mReceivers.queryIntent(intent, resolvedType, flags, userId); 7456 return applyPostResolutionFilter( 7457 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7458 } 7459 final PackageParser.Package pkg = mPackages.get(pkgName); 7460 if (pkg != null) { 7461 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 7462 intent, resolvedType, flags, pkg.receivers, userId); 7463 return applyPostResolutionFilter( 7464 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7465 } 7466 return Collections.emptyList(); 7467 } 7468 } 7469 7470 @Override 7471 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7472 final int callingUid = Binder.getCallingUid(); 7473 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7474 } 7475 7476 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7477 int userId, int callingUid) { 7478 if (!sUserManager.exists(userId)) return null; 7479 flags = updateFlagsForResolve( 7480 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7481 List<ResolveInfo> query = queryIntentServicesInternal( 7482 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7483 if (query != null) { 7484 if (query.size() >= 1) { 7485 // If there is more than one service with the same priority, 7486 // just arbitrarily pick the first one. 7487 return query.get(0); 7488 } 7489 } 7490 return null; 7491 } 7492 7493 @Override 7494 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7495 String resolvedType, int flags, int userId) { 7496 final int callingUid = Binder.getCallingUid(); 7497 return new ParceledListSlice<>(queryIntentServicesInternal( 7498 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7499 } 7500 7501 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7502 String resolvedType, int flags, int userId, int callingUid, 7503 boolean includeInstantApps) { 7504 if (!sUserManager.exists(userId)) return Collections.emptyList(); 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, includeInstantApps); 7510 ComponentName comp = intent.getComponent(); 7511 if (comp == null) { 7512 if (intent.getSelector() != null) { 7513 intent = intent.getSelector(); 7514 comp = intent.getComponent(); 7515 } 7516 } 7517 if (comp != null) { 7518 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7519 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7520 if (si != null) { 7521 // When specifying an explicit component, we prevent the service from being 7522 // used when either 1) the service is in an instant application and the 7523 // caller is not the same instant application or 2) the calling package is 7524 // ephemeral and the activity is not visible to ephemeral applications. 7525 final boolean matchInstantApp = 7526 (flags & PackageManager.MATCH_INSTANT) != 0; 7527 final boolean matchVisibleToInstantAppOnly = 7528 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7529 final boolean isCallerInstantApp = 7530 instantAppPkgName != null; 7531 final boolean isTargetSameInstantApp = 7532 comp.getPackageName().equals(instantAppPkgName); 7533 final boolean isTargetInstantApp = 7534 (si.applicationInfo.privateFlags 7535 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7536 final boolean isTargetHiddenFromInstantApp = 7537 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7538 final boolean blockResolution = 7539 !isTargetSameInstantApp 7540 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7541 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7542 && isTargetHiddenFromInstantApp)); 7543 if (!blockResolution) { 7544 final ResolveInfo ri = new ResolveInfo(); 7545 ri.serviceInfo = si; 7546 list.add(ri); 7547 } 7548 } 7549 return list; 7550 } 7551 7552 // reader 7553 synchronized (mPackages) { 7554 String pkgName = intent.getPackage(); 7555 if (pkgName == null) { 7556 return applyPostServiceResolutionFilter( 7557 mServices.queryIntent(intent, resolvedType, flags, userId), 7558 instantAppPkgName); 7559 } 7560 final PackageParser.Package pkg = mPackages.get(pkgName); 7561 if (pkg != null) { 7562 return applyPostServiceResolutionFilter( 7563 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7564 userId), 7565 instantAppPkgName); 7566 } 7567 return Collections.emptyList(); 7568 } 7569 } 7570 7571 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7572 String instantAppPkgName) { 7573 if (instantAppPkgName == null) { 7574 return resolveInfos; 7575 } 7576 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7577 final ResolveInfo info = resolveInfos.get(i); 7578 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7579 // allow services that are defined in the provided package 7580 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7581 if (info.serviceInfo.splitName != null 7582 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7583 info.serviceInfo.splitName)) { 7584 // requested service is defined in a split that hasn't been installed yet. 7585 // add the installer to the resolve list 7586 if (DEBUG_INSTANT) { 7587 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7588 } 7589 final ResolveInfo installerInfo = new ResolveInfo( 7590 mInstantAppInstallerInfo); 7591 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7592 null /* installFailureActivity */, 7593 info.serviceInfo.packageName, 7594 info.serviceInfo.applicationInfo.versionCode, 7595 info.serviceInfo.splitName); 7596 // make sure this resolver is the default 7597 installerInfo.isDefault = true; 7598 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7599 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7600 // add a non-generic filter 7601 installerInfo.filter = new IntentFilter(); 7602 // load resources from the correct package 7603 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7604 resolveInfos.set(i, installerInfo); 7605 } 7606 continue; 7607 } 7608 // allow services that have been explicitly exposed to ephemeral apps 7609 if (!isEphemeralApp 7610 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7611 continue; 7612 } 7613 resolveInfos.remove(i); 7614 } 7615 return resolveInfos; 7616 } 7617 7618 @Override 7619 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7620 String resolvedType, int flags, int userId) { 7621 return new ParceledListSlice<>( 7622 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7623 } 7624 7625 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7626 Intent intent, String resolvedType, int flags, int userId) { 7627 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7628 final int callingUid = Binder.getCallingUid(); 7629 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7630 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7631 false /*includeInstantApps*/); 7632 ComponentName comp = intent.getComponent(); 7633 if (comp == null) { 7634 if (intent.getSelector() != null) { 7635 intent = intent.getSelector(); 7636 comp = intent.getComponent(); 7637 } 7638 } 7639 if (comp != null) { 7640 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7641 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7642 if (pi != null) { 7643 // When specifying an explicit component, we prevent the provider from being 7644 // used when either 1) the provider is in an instant application and the 7645 // caller is not the same instant application or 2) the calling package is an 7646 // instant application and the provider is not visible to instant applications. 7647 final boolean matchInstantApp = 7648 (flags & PackageManager.MATCH_INSTANT) != 0; 7649 final boolean matchVisibleToInstantAppOnly = 7650 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7651 final boolean isCallerInstantApp = 7652 instantAppPkgName != null; 7653 final boolean isTargetSameInstantApp = 7654 comp.getPackageName().equals(instantAppPkgName); 7655 final boolean isTargetInstantApp = 7656 (pi.applicationInfo.privateFlags 7657 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7658 final boolean isTargetHiddenFromInstantApp = 7659 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7660 final boolean blockResolution = 7661 !isTargetSameInstantApp 7662 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7663 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7664 && isTargetHiddenFromInstantApp)); 7665 if (!blockResolution) { 7666 final ResolveInfo ri = new ResolveInfo(); 7667 ri.providerInfo = pi; 7668 list.add(ri); 7669 } 7670 } 7671 return list; 7672 } 7673 7674 // reader 7675 synchronized (mPackages) { 7676 String pkgName = intent.getPackage(); 7677 if (pkgName == null) { 7678 return applyPostContentProviderResolutionFilter( 7679 mProviders.queryIntent(intent, resolvedType, flags, userId), 7680 instantAppPkgName); 7681 } 7682 final PackageParser.Package pkg = mPackages.get(pkgName); 7683 if (pkg != null) { 7684 return applyPostContentProviderResolutionFilter( 7685 mProviders.queryIntentForPackage( 7686 intent, resolvedType, flags, pkg.providers, userId), 7687 instantAppPkgName); 7688 } 7689 return Collections.emptyList(); 7690 } 7691 } 7692 7693 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7694 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7695 if (instantAppPkgName == null) { 7696 return resolveInfos; 7697 } 7698 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7699 final ResolveInfo info = resolveInfos.get(i); 7700 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7701 // allow providers that are defined in the provided package 7702 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7703 if (info.providerInfo.splitName != null 7704 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7705 info.providerInfo.splitName)) { 7706 // requested provider is defined in a split that hasn't been installed yet. 7707 // add the installer to the resolve list 7708 if (DEBUG_INSTANT) { 7709 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7710 } 7711 final ResolveInfo installerInfo = new ResolveInfo( 7712 mInstantAppInstallerInfo); 7713 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7714 null /*failureActivity*/, 7715 info.providerInfo.packageName, 7716 info.providerInfo.applicationInfo.versionCode, 7717 info.providerInfo.splitName); 7718 // make sure this resolver is the default 7719 installerInfo.isDefault = true; 7720 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7721 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7722 // add a non-generic filter 7723 installerInfo.filter = new IntentFilter(); 7724 // load resources from the correct package 7725 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7726 resolveInfos.set(i, installerInfo); 7727 } 7728 continue; 7729 } 7730 // allow providers that have been explicitly exposed to instant applications 7731 if (!isEphemeralApp 7732 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7733 continue; 7734 } 7735 resolveInfos.remove(i); 7736 } 7737 return resolveInfos; 7738 } 7739 7740 @Override 7741 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7742 final int callingUid = Binder.getCallingUid(); 7743 if (getInstantAppPackageName(callingUid) != null) { 7744 return ParceledListSlice.emptyList(); 7745 } 7746 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7747 flags = updateFlagsForPackage(flags, userId, null); 7748 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7749 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7750 true /* requireFullPermission */, false /* checkShell */, 7751 "get installed packages"); 7752 7753 // writer 7754 synchronized (mPackages) { 7755 ArrayList<PackageInfo> list; 7756 if (listUninstalled) { 7757 list = new ArrayList<>(mSettings.mPackages.size()); 7758 for (PackageSetting ps : mSettings.mPackages.values()) { 7759 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7760 continue; 7761 } 7762 if (filterAppAccessLPr(ps, callingUid, userId)) { 7763 continue; 7764 } 7765 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7766 if (pi != null) { 7767 list.add(pi); 7768 } 7769 } 7770 } else { 7771 list = new ArrayList<>(mPackages.size()); 7772 for (PackageParser.Package p : mPackages.values()) { 7773 final PackageSetting ps = (PackageSetting) p.mExtras; 7774 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7775 continue; 7776 } 7777 if (filterAppAccessLPr(ps, callingUid, userId)) { 7778 continue; 7779 } 7780 final PackageInfo pi = generatePackageInfo((PackageSetting) 7781 p.mExtras, flags, userId); 7782 if (pi != null) { 7783 list.add(pi); 7784 } 7785 } 7786 } 7787 7788 return new ParceledListSlice<>(list); 7789 } 7790 } 7791 7792 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7793 String[] permissions, boolean[] tmp, int flags, int userId) { 7794 int numMatch = 0; 7795 final PermissionsState permissionsState = ps.getPermissionsState(); 7796 for (int i=0; i<permissions.length; i++) { 7797 final String permission = permissions[i]; 7798 if (permissionsState.hasPermission(permission, userId)) { 7799 tmp[i] = true; 7800 numMatch++; 7801 } else { 7802 tmp[i] = false; 7803 } 7804 } 7805 if (numMatch == 0) { 7806 return; 7807 } 7808 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7809 7810 // The above might return null in cases of uninstalled apps or install-state 7811 // skew across users/profiles. 7812 if (pi != null) { 7813 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7814 if (numMatch == permissions.length) { 7815 pi.requestedPermissions = permissions; 7816 } else { 7817 pi.requestedPermissions = new String[numMatch]; 7818 numMatch = 0; 7819 for (int i=0; i<permissions.length; i++) { 7820 if (tmp[i]) { 7821 pi.requestedPermissions[numMatch] = permissions[i]; 7822 numMatch++; 7823 } 7824 } 7825 } 7826 } 7827 list.add(pi); 7828 } 7829 } 7830 7831 @Override 7832 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7833 String[] permissions, int flags, int userId) { 7834 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7835 flags = updateFlagsForPackage(flags, userId, permissions); 7836 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7837 true /* requireFullPermission */, false /* checkShell */, 7838 "get packages holding permissions"); 7839 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7840 7841 // writer 7842 synchronized (mPackages) { 7843 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7844 boolean[] tmpBools = new boolean[permissions.length]; 7845 if (listUninstalled) { 7846 for (PackageSetting ps : mSettings.mPackages.values()) { 7847 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7848 userId); 7849 } 7850 } else { 7851 for (PackageParser.Package pkg : mPackages.values()) { 7852 PackageSetting ps = (PackageSetting)pkg.mExtras; 7853 if (ps != null) { 7854 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7855 userId); 7856 } 7857 } 7858 } 7859 7860 return new ParceledListSlice<PackageInfo>(list); 7861 } 7862 } 7863 7864 @Override 7865 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7866 final int callingUid = Binder.getCallingUid(); 7867 if (getInstantAppPackageName(callingUid) != null) { 7868 return ParceledListSlice.emptyList(); 7869 } 7870 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7871 flags = updateFlagsForApplication(flags, userId, null); 7872 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7873 7874 // writer 7875 synchronized (mPackages) { 7876 ArrayList<ApplicationInfo> list; 7877 if (listUninstalled) { 7878 list = new ArrayList<>(mSettings.mPackages.size()); 7879 for (PackageSetting ps : mSettings.mPackages.values()) { 7880 ApplicationInfo ai; 7881 int effectiveFlags = flags; 7882 if (ps.isSystem()) { 7883 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7884 } 7885 if (ps.pkg != null) { 7886 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7887 continue; 7888 } 7889 if (filterAppAccessLPr(ps, callingUid, userId)) { 7890 continue; 7891 } 7892 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7893 ps.readUserState(userId), userId); 7894 if (ai != null) { 7895 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7896 } 7897 } else { 7898 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7899 // and already converts to externally visible package name 7900 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7901 callingUid, effectiveFlags, userId); 7902 } 7903 if (ai != null) { 7904 list.add(ai); 7905 } 7906 } 7907 } else { 7908 list = new ArrayList<>(mPackages.size()); 7909 for (PackageParser.Package p : mPackages.values()) { 7910 if (p.mExtras != null) { 7911 PackageSetting ps = (PackageSetting) p.mExtras; 7912 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 7913 continue; 7914 } 7915 if (filterAppAccessLPr(ps, callingUid, userId)) { 7916 continue; 7917 } 7918 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7919 ps.readUserState(userId), userId); 7920 if (ai != null) { 7921 ai.packageName = resolveExternalPackageNameLPr(p); 7922 list.add(ai); 7923 } 7924 } 7925 } 7926 } 7927 7928 return new ParceledListSlice<>(list); 7929 } 7930 } 7931 7932 @Override 7933 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7934 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7935 return null; 7936 } 7937 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 7938 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7939 "getEphemeralApplications"); 7940 } 7941 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7942 true /* requireFullPermission */, false /* checkShell */, 7943 "getEphemeralApplications"); 7944 synchronized (mPackages) { 7945 List<InstantAppInfo> instantApps = mInstantAppRegistry 7946 .getInstantAppsLPr(userId); 7947 if (instantApps != null) { 7948 return new ParceledListSlice<>(instantApps); 7949 } 7950 } 7951 return null; 7952 } 7953 7954 @Override 7955 public boolean isInstantApp(String packageName, int userId) { 7956 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7957 true /* requireFullPermission */, false /* checkShell */, 7958 "isInstantApp"); 7959 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7960 return false; 7961 } 7962 7963 synchronized (mPackages) { 7964 int callingUid = Binder.getCallingUid(); 7965 if (Process.isIsolated(callingUid)) { 7966 callingUid = mIsolatedOwners.get(callingUid); 7967 } 7968 final PackageSetting ps = mSettings.mPackages.get(packageName); 7969 PackageParser.Package pkg = mPackages.get(packageName); 7970 final boolean returnAllowed = 7971 ps != null 7972 && (isCallerSameApp(packageName, callingUid) 7973 || canViewInstantApps(callingUid, userId) 7974 || mInstantAppRegistry.isInstantAccessGranted( 7975 userId, UserHandle.getAppId(callingUid), ps.appId)); 7976 if (returnAllowed) { 7977 return ps.getInstantApp(userId); 7978 } 7979 } 7980 return false; 7981 } 7982 7983 @Override 7984 public byte[] getInstantAppCookie(String packageName, int userId) { 7985 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7986 return null; 7987 } 7988 7989 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7990 true /* requireFullPermission */, false /* checkShell */, 7991 "getInstantAppCookie"); 7992 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7993 return null; 7994 } 7995 synchronized (mPackages) { 7996 return mInstantAppRegistry.getInstantAppCookieLPw( 7997 packageName, userId); 7998 } 7999 } 8000 8001 @Override 8002 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 8003 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8004 return true; 8005 } 8006 8007 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8008 true /* requireFullPermission */, true /* checkShell */, 8009 "setInstantAppCookie"); 8010 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8011 return false; 8012 } 8013 synchronized (mPackages) { 8014 return mInstantAppRegistry.setInstantAppCookieLPw( 8015 packageName, cookie, userId); 8016 } 8017 } 8018 8019 @Override 8020 public Bitmap getInstantAppIcon(String packageName, int userId) { 8021 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8022 return null; 8023 } 8024 8025 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8026 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8027 "getInstantAppIcon"); 8028 } 8029 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8030 true /* requireFullPermission */, false /* checkShell */, 8031 "getInstantAppIcon"); 8032 8033 synchronized (mPackages) { 8034 return mInstantAppRegistry.getInstantAppIconLPw( 8035 packageName, userId); 8036 } 8037 } 8038 8039 private boolean isCallerSameApp(String packageName, int uid) { 8040 PackageParser.Package pkg = mPackages.get(packageName); 8041 return pkg != null 8042 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 8043 } 8044 8045 @Override 8046 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 8047 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8048 return ParceledListSlice.emptyList(); 8049 } 8050 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 8051 } 8052 8053 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 8054 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 8055 8056 // reader 8057 synchronized (mPackages) { 8058 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 8059 final int userId = UserHandle.getCallingUserId(); 8060 while (i.hasNext()) { 8061 final PackageParser.Package p = i.next(); 8062 if (p.applicationInfo == null) continue; 8063 8064 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 8065 && !p.applicationInfo.isDirectBootAware(); 8066 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 8067 && p.applicationInfo.isDirectBootAware(); 8068 8069 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 8070 && (!mSafeMode || isSystemApp(p)) 8071 && (matchesUnaware || matchesAware)) { 8072 PackageSetting ps = mSettings.mPackages.get(p.packageName); 8073 if (ps != null) { 8074 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8075 ps.readUserState(userId), userId); 8076 if (ai != null) { 8077 finalList.add(ai); 8078 } 8079 } 8080 } 8081 } 8082 } 8083 8084 return finalList; 8085 } 8086 8087 @Override 8088 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 8089 return resolveContentProviderInternal(name, flags, userId); 8090 } 8091 8092 private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) { 8093 if (!sUserManager.exists(userId)) return null; 8094 flags = updateFlagsForComponent(flags, userId, name); 8095 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 8096 // reader 8097 synchronized (mPackages) { 8098 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 8099 PackageSetting ps = provider != null 8100 ? mSettings.mPackages.get(provider.owner.packageName) 8101 : null; 8102 if (ps != null) { 8103 final boolean isInstantApp = ps.getInstantApp(userId); 8104 // normal application; filter out instant application provider 8105 if (instantAppPkgName == null && isInstantApp) { 8106 return null; 8107 } 8108 // instant application; filter out other instant applications 8109 if (instantAppPkgName != null 8110 && isInstantApp 8111 && !provider.owner.packageName.equals(instantAppPkgName)) { 8112 return null; 8113 } 8114 // instant application; filter out non-exposed provider 8115 if (instantAppPkgName != null 8116 && !isInstantApp 8117 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 8118 return null; 8119 } 8120 // provider not enabled 8121 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 8122 return null; 8123 } 8124 return PackageParser.generateProviderInfo( 8125 provider, flags, ps.readUserState(userId), userId); 8126 } 8127 return null; 8128 } 8129 } 8130 8131 /** 8132 * @deprecated 8133 */ 8134 @Deprecated 8135 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 8136 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8137 return; 8138 } 8139 // reader 8140 synchronized (mPackages) { 8141 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 8142 .entrySet().iterator(); 8143 final int userId = UserHandle.getCallingUserId(); 8144 while (i.hasNext()) { 8145 Map.Entry<String, PackageParser.Provider> entry = i.next(); 8146 PackageParser.Provider p = entry.getValue(); 8147 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8148 8149 if (ps != null && p.syncable 8150 && (!mSafeMode || (p.info.applicationInfo.flags 8151 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 8152 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 8153 ps.readUserState(userId), userId); 8154 if (info != null) { 8155 outNames.add(entry.getKey()); 8156 outInfo.add(info); 8157 } 8158 } 8159 } 8160 } 8161 } 8162 8163 @Override 8164 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8165 int uid, int flags, String metaDataKey) { 8166 final int callingUid = Binder.getCallingUid(); 8167 final int userId = processName != null ? UserHandle.getUserId(uid) 8168 : UserHandle.getCallingUserId(); 8169 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8170 flags = updateFlagsForComponent(flags, userId, processName); 8171 ArrayList<ProviderInfo> finalList = null; 8172 // reader 8173 synchronized (mPackages) { 8174 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 8175 while (i.hasNext()) { 8176 final PackageParser.Provider p = i.next(); 8177 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8178 if (ps != null && p.info.authority != null 8179 && (processName == null 8180 || (p.info.processName.equals(processName) 8181 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 8182 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 8183 8184 // See PM.queryContentProviders()'s javadoc for why we have the metaData 8185 // parameter. 8186 if (metaDataKey != null 8187 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 8188 continue; 8189 } 8190 final ComponentName component = 8191 new ComponentName(p.info.packageName, p.info.name); 8192 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8193 continue; 8194 } 8195 if (finalList == null) { 8196 finalList = new ArrayList<ProviderInfo>(3); 8197 } 8198 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8199 ps.readUserState(userId), userId); 8200 if (info != null) { 8201 finalList.add(info); 8202 } 8203 } 8204 } 8205 } 8206 8207 if (finalList != null) { 8208 Collections.sort(finalList, mProviderInitOrderSorter); 8209 return new ParceledListSlice<ProviderInfo>(finalList); 8210 } 8211 8212 return ParceledListSlice.emptyList(); 8213 } 8214 8215 @Override 8216 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8217 // reader 8218 synchronized (mPackages) { 8219 final int callingUid = Binder.getCallingUid(); 8220 final int callingUserId = UserHandle.getUserId(callingUid); 8221 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8222 if (ps == null) return null; 8223 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8224 return null; 8225 } 8226 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8227 return PackageParser.generateInstrumentationInfo(i, flags); 8228 } 8229 } 8230 8231 @Override 8232 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8233 String targetPackage, int flags) { 8234 final int callingUid = Binder.getCallingUid(); 8235 final int callingUserId = UserHandle.getUserId(callingUid); 8236 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8237 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8238 return ParceledListSlice.emptyList(); 8239 } 8240 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8241 } 8242 8243 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8244 int flags) { 8245 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 8246 8247 // reader 8248 synchronized (mPackages) { 8249 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8250 while (i.hasNext()) { 8251 final PackageParser.Instrumentation p = i.next(); 8252 if (targetPackage == null 8253 || targetPackage.equals(p.info.targetPackage)) { 8254 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8255 flags); 8256 if (ii != null) { 8257 finalList.add(ii); 8258 } 8259 } 8260 } 8261 } 8262 8263 return finalList; 8264 } 8265 8266 private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) { 8267 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]"); 8268 try { 8269 scanDirLI(scanDir, parseFlags, scanFlags, currentTime); 8270 } finally { 8271 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8272 } 8273 } 8274 8275 private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) { 8276 final File[] files = scanDir.listFiles(); 8277 if (ArrayUtils.isEmpty(files)) { 8278 Log.d(TAG, "No files in app dir " + scanDir); 8279 return; 8280 } 8281 8282 if (DEBUG_PACKAGE_SCANNING) { 8283 Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags 8284 + " flags=0x" + Integer.toHexString(parseFlags)); 8285 } 8286 try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8287 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8288 mParallelPackageParserCallback)) { 8289 // Submit files for parsing in parallel 8290 int fileCount = 0; 8291 for (File file : files) { 8292 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8293 && !PackageInstallerService.isStageName(file.getName()); 8294 if (!isPackage) { 8295 // Ignore entries which are not packages 8296 continue; 8297 } 8298 parallelPackageParser.submit(file, parseFlags); 8299 fileCount++; 8300 } 8301 8302 // Process results one by one 8303 for (; fileCount > 0; fileCount--) { 8304 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8305 Throwable throwable = parseResult.throwable; 8306 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8307 8308 if (throwable == null) { 8309 // TODO(toddke): move lower in the scan chain 8310 // Static shared libraries have synthetic package names 8311 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8312 renameStaticSharedLibraryPackage(parseResult.pkg); 8313 } 8314 try { 8315 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8316 scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags, 8317 currentTime, null); 8318 } 8319 } catch (PackageManagerException e) { 8320 errorCode = e.error; 8321 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8322 } 8323 } else if (throwable instanceof PackageParser.PackageParserException) { 8324 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8325 throwable; 8326 errorCode = e.error; 8327 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8328 } else { 8329 throw new IllegalStateException("Unexpected exception occurred while parsing " 8330 + parseResult.scanFile, throwable); 8331 } 8332 8333 // Delete invalid userdata apps 8334 if ((scanFlags & SCAN_AS_SYSTEM) == 0 && 8335 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8336 logCriticalInfo(Log.WARN, 8337 "Deleting invalid package at " + parseResult.scanFile); 8338 removeCodePathLI(parseResult.scanFile); 8339 } 8340 } 8341 } 8342 } 8343 8344 public static void reportSettingsProblem(int priority, String msg) { 8345 logCriticalInfo(priority, msg); 8346 } 8347 8348 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, 8349 boolean forceCollect) throws PackageManagerException { 8350 // When upgrading from pre-N MR1, verify the package time stamp using the package 8351 // directory and not the APK file. 8352 final long lastModifiedTime = mIsPreNMR1Upgrade 8353 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg); 8354 // Note that currently skipVerify skips verification on both base and splits for simplicity. 8355 final boolean skipVerify = forceCollect && canSkipFullPackageVerification(pkg); 8356 if (ps != null && !forceCollect 8357 && ps.codePathString.equals(pkg.codePath) 8358 && ps.timeStamp == lastModifiedTime 8359 && !isCompatSignatureUpdateNeeded(pkg) 8360 && !isRecoverSignatureUpdateNeeded(pkg)) { 8361 if (ps.signatures.mSigningDetails.signatures != null 8362 && ps.signatures.mSigningDetails.signatures.length != 0 8363 && ps.signatures.mSigningDetails.signatureSchemeVersion 8364 != SignatureSchemeVersion.UNKNOWN) { 8365 // Optimization: reuse the existing cached signing data 8366 // if the package appears to be unchanged. 8367 pkg.mSigningDetails = 8368 new PackageParser.SigningDetails(ps.signatures.mSigningDetails); 8369 return; 8370 } 8371 8372 Slog.w(TAG, "PackageSetting for " + ps.name 8373 + " is missing signatures. Collecting certs again to recover them."); 8374 } else { 8375 Slog.i(TAG, pkg.codePath + " changed; collecting certs" + 8376 (forceCollect ? " (forced)" : "")); 8377 } 8378 8379 try { 8380 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8381 PackageParser.collectCertificates(pkg, skipVerify); 8382 } catch (PackageParserException e) { 8383 throw PackageManagerException.from(e); 8384 } finally { 8385 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8386 } 8387 } 8388 8389 /** 8390 * Traces a package scan. 8391 * @see #scanPackageLI(File, int, int, long, UserHandle) 8392 */ 8393 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8394 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8395 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8396 try { 8397 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8398 } finally { 8399 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8400 } 8401 } 8402 8403 /** 8404 * Scans a package and returns the newly parsed package. 8405 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8406 */ 8407 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8408 long currentTime, UserHandle user) throws PackageManagerException { 8409 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8410 PackageParser pp = new PackageParser(); 8411 pp.setSeparateProcesses(mSeparateProcesses); 8412 pp.setOnlyCoreApps(mOnlyCore); 8413 pp.setDisplayMetrics(mMetrics); 8414 pp.setCallback(mPackageParserCallback); 8415 8416 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8417 final PackageParser.Package pkg; 8418 try { 8419 pkg = pp.parsePackage(scanFile, parseFlags); 8420 } catch (PackageParserException e) { 8421 throw PackageManagerException.from(e); 8422 } finally { 8423 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8424 } 8425 8426 // Static shared libraries have synthetic package names 8427 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8428 renameStaticSharedLibraryPackage(pkg); 8429 } 8430 8431 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8432 } 8433 8434 /** 8435 * Scans a package and returns the newly parsed package. 8436 * @throws PackageManagerException on a parse error. 8437 */ 8438 private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg, 8439 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8440 @Nullable UserHandle user) 8441 throws PackageManagerException { 8442 // If the package has children and this is the first dive in the function 8443 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8444 // packages (parent and children) would be successfully scanned before the 8445 // actual scan since scanning mutates internal state and we want to atomically 8446 // install the package and its children. 8447 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8448 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8449 scanFlags |= SCAN_CHECK_ONLY; 8450 } 8451 } else { 8452 scanFlags &= ~SCAN_CHECK_ONLY; 8453 } 8454 8455 // Scan the parent 8456 PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags, 8457 scanFlags, currentTime, user); 8458 8459 // Scan the children 8460 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8461 for (int i = 0; i < childCount; i++) { 8462 PackageParser.Package childPackage = pkg.childPackages.get(i); 8463 addForInitLI(childPackage, parseFlags, scanFlags, 8464 currentTime, user); 8465 } 8466 8467 8468 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8469 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8470 } 8471 8472 return scannedPkg; 8473 } 8474 8475 /** 8476 * Returns if full apk verification can be skipped for the whole package, including the splits. 8477 */ 8478 private boolean canSkipFullPackageVerification(PackageParser.Package pkg) { 8479 if (!canSkipFullApkVerification(pkg.baseCodePath)) { 8480 return false; 8481 } 8482 // TODO: Allow base and splits to be verified individually. 8483 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8484 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8485 if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) { 8486 return false; 8487 } 8488 } 8489 } 8490 return true; 8491 } 8492 8493 /** 8494 * Returns if full apk verification can be skipped, depending on current FSVerity setup and 8495 * whether the apk contains signed root hash. Note that the signer's certificate still needs to 8496 * match one in a trusted source, and should be done separately. 8497 */ 8498 private boolean canSkipFullApkVerification(String apkPath) { 8499 byte[] rootHashObserved = null; 8500 try { 8501 rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath); 8502 if (rootHashObserved == null) { 8503 return false; // APK does not contain Merkle tree root hash. 8504 } 8505 synchronized (mInstallLock) { 8506 // Returns whether the observed root hash matches what kernel has. 8507 mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved); 8508 return true; 8509 } 8510 } catch (InstallerException | IOException | DigestException | 8511 NoSuchAlgorithmException e) { 8512 Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e); 8513 } 8514 return false; 8515 } 8516 8517 // Temporary to catch potential issues with refactoring 8518 private static boolean REFACTOR_DEBUG = true; 8519 /** 8520 * Adds a new package to the internal data structures during platform initialization. 8521 * <p>After adding, the package is known to the system and available for querying. 8522 * <p>For packages located on the device ROM [eg. packages located in /system, /vendor, 8523 * etc...], additional checks are performed. Basic verification [such as ensuring 8524 * matching signatures, checking version codes, etc...] occurs if the package is 8525 * identical to a previously known package. If the package fails a signature check, 8526 * the version installed on /data will be removed. If the version of the new package 8527 * is less than or equal than the version on /data, it will be ignored. 8528 * <p>Regardless of the package location, the results are applied to the internal 8529 * structures and the package is made available to the rest of the system. 8530 * <p>NOTE: The return value should be removed. It's the passed in package object. 8531 */ 8532 private PackageParser.Package addForInitLI(PackageParser.Package pkg, 8533 @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8534 @Nullable UserHandle user) 8535 throws PackageManagerException { 8536 final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0; 8537 final String renamedPkgName; 8538 final PackageSetting disabledPkgSetting; 8539 final boolean isSystemPkgUpdated; 8540 final boolean pkgAlreadyExists; 8541 PackageSetting pkgSetting; 8542 8543 // NOTE: installPackageLI() has the same code to setup the package's 8544 // application info. This probably should be done lower in the call 8545 // stack [such as scanPackageOnly()]. However, we verify the application 8546 // info prior to that [in scanPackageNew()] and thus have to setup 8547 // the application info early. 8548 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8549 pkg.setApplicationInfoCodePath(pkg.codePath); 8550 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8551 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8552 pkg.setApplicationInfoResourcePath(pkg.codePath); 8553 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 8554 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8555 8556 synchronized (mPackages) { 8557 renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8558 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 8559if (REFACTOR_DEBUG) { 8560Slog.e("TODD", 8561 "Add pkg: " + pkg.packageName + (realPkgName==null?"":", realName: " + realPkgName)); 8562} 8563 if (realPkgName != null) { 8564 ensurePackageRenamed(pkg, renamedPkgName); 8565 } 8566 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 8567 final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName); 8568 pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting; 8569 pkgAlreadyExists = pkgSetting != null; 8570 final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName; 8571 disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName); 8572 isSystemPkgUpdated = disabledPkgSetting != null; 8573 8574 if (DEBUG_INSTALL && isSystemPkgUpdated) { 8575 Slog.d(TAG, "updatedPkg = " + disabledPkgSetting); 8576 } 8577if (REFACTOR_DEBUG) { 8578Slog.e("TODD", 8579 "SSP? " + scanSystemPartition 8580 + ", exists? " + pkgAlreadyExists + (pkgAlreadyExists?" "+pkgSetting.toString():"") 8581 + ", upgraded? " + isSystemPkgUpdated + (isSystemPkgUpdated?" "+disabledPkgSetting.toString():"")); 8582} 8583 8584 final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null) 8585 ? mSettings.getSharedUserLPw(pkg.mSharedUserId, 8586 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true) 8587 : null; 8588 if (DEBUG_PACKAGE_SCANNING 8589 && (parseFlags & PackageParser.PARSE_CHATTY) != 0 8590 && sharedUserSetting != null) { 8591 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 8592 + " (uid=" + sharedUserSetting.userId + "):" 8593 + " packages=" + sharedUserSetting.packages); 8594if (REFACTOR_DEBUG) { 8595Slog.e("TODD", 8596 "Shared UserID " + pkg.mSharedUserId 8597 + " (uid=" + sharedUserSetting.userId + "):" 8598 + " packages=" + sharedUserSetting.packages); 8599} 8600 } 8601 8602 if (scanSystemPartition) { 8603 // Potentially prune child packages. If the application on the /system 8604 // partition has been updated via OTA, but, is still disabled by a 8605 // version on /data, cycle through all of its children packages and 8606 // remove children that are no longer defined. 8607 if (isSystemPkgUpdated) { 8608if (REFACTOR_DEBUG) { 8609Slog.e("TODD", 8610 "Disable child packages"); 8611} 8612 final int scannedChildCount = (pkg.childPackages != null) 8613 ? pkg.childPackages.size() : 0; 8614 final int disabledChildCount = disabledPkgSetting.childPackageNames != null 8615 ? disabledPkgSetting.childPackageNames.size() : 0; 8616 for (int i = 0; i < disabledChildCount; i++) { 8617 String disabledChildPackageName = 8618 disabledPkgSetting.childPackageNames.get(i); 8619 boolean disabledPackageAvailable = false; 8620 for (int j = 0; j < scannedChildCount; j++) { 8621 PackageParser.Package childPkg = pkg.childPackages.get(j); 8622 if (childPkg.packageName.equals(disabledChildPackageName)) { 8623if (REFACTOR_DEBUG) { 8624Slog.e("TODD", 8625 "Ignore " + disabledChildPackageName); 8626} 8627 disabledPackageAvailable = true; 8628 break; 8629 } 8630 } 8631 if (!disabledPackageAvailable) { 8632if (REFACTOR_DEBUG) { 8633Slog.e("TODD", 8634 "Disable " + disabledChildPackageName); 8635} 8636 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8637 } 8638 } 8639 // we're updating the disabled package, so, scan it as the package setting 8640 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, 8641 disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */, 8642 null /* originalPkgSetting */, null, parseFlags, scanFlags, 8643 (pkg == mPlatformPackage), user); 8644if (REFACTOR_DEBUG) { 8645Slog.e("TODD", 8646 "Scan disabled system package"); 8647Slog.e("TODD", 8648 "Pre: " + request.pkgSetting.dumpState_temp()); 8649} 8650final ScanResult result = 8651 scanPackageOnlyLI(request, mFactoryTest, -1L); 8652if (REFACTOR_DEBUG) { 8653Slog.e("TODD", 8654 "Post: " + (result.success?result.pkgSetting.dumpState_temp():"FAILED scan")); 8655} 8656 } 8657 } 8658 } 8659 8660 final boolean newPkgChangedPaths = 8661 pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath); 8662if (REFACTOR_DEBUG) { 8663Slog.e("TODD", 8664 "paths changed? " + newPkgChangedPaths 8665 + "; old: " + pkg.codePath 8666 + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.codePathString)); 8667} 8668 final boolean newPkgVersionGreater = 8669 pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode; 8670if (REFACTOR_DEBUG) { 8671Slog.e("TODD", 8672 "version greater? " + newPkgVersionGreater 8673 + "; old: " + pkg.getLongVersionCode() 8674 + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.versionCode)); 8675} 8676 final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated 8677 && newPkgChangedPaths && newPkgVersionGreater; 8678if (REFACTOR_DEBUG) { 8679 Slog.e("TODD", 8680 "system better? " + isSystemPkgBetter); 8681} 8682 if (isSystemPkgBetter) { 8683 // The version of the application on /system is greater than the version on 8684 // /data. Switch back to the application on /system. 8685 // It's safe to assume the application on /system will correctly scan. If not, 8686 // there won't be a working copy of the application. 8687 synchronized (mPackages) { 8688 // just remove the loaded entries from package lists 8689 mPackages.remove(pkgSetting.name); 8690 } 8691 8692 logCriticalInfo(Log.WARN, 8693 "System package updated;" 8694 + " name: " + pkgSetting.name 8695 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8696 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8697if (REFACTOR_DEBUG) { 8698Slog.e("TODD", 8699 "System package changed;" 8700 + " name: " + pkgSetting.name 8701 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8702 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8703} 8704 8705 final InstallArgs args = createInstallArgsForExisting( 8706 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8707 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8708 args.cleanUpResourcesLI(); 8709 synchronized (mPackages) { 8710 mSettings.enableSystemPackageLPw(pkgSetting.name); 8711 } 8712 } 8713 8714 if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) { 8715if (REFACTOR_DEBUG) { 8716Slog.e("TODD", 8717 "THROW exception; system pkg version not good enough"); 8718} 8719 // The version of the application on the /system partition is less than or 8720 // equal to the version on the /data partition. Throw an exception and use 8721 // the application already installed on the /data partition. 8722 throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at " 8723 + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode 8724 + " better than this " + pkg.getLongVersionCode()); 8725 } 8726 8727 // Verify certificates against what was last scanned. If it is an updated priv app, we will 8728 // force re-collecting certificate. Full apk verification will happen unless apk verity is 8729 // set up for the file. In that case, only small part of the apk is verified upfront. 8730 final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced( 8731 disabledPkgSetting); 8732 collectCertificatesLI(pkgSetting, pkg, forceCollect); 8733 8734 boolean shouldHideSystemApp = false; 8735 // A new application appeared on /system, but, we already have a copy of 8736 // the application installed on /data. 8737 if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists 8738 && !pkgSetting.isSystem()) { 8739 // if the signatures don't match, wipe the installed application and its data 8740 if (compareSignatures(pkgSetting.signatures.mSigningDetails.signatures, 8741 pkg.mSigningDetails.signatures) 8742 != PackageManager.SIGNATURE_MATCH) { 8743 logCriticalInfo(Log.WARN, 8744 "System package signature mismatch;" 8745 + " name: " + pkgSetting.name); 8746if (REFACTOR_DEBUG) { 8747Slog.e("TODD", 8748 "System package signature mismatch;" 8749 + " name: " + pkgSetting.name); 8750} 8751 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8752 "scanPackageInternalLI")) { 8753 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8754 } 8755 pkgSetting = null; 8756 } else if (newPkgVersionGreater) { 8757 // The application on /system is newer than the application on /data. 8758 // Simply remove the application on /data [keeping application data] 8759 // and replace it with the version on /system. 8760 logCriticalInfo(Log.WARN, 8761 "System package enabled;" 8762 + " name: " + pkgSetting.name 8763 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8764 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8765if (REFACTOR_DEBUG) { 8766Slog.e("TODD", 8767 "System package enabled;" 8768 + " name: " + pkgSetting.name 8769 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8770 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8771} 8772 InstallArgs args = createInstallArgsForExisting( 8773 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8774 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8775 synchronized (mInstallLock) { 8776 args.cleanUpResourcesLI(); 8777 } 8778 } else { 8779 // The application on /system is older than the application on /data. Hide 8780 // the application on /system and the version on /data will be scanned later 8781 // and re-added like an update. 8782 shouldHideSystemApp = true; 8783 logCriticalInfo(Log.INFO, 8784 "System package disabled;" 8785 + " name: " + pkgSetting.name 8786 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8787 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8788if (REFACTOR_DEBUG) { 8789Slog.e("TODD", 8790 "System package disabled;" 8791 + " name: " + pkgSetting.name 8792 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8793 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8794} 8795 } 8796 } 8797 8798if (REFACTOR_DEBUG) { 8799Slog.e("TODD", 8800 "Scan package"); 8801Slog.e("TODD", 8802 "Pre: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp())); 8803} 8804 final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags 8805 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8806if (REFACTOR_DEBUG) { 8807pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8808Slog.e("TODD", 8809 "Post: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp())); 8810} 8811 8812 if (shouldHideSystemApp) { 8813if (REFACTOR_DEBUG) { 8814Slog.e("TODD", 8815 "Disable package: " + pkg.packageName); 8816} 8817 synchronized (mPackages) { 8818 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8819 } 8820 } 8821 return scannedPkg; 8822 } 8823 8824 private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8825 // Derive the new package synthetic package name 8826 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8827 + pkg.staticSharedLibVersion); 8828 } 8829 8830 private static String fixProcessName(String defProcessName, 8831 String processName) { 8832 if (processName == null) { 8833 return defProcessName; 8834 } 8835 return processName; 8836 } 8837 8838 /** 8839 * Enforces that only the system UID or root's UID can call a method exposed 8840 * via Binder. 8841 * 8842 * @param message used as message if SecurityException is thrown 8843 * @throws SecurityException if the caller is not system or root 8844 */ 8845 private static final void enforceSystemOrRoot(String message) { 8846 final int uid = Binder.getCallingUid(); 8847 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 8848 throw new SecurityException(message); 8849 } 8850 } 8851 8852 @Override 8853 public void performFstrimIfNeeded() { 8854 enforceSystemOrRoot("Only the system can request fstrim"); 8855 8856 // Before everything else, see whether we need to fstrim. 8857 try { 8858 IStorageManager sm = PackageHelper.getStorageManager(); 8859 if (sm != null) { 8860 boolean doTrim = false; 8861 final long interval = android.provider.Settings.Global.getLong( 8862 mContext.getContentResolver(), 8863 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8864 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8865 if (interval > 0) { 8866 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8867 if (timeSinceLast > interval) { 8868 doTrim = true; 8869 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8870 + "; running immediately"); 8871 } 8872 } 8873 if (doTrim) { 8874 final boolean dexOptDialogShown; 8875 synchronized (mPackages) { 8876 dexOptDialogShown = mDexOptDialogShown; 8877 } 8878 if (!isFirstBoot() && dexOptDialogShown) { 8879 try { 8880 ActivityManager.getService().showBootMessage( 8881 mContext.getResources().getString( 8882 R.string.android_upgrading_fstrim), true); 8883 } catch (RemoteException e) { 8884 } 8885 } 8886 sm.runMaintenance(); 8887 } 8888 } else { 8889 Slog.e(TAG, "storageManager service unavailable!"); 8890 } 8891 } catch (RemoteException e) { 8892 // Can't happen; StorageManagerService is local 8893 } 8894 } 8895 8896 @Override 8897 public void updatePackagesIfNeeded() { 8898 enforceSystemOrRoot("Only the system can request package update"); 8899 8900 // We need to re-extract after an OTA. 8901 boolean causeUpgrade = isUpgrade(); 8902 8903 // First boot or factory reset. 8904 // Note: we also handle devices that are upgrading to N right now as if it is their 8905 // first boot, as they do not have profile data. 8906 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8907 8908 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8909 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8910 8911 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8912 return; 8913 } 8914 8915 List<PackageParser.Package> pkgs; 8916 synchronized (mPackages) { 8917 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8918 } 8919 8920 final long startTime = System.nanoTime(); 8921 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8922 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 8923 false /* bootComplete */); 8924 8925 final int elapsedTimeSeconds = 8926 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8927 8928 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8929 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8930 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8931 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8932 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8933 } 8934 8935 /* 8936 * Return the prebuilt profile path given a package base code path. 8937 */ 8938 private static String getPrebuildProfilePath(PackageParser.Package pkg) { 8939 return pkg.baseCodePath + ".prof"; 8940 } 8941 8942 /** 8943 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8944 * containing statistics about the invocation. The array consists of three elements, 8945 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8946 * and {@code numberOfPackagesFailed}. 8947 */ 8948 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8949 final String compilerFilter, boolean bootComplete) { 8950 8951 int numberOfPackagesVisited = 0; 8952 int numberOfPackagesOptimized = 0; 8953 int numberOfPackagesSkipped = 0; 8954 int numberOfPackagesFailed = 0; 8955 final int numberOfPackagesToDexopt = pkgs.size(); 8956 8957 for (PackageParser.Package pkg : pkgs) { 8958 numberOfPackagesVisited++; 8959 8960 boolean useProfileForDexopt = false; 8961 8962 if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) { 8963 // Copy over initial preopt profiles since we won't get any JIT samples for methods 8964 // that are already compiled. 8965 File profileFile = new File(getPrebuildProfilePath(pkg)); 8966 // Copy profile if it exists. 8967 if (profileFile.exists()) { 8968 try { 8969 // We could also do this lazily before calling dexopt in 8970 // PackageDexOptimizer to prevent this happening on first boot. The issue 8971 // is that we don't have a good way to say "do this only once". 8972 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8973 pkg.applicationInfo.uid, pkg.packageName, 8974 ArtManager.getProfileName(null))) { 8975 Log.e(TAG, "Installer failed to copy system profile!"); 8976 } else { 8977 // Disabled as this causes speed-profile compilation during first boot 8978 // even if things are already compiled. 8979 // useProfileForDexopt = true; 8980 } 8981 } catch (Exception e) { 8982 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", 8983 e); 8984 } 8985 } else { 8986 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8987 // Handle compressed APKs in this path. Only do this for stubs with profiles to 8988 // minimize the number off apps being speed-profile compiled during first boot. 8989 // The other paths will not change the filter. 8990 if (disabledPs != null && disabledPs.pkg.isStub) { 8991 // The package is the stub one, remove the stub suffix to get the normal 8992 // package and APK names. 8993 String systemProfilePath = 8994 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, ""); 8995 profileFile = new File(systemProfilePath); 8996 // If we have a profile for a compressed APK, copy it to the reference 8997 // location. 8998 // Note that copying the profile here will cause it to override the 8999 // reference profile every OTA even though the existing reference profile 9000 // may have more data. We can't copy during decompression since the 9001 // directories are not set up at that point. 9002 if (profileFile.exists()) { 9003 try { 9004 // We could also do this lazily before calling dexopt in 9005 // PackageDexOptimizer to prevent this happening on first boot. The 9006 // issue is that we don't have a good way to say "do this only 9007 // once". 9008 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 9009 pkg.applicationInfo.uid, pkg.packageName, 9010 ArtManager.getProfileName(null))) { 9011 Log.e(TAG, "Failed to copy system profile for stub package!"); 9012 } else { 9013 useProfileForDexopt = true; 9014 } 9015 } catch (Exception e) { 9016 Log.e(TAG, "Failed to copy profile " + 9017 profileFile.getAbsolutePath() + " ", e); 9018 } 9019 } 9020 } 9021 } 9022 } 9023 9024 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 9025 if (DEBUG_DEXOPT) { 9026 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 9027 } 9028 numberOfPackagesSkipped++; 9029 continue; 9030 } 9031 9032 if (DEBUG_DEXOPT) { 9033 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 9034 numberOfPackagesToDexopt + ": " + pkg.packageName); 9035 } 9036 9037 if (showDialog) { 9038 try { 9039 ActivityManager.getService().showBootMessage( 9040 mContext.getResources().getString(R.string.android_upgrading_apk, 9041 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 9042 } catch (RemoteException e) { 9043 } 9044 synchronized (mPackages) { 9045 mDexOptDialogShown = true; 9046 } 9047 } 9048 9049 String pkgCompilerFilter = compilerFilter; 9050 if (useProfileForDexopt) { 9051 // Use background dexopt mode to try and use the profile. Note that this does not 9052 // guarantee usage of the profile. 9053 pkgCompilerFilter = 9054 PackageManagerServiceCompilerMapping.getCompilerFilterForReason( 9055 PackageManagerService.REASON_BACKGROUND_DEXOPT); 9056 } 9057 9058 // checkProfiles is false to avoid merging profiles during boot which 9059 // might interfere with background compilation (b/28612421). 9060 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 9061 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 9062 // trade-off worth doing to save boot time work. 9063 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0; 9064 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions( 9065 pkg.packageName, 9066 pkgCompilerFilter, 9067 dexoptFlags)); 9068 9069 switch (primaryDexOptStaus) { 9070 case PackageDexOptimizer.DEX_OPT_PERFORMED: 9071 numberOfPackagesOptimized++; 9072 break; 9073 case PackageDexOptimizer.DEX_OPT_SKIPPED: 9074 numberOfPackagesSkipped++; 9075 break; 9076 case PackageDexOptimizer.DEX_OPT_FAILED: 9077 numberOfPackagesFailed++; 9078 break; 9079 default: 9080 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus); 9081 break; 9082 } 9083 } 9084 9085 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 9086 numberOfPackagesFailed }; 9087 } 9088 9089 @Override 9090 public void notifyPackageUse(String packageName, int reason) { 9091 synchronized (mPackages) { 9092 final int callingUid = Binder.getCallingUid(); 9093 final int callingUserId = UserHandle.getUserId(callingUid); 9094 if (getInstantAppPackageName(callingUid) != null) { 9095 if (!isCallerSameApp(packageName, callingUid)) { 9096 return; 9097 } 9098 } else { 9099 if (isInstantApp(packageName, callingUserId)) { 9100 return; 9101 } 9102 } 9103 notifyPackageUseLocked(packageName, reason); 9104 } 9105 } 9106 9107 private void notifyPackageUseLocked(String packageName, int reason) { 9108 final PackageParser.Package p = mPackages.get(packageName); 9109 if (p == null) { 9110 return; 9111 } 9112 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 9113 } 9114 9115 @Override 9116 public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames, 9117 List<String> classPaths, String loaderIsa) { 9118 int userId = UserHandle.getCallingUserId(); 9119 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 9120 if (ai == null) { 9121 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 9122 + loadingPackageName + ", user=" + userId); 9123 return; 9124 } 9125 mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId); 9126 } 9127 9128 @Override 9129 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule, 9130 IDexModuleRegisterCallback callback) { 9131 int userId = UserHandle.getCallingUserId(); 9132 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId); 9133 DexManager.RegisterDexModuleResult result; 9134 if (ai == null) { 9135 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" + 9136 " calling user. package=" + packageName + ", user=" + userId); 9137 result = new DexManager.RegisterDexModuleResult(false, "Package not installed"); 9138 } else { 9139 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId); 9140 } 9141 9142 if (callback != null) { 9143 mHandler.post(() -> { 9144 try { 9145 callback.onDexModuleRegistered(dexModulePath, result.success, result.message); 9146 } catch (RemoteException e) { 9147 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e); 9148 } 9149 }); 9150 } 9151 } 9152 9153 /** 9154 * Ask the package manager to perform a dex-opt with the given compiler filter. 9155 * 9156 * Note: exposed only for the shell command to allow moving packages explicitly to a 9157 * definite state. 9158 */ 9159 @Override 9160 public boolean performDexOptMode(String packageName, 9161 boolean checkProfiles, String targetCompilerFilter, boolean force, 9162 boolean bootComplete, String splitName) { 9163 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) | 9164 (force ? DexoptOptions.DEXOPT_FORCE : 0) | 9165 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0); 9166 return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter, 9167 splitName, flags)); 9168 } 9169 9170 /** 9171 * Ask the package manager to perform a dex-opt with the given compiler filter on the 9172 * secondary dex files belonging to the given package. 9173 * 9174 * Note: exposed only for the shell command to allow moving packages explicitly to a 9175 * definite state. 9176 */ 9177 @Override 9178 public boolean performDexOptSecondary(String packageName, String compilerFilter, 9179 boolean force) { 9180 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX | 9181 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES | 9182 DexoptOptions.DEXOPT_BOOT_COMPLETE | 9183 (force ? DexoptOptions.DEXOPT_FORCE : 0); 9184 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags)); 9185 } 9186 9187 /*package*/ boolean performDexOpt(DexoptOptions options) { 9188 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9189 return false; 9190 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) { 9191 return false; 9192 } 9193 9194 if (options.isDexoptOnlySecondaryDex()) { 9195 return mDexManager.dexoptSecondaryDex(options); 9196 } else { 9197 int dexoptStatus = performDexOptWithStatus(options); 9198 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9199 } 9200 } 9201 9202 /** 9203 * Perform dexopt on the given package and return one of following result: 9204 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9205 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9206 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9207 */ 9208 /* package */ int performDexOptWithStatus(DexoptOptions options) { 9209 return performDexOptTraced(options); 9210 } 9211 9212 private int performDexOptTraced(DexoptOptions options) { 9213 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9214 try { 9215 return performDexOptInternal(options); 9216 } finally { 9217 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9218 } 9219 } 9220 9221 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9222 // if the package can now be considered up to date for the given filter. 9223 private int performDexOptInternal(DexoptOptions options) { 9224 PackageParser.Package p; 9225 synchronized (mPackages) { 9226 p = mPackages.get(options.getPackageName()); 9227 if (p == null) { 9228 // Package could not be found. Report failure. 9229 return PackageDexOptimizer.DEX_OPT_FAILED; 9230 } 9231 mPackageUsage.maybeWriteAsync(mPackages); 9232 mCompilerStats.maybeWriteAsync(); 9233 } 9234 long callingId = Binder.clearCallingIdentity(); 9235 try { 9236 synchronized (mInstallLock) { 9237 return performDexOptInternalWithDependenciesLI(p, options); 9238 } 9239 } finally { 9240 Binder.restoreCallingIdentity(callingId); 9241 } 9242 } 9243 9244 public ArraySet<String> getOptimizablePackages() { 9245 ArraySet<String> pkgs = new ArraySet<String>(); 9246 synchronized (mPackages) { 9247 for (PackageParser.Package p : mPackages.values()) { 9248 if (PackageDexOptimizer.canOptimizePackage(p)) { 9249 pkgs.add(p.packageName); 9250 } 9251 } 9252 } 9253 return pkgs; 9254 } 9255 9256 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9257 DexoptOptions options) { 9258 // Select the dex optimizer based on the force parameter. 9259 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9260 // allocate an object here. 9261 PackageDexOptimizer pdo = options.isForce() 9262 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9263 : mPackageDexOptimizer; 9264 9265 // Dexopt all dependencies first. Note: we ignore the return value and march on 9266 // on errors. 9267 // Note that we are going to call performDexOpt on those libraries as many times as 9268 // they are referenced in packages. When we do a batch of performDexOpt (for example 9269 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9270 // and the first package that uses the library will dexopt it. The 9271 // others will see that the compiled code for the library is up to date. 9272 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 9273 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9274 if (!deps.isEmpty()) { 9275 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(), 9276 options.getCompilerFilter(), options.getSplitName(), 9277 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY); 9278 for (PackageParser.Package depPackage : deps) { 9279 // TODO: Analyze and investigate if we (should) profile libraries. 9280 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 9281 getOrCreateCompilerPackageStats(depPackage), 9282 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions); 9283 } 9284 } 9285 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, 9286 getOrCreateCompilerPackageStats(p), 9287 mDexManager.getPackageUseInfoOrDefault(p.packageName), options); 9288 } 9289 9290 /** 9291 * Reconcile the information we have about the secondary dex files belonging to 9292 * {@code packagName} and the actual dex files. For all dex files that were 9293 * deleted, update the internal records and delete the generated oat files. 9294 */ 9295 @Override 9296 public void reconcileSecondaryDexFiles(String packageName) { 9297 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9298 return; 9299 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9300 return; 9301 } 9302 mDexManager.reconcileSecondaryDexFiles(packageName); 9303 } 9304 9305 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 9306 // a reference there. 9307 /*package*/ DexManager getDexManager() { 9308 return mDexManager; 9309 } 9310 9311 /** 9312 * Execute the background dexopt job immediately. 9313 */ 9314 @Override 9315 public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) { 9316 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9317 return false; 9318 } 9319 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames); 9320 } 9321 9322 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 9323 if (p.usesLibraries != null || p.usesOptionalLibraries != null 9324 || p.usesStaticLibraries != null) { 9325 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 9326 Set<String> collectedNames = new HashSet<>(); 9327 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 9328 9329 retValue.remove(p); 9330 9331 return retValue; 9332 } else { 9333 return Collections.emptyList(); 9334 } 9335 } 9336 9337 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 9338 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9339 if (!collectedNames.contains(p.packageName)) { 9340 collectedNames.add(p.packageName); 9341 collected.add(p); 9342 9343 if (p.usesLibraries != null) { 9344 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 9345 null, collected, collectedNames); 9346 } 9347 if (p.usesOptionalLibraries != null) { 9348 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 9349 null, collected, collectedNames); 9350 } 9351 if (p.usesStaticLibraries != null) { 9352 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 9353 p.usesStaticLibrariesVersions, collected, collectedNames); 9354 } 9355 } 9356 } 9357 9358 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions, 9359 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9360 final int libNameCount = libs.size(); 9361 for (int i = 0; i < libNameCount; i++) { 9362 String libName = libs.get(i); 9363 long version = (versions != null && versions.length == libNameCount) 9364 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 9365 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 9366 if (libPkg != null) { 9367 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 9368 } 9369 } 9370 } 9371 9372 private PackageParser.Package findSharedNonSystemLibrary(String name, long version) { 9373 synchronized (mPackages) { 9374 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 9375 if (libEntry != null) { 9376 return mPackages.get(libEntry.apk); 9377 } 9378 return null; 9379 } 9380 } 9381 9382 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) { 9383 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9384 if (versionedLib == null) { 9385 return null; 9386 } 9387 return versionedLib.get(version); 9388 } 9389 9390 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9391 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9392 pkg.staticSharedLibName); 9393 if (versionedLib == null) { 9394 return null; 9395 } 9396 long previousLibVersion = -1; 9397 final int versionCount = versionedLib.size(); 9398 for (int i = 0; i < versionCount; i++) { 9399 final long libVersion = versionedLib.keyAt(i); 9400 if (libVersion < pkg.staticSharedLibVersion) { 9401 previousLibVersion = Math.max(previousLibVersion, libVersion); 9402 } 9403 } 9404 if (previousLibVersion >= 0) { 9405 return versionedLib.get(previousLibVersion); 9406 } 9407 return null; 9408 } 9409 9410 public void shutdown() { 9411 mPackageUsage.writeNow(mPackages); 9412 mCompilerStats.writeNow(); 9413 mDexManager.writePackageDexUsageNow(); 9414 } 9415 9416 @Override 9417 public void dumpProfiles(String packageName) { 9418 PackageParser.Package pkg; 9419 synchronized (mPackages) { 9420 pkg = mPackages.get(packageName); 9421 if (pkg == null) { 9422 throw new IllegalArgumentException("Unknown package: " + packageName); 9423 } 9424 } 9425 /* Only the shell, root, or the app user should be able to dump profiles. */ 9426 int callingUid = Binder.getCallingUid(); 9427 if (callingUid != Process.SHELL_UID && 9428 callingUid != Process.ROOT_UID && 9429 callingUid != pkg.applicationInfo.uid) { 9430 throw new SecurityException("dumpProfiles"); 9431 } 9432 9433 synchronized (mInstallLock) { 9434 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9435 mArtManagerService.dumpProfiles(pkg); 9436 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9437 } 9438 } 9439 9440 @Override 9441 public void forceDexOpt(String packageName) { 9442 enforceSystemOrRoot("forceDexOpt"); 9443 9444 PackageParser.Package pkg; 9445 synchronized (mPackages) { 9446 pkg = mPackages.get(packageName); 9447 if (pkg == null) { 9448 throw new IllegalArgumentException("Unknown package: " + packageName); 9449 } 9450 } 9451 9452 synchronized (mInstallLock) { 9453 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9454 9455 // Whoever is calling forceDexOpt wants a compiled package. 9456 // Don't use profiles since that may cause compilation to be skipped. 9457 final int res = performDexOptInternalWithDependenciesLI( 9458 pkg, 9459 new DexoptOptions(packageName, 9460 getDefaultCompilerFilter(), 9461 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE)); 9462 9463 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9464 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9465 throw new IllegalStateException("Failed to dexopt: " + res); 9466 } 9467 } 9468 } 9469 9470 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9471 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9472 Slog.w(TAG, "Unable to update from " + oldPkg.name 9473 + " to " + newPkg.packageName 9474 + ": old package not in system partition"); 9475 return false; 9476 } else if (mPackages.get(oldPkg.name) != null) { 9477 Slog.w(TAG, "Unable to update from " + oldPkg.name 9478 + " to " + newPkg.packageName 9479 + ": old package still exists"); 9480 return false; 9481 } 9482 return true; 9483 } 9484 9485 void removeCodePathLI(File codePath) { 9486 if (codePath.isDirectory()) { 9487 try { 9488 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9489 } catch (InstallerException e) { 9490 Slog.w(TAG, "Failed to remove code path", e); 9491 } 9492 } else { 9493 codePath.delete(); 9494 } 9495 } 9496 9497 private int[] resolveUserIds(int userId) { 9498 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9499 } 9500 9501 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9502 if (pkg == null) { 9503 Slog.wtf(TAG, "Package was null!", new Throwable()); 9504 return; 9505 } 9506 clearAppDataLeafLIF(pkg, userId, flags); 9507 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9508 for (int i = 0; i < childCount; i++) { 9509 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9510 } 9511 9512 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 9513 } 9514 9515 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9516 final PackageSetting ps; 9517 synchronized (mPackages) { 9518 ps = mSettings.mPackages.get(pkg.packageName); 9519 } 9520 for (int realUserId : resolveUserIds(userId)) { 9521 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9522 try { 9523 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9524 ceDataInode); 9525 } catch (InstallerException e) { 9526 Slog.w(TAG, String.valueOf(e)); 9527 } 9528 } 9529 } 9530 9531 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9532 if (pkg == null) { 9533 Slog.wtf(TAG, "Package was null!", new Throwable()); 9534 return; 9535 } 9536 destroyAppDataLeafLIF(pkg, userId, flags); 9537 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9538 for (int i = 0; i < childCount; i++) { 9539 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9540 } 9541 } 9542 9543 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9544 final PackageSetting ps; 9545 synchronized (mPackages) { 9546 ps = mSettings.mPackages.get(pkg.packageName); 9547 } 9548 for (int realUserId : resolveUserIds(userId)) { 9549 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9550 try { 9551 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9552 ceDataInode); 9553 } catch (InstallerException e) { 9554 Slog.w(TAG, String.valueOf(e)); 9555 } 9556 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9557 } 9558 } 9559 9560 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9561 if (pkg == null) { 9562 Slog.wtf(TAG, "Package was null!", new Throwable()); 9563 return; 9564 } 9565 destroyAppProfilesLeafLIF(pkg); 9566 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9567 for (int i = 0; i < childCount; i++) { 9568 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9569 } 9570 } 9571 9572 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9573 try { 9574 mInstaller.destroyAppProfiles(pkg.packageName); 9575 } catch (InstallerException e) { 9576 Slog.w(TAG, String.valueOf(e)); 9577 } 9578 } 9579 9580 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9581 if (pkg == null) { 9582 Slog.wtf(TAG, "Package was null!", new Throwable()); 9583 return; 9584 } 9585 mArtManagerService.clearAppProfiles(pkg); 9586 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9587 for (int i = 0; i < childCount; i++) { 9588 mArtManagerService.clearAppProfiles(pkg.childPackages.get(i)); 9589 } 9590 } 9591 9592 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9593 long lastUpdateTime) { 9594 // Set parent install/update time 9595 PackageSetting ps = (PackageSetting) pkg.mExtras; 9596 if (ps != null) { 9597 ps.firstInstallTime = firstInstallTime; 9598 ps.lastUpdateTime = lastUpdateTime; 9599 } 9600 // Set children install/update time 9601 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9602 for (int i = 0; i < childCount; i++) { 9603 PackageParser.Package childPkg = pkg.childPackages.get(i); 9604 ps = (PackageSetting) childPkg.mExtras; 9605 if (ps != null) { 9606 ps.firstInstallTime = firstInstallTime; 9607 ps.lastUpdateTime = lastUpdateTime; 9608 } 9609 } 9610 } 9611 9612 private void addSharedLibraryLPr(Set<String> usesLibraryFiles, 9613 SharedLibraryEntry file, 9614 PackageParser.Package changingLib) { 9615 if (file.path != null) { 9616 usesLibraryFiles.add(file.path); 9617 return; 9618 } 9619 PackageParser.Package p = mPackages.get(file.apk); 9620 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9621 // If we are doing this while in the middle of updating a library apk, 9622 // then we need to make sure to use that new apk for determining the 9623 // dependencies here. (We haven't yet finished committing the new apk 9624 // to the package manager state.) 9625 if (p == null || p.packageName.equals(changingLib.packageName)) { 9626 p = changingLib; 9627 } 9628 } 9629 if (p != null) { 9630 usesLibraryFiles.addAll(p.getAllCodePaths()); 9631 if (p.usesLibraryFiles != null) { 9632 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 9633 } 9634 } 9635 } 9636 9637 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9638 PackageParser.Package changingLib) throws PackageManagerException { 9639 if (pkg == null) { 9640 return; 9641 } 9642 // The collection used here must maintain the order of addition (so 9643 // that libraries are searched in the correct order) and must have no 9644 // duplicates. 9645 Set<String> usesLibraryFiles = null; 9646 if (pkg.usesLibraries != null) { 9647 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9648 null, null, pkg.packageName, changingLib, true, 9649 pkg.applicationInfo.targetSdkVersion, null); 9650 } 9651 if (pkg.usesStaticLibraries != null) { 9652 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9653 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9654 pkg.packageName, changingLib, true, 9655 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9656 } 9657 if (pkg.usesOptionalLibraries != null) { 9658 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9659 null, null, pkg.packageName, changingLib, false, 9660 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9661 } 9662 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9663 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9664 } else { 9665 pkg.usesLibraryFiles = null; 9666 } 9667 } 9668 9669 private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9670 @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests, 9671 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9672 boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries) 9673 throws PackageManagerException { 9674 final int libCount = requestedLibraries.size(); 9675 for (int i = 0; i < libCount; i++) { 9676 final String libName = requestedLibraries.get(i); 9677 final long libVersion = requiredVersions != null ? requiredVersions[i] 9678 : SharedLibraryInfo.VERSION_UNDEFINED; 9679 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9680 if (libEntry == null) { 9681 if (required) { 9682 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9683 "Package " + packageName + " requires unavailable shared library " 9684 + libName + "; failing!"); 9685 } else if (DEBUG_SHARED_LIBRARIES) { 9686 Slog.i(TAG, "Package " + packageName 9687 + " desires unavailable shared library " 9688 + libName + "; ignoring!"); 9689 } 9690 } else { 9691 if (requiredVersions != null && requiredCertDigests != null) { 9692 if (libEntry.info.getLongVersion() != requiredVersions[i]) { 9693 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9694 "Package " + packageName + " requires unavailable static shared" 9695 + " library " + libName + " version " 9696 + libEntry.info.getLongVersion() + "; failing!"); 9697 } 9698 9699 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9700 if (libPkg == null) { 9701 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9702 "Package " + packageName + " requires unavailable static shared" 9703 + " library; failing!"); 9704 } 9705 9706 final String[] expectedCertDigests = requiredCertDigests[i]; 9707 // For apps targeting O MR1 we require explicit enumeration of all certs. 9708 final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O) 9709 ? PackageUtils.computeSignaturesSha256Digests( 9710 libPkg.mSigningDetails.signatures) 9711 : PackageUtils.computeSignaturesSha256Digests( 9712 new Signature[]{libPkg.mSigningDetails.signatures[0]}); 9713 9714 // Take a shortcut if sizes don't match. Note that if an app doesn't 9715 // target O we don't parse the "additional-certificate" tags similarly 9716 // how we only consider all certs only for apps targeting O (see above). 9717 // Therefore, the size check is safe to make. 9718 if (expectedCertDigests.length != libCertDigests.length) { 9719 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9720 "Package " + packageName + " requires differently signed" + 9721 " static shared library; failing!"); 9722 } 9723 9724 // Use a predictable order as signature order may vary 9725 Arrays.sort(libCertDigests); 9726 Arrays.sort(expectedCertDigests); 9727 9728 final int certCount = libCertDigests.length; 9729 for (int j = 0; j < certCount; j++) { 9730 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) { 9731 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9732 "Package " + packageName + " requires differently signed" + 9733 " static shared library; failing!"); 9734 } 9735 } 9736 } 9737 9738 if (outUsedLibraries == null) { 9739 // Use LinkedHashSet to preserve the order of files added to 9740 // usesLibraryFiles while eliminating duplicates. 9741 outUsedLibraries = new LinkedHashSet<>(); 9742 } 9743 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9744 } 9745 } 9746 return outUsedLibraries; 9747 } 9748 9749 private static boolean hasString(List<String> list, List<String> which) { 9750 if (list == null) { 9751 return false; 9752 } 9753 for (int i=list.size()-1; i>=0; i--) { 9754 for (int j=which.size()-1; j>=0; j--) { 9755 if (which.get(j).equals(list.get(i))) { 9756 return true; 9757 } 9758 } 9759 } 9760 return false; 9761 } 9762 9763 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9764 PackageParser.Package changingPkg) { 9765 ArrayList<PackageParser.Package> res = null; 9766 for (PackageParser.Package pkg : mPackages.values()) { 9767 if (changingPkg != null 9768 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9769 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9770 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9771 changingPkg.staticSharedLibName)) { 9772 return null; 9773 } 9774 if (res == null) { 9775 res = new ArrayList<>(); 9776 } 9777 res.add(pkg); 9778 try { 9779 updateSharedLibrariesLPr(pkg, changingPkg); 9780 } catch (PackageManagerException e) { 9781 // If a system app update or an app and a required lib missing we 9782 // delete the package and for updated system apps keep the data as 9783 // it is better for the user to reinstall than to be in an limbo 9784 // state. Also libs disappearing under an app should never happen 9785 // - just in case. 9786 if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) { 9787 final int flags = pkg.isUpdatedSystemApp() 9788 ? PackageManager.DELETE_KEEP_DATA : 0; 9789 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9790 flags , null, true, null); 9791 } 9792 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9793 } 9794 } 9795 return res; 9796 } 9797 9798 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9799 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9800 @Nullable UserHandle user) throws PackageManagerException { 9801 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9802 // If the package has children and this is the first dive in the function 9803 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9804 // whether all packages (parent and children) would be successfully scanned 9805 // before the actual scan since scanning mutates internal state and we want 9806 // to atomically install the package and its children. 9807 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9808 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9809 scanFlags |= SCAN_CHECK_ONLY; 9810 } 9811 } else { 9812 scanFlags &= ~SCAN_CHECK_ONLY; 9813 } 9814 9815 final PackageParser.Package scannedPkg; 9816 try { 9817 // Scan the parent 9818 scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user); 9819 // Scan the children 9820 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9821 for (int i = 0; i < childCount; i++) { 9822 PackageParser.Package childPkg = pkg.childPackages.get(i); 9823 scanPackageNewLI(childPkg, parseFlags, 9824 scanFlags, currentTime, user); 9825 } 9826 } finally { 9827 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9828 } 9829 9830 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9831 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 9832 } 9833 9834 return scannedPkg; 9835 } 9836 9837 /** The result of a package scan. */ 9838 private static class ScanResult { 9839 /** Whether or not the package scan was successful */ 9840 public final boolean success; 9841 /** 9842 * The final package settings. This may be the same object passed in 9843 * the {@link ScanRequest}, but, with modified values. 9844 */ 9845 @Nullable public final PackageSetting pkgSetting; 9846 /** ABI code paths that have changed in the package scan */ 9847 @Nullable public final List<String> changedAbiCodePath; 9848 public ScanResult( 9849 boolean success, 9850 @Nullable PackageSetting pkgSetting, 9851 @Nullable List<String> changedAbiCodePath) { 9852 this.success = success; 9853 this.pkgSetting = pkgSetting; 9854 this.changedAbiCodePath = changedAbiCodePath; 9855 } 9856 } 9857 9858 /** A package to be scanned */ 9859 private static class ScanRequest { 9860 /** The parsed package */ 9861 @NonNull public final PackageParser.Package pkg; 9862 /** Shared user settings, if the package has a shared user */ 9863 @Nullable public final SharedUserSetting sharedUserSetting; 9864 /** 9865 * Package settings of the currently installed version. 9866 * <p><em>IMPORTANT:</em> The contents of this object may be modified 9867 * during scan. 9868 */ 9869 @Nullable public final PackageSetting pkgSetting; 9870 /** A copy of the settings for the currently installed version */ 9871 @Nullable public final PackageSetting oldPkgSetting; 9872 /** Package settings for the disabled version on the /system partition */ 9873 @Nullable public final PackageSetting disabledPkgSetting; 9874 /** Package settings for the installed version under its original package name */ 9875 @Nullable public final PackageSetting originalPkgSetting; 9876 /** The real package name of a renamed application */ 9877 @Nullable public final String realPkgName; 9878 public final @ParseFlags int parseFlags; 9879 public final @ScanFlags int scanFlags; 9880 /** The user for which the package is being scanned */ 9881 @Nullable public final UserHandle user; 9882 /** Whether or not the platform package is being scanned */ 9883 public final boolean isPlatformPackage; 9884 public ScanRequest( 9885 @NonNull PackageParser.Package pkg, 9886 @Nullable SharedUserSetting sharedUserSetting, 9887 @Nullable PackageSetting pkgSetting, 9888 @Nullable PackageSetting disabledPkgSetting, 9889 @Nullable PackageSetting originalPkgSetting, 9890 @Nullable String realPkgName, 9891 @ParseFlags int parseFlags, 9892 @ScanFlags int scanFlags, 9893 boolean isPlatformPackage, 9894 @Nullable UserHandle user) { 9895 this.pkg = pkg; 9896 this.pkgSetting = pkgSetting; 9897 this.sharedUserSetting = sharedUserSetting; 9898 this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting); 9899 this.disabledPkgSetting = disabledPkgSetting; 9900 this.originalPkgSetting = originalPkgSetting; 9901 this.realPkgName = realPkgName; 9902 this.parseFlags = parseFlags; 9903 this.scanFlags = scanFlags; 9904 this.isPlatformPackage = isPlatformPackage; 9905 this.user = user; 9906 } 9907 } 9908 9909 /** 9910 * Returns the actual scan flags depending upon the state of the other settings. 9911 * <p>Updated system applications will not have the following flags set 9912 * by default and need to be adjusted after the fact: 9913 * <ul> 9914 * <li>{@link #SCAN_AS_SYSTEM}</li> 9915 * <li>{@link #SCAN_AS_PRIVILEGED}</li> 9916 * <li>{@link #SCAN_AS_OEM}</li> 9917 * <li>{@link #SCAN_AS_VENDOR}</li> 9918 * <li>{@link #SCAN_AS_PRODUCT}</li> 9919 * <li>{@link #SCAN_AS_INSTANT_APP}</li> 9920 * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li> 9921 * </ul> 9922 */ 9923 private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags, 9924 PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user, 9925 PackageParser.Package pkg) { 9926 if (disabledPkgSetting != null) { 9927 // updated system application, must at least have SCAN_AS_SYSTEM 9928 scanFlags |= SCAN_AS_SYSTEM; 9929 if ((disabledPkgSetting.pkgPrivateFlags 9930 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 9931 scanFlags |= SCAN_AS_PRIVILEGED; 9932 } 9933 if ((disabledPkgSetting.pkgPrivateFlags 9934 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) { 9935 scanFlags |= SCAN_AS_OEM; 9936 } 9937 if ((disabledPkgSetting.pkgPrivateFlags 9938 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) { 9939 scanFlags |= SCAN_AS_VENDOR; 9940 } 9941 if ((disabledPkgSetting.pkgPrivateFlags 9942 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) { 9943 scanFlags |= SCAN_AS_PRODUCT; 9944 } 9945 } 9946 if (pkgSetting != null) { 9947 final int userId = ((user == null) ? 0 : user.getIdentifier()); 9948 if (pkgSetting.getInstantApp(userId)) { 9949 scanFlags |= SCAN_AS_INSTANT_APP; 9950 } 9951 if (pkgSetting.getVirtulalPreload(userId)) { 9952 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 9953 } 9954 } 9955 9956 // Scan as privileged apps that share a user with a priv-app. 9957 if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged() 9958 && (pkg.mSharedUserId != null)) { 9959 SharedUserSetting sharedUserSetting = null; 9960 try { 9961 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 9962 } catch (PackageManagerException ignore) {} 9963 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 9964 // Exempt SharedUsers signed with the platform key. 9965 // TODO(b/72378145) Fix this exemption. Force signature apps 9966 // to whitelist their privileged permissions just like other 9967 // priv-apps. 9968 synchronized (mPackages) { 9969 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 9970 if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures, 9971 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) { 9972 scanFlags |= SCAN_AS_PRIVILEGED; 9973 } 9974 } 9975 } 9976 } 9977 9978 return scanFlags; 9979 } 9980 9981 @GuardedBy("mInstallLock") 9982 private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg, 9983 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9984 @Nullable UserHandle user) throws PackageManagerException { 9985 9986 final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9987 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 9988 if (realPkgName != null) { 9989 ensurePackageRenamed(pkg, renamedPkgName); 9990 } 9991 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 9992 final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9993 final PackageSetting disabledPkgSetting = 9994 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9995 9996 if (mTransferedPackages.contains(pkg.packageName)) { 9997 Slog.w(TAG, "Package " + pkg.packageName 9998 + " was transferred to another, but its .apk remains"); 9999 } 10000 10001 scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg); 10002 synchronized (mPackages) { 10003 applyPolicy(pkg, parseFlags, scanFlags); 10004 assertPackageIsValid(pkg, parseFlags, scanFlags); 10005 10006 SharedUserSetting sharedUserSetting = null; 10007 if (pkg.mSharedUserId != null) { 10008 // SIDE EFFECTS; may potentially allocate a new shared user 10009 sharedUserSetting = mSettings.getSharedUserLPw( 10010 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 10011 if (DEBUG_PACKAGE_SCANNING) { 10012 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10013 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 10014 + " (uid=" + sharedUserSetting.userId + "):" 10015 + " packages=" + sharedUserSetting.packages); 10016 } 10017 } 10018 10019 boolean scanSucceeded = false; 10020 try { 10021 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting, 10022 disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags, 10023 (pkg == mPlatformPackage), user); 10024 final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime); 10025 if (result.success) { 10026 commitScanResultsLocked(request, result); 10027 } 10028 scanSucceeded = true; 10029 } finally { 10030 if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 10031 // DELETE_DATA_ON_FAILURES is only used by frozen paths 10032 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 10033 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 10034 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 10035 } 10036 } 10037 } 10038 return pkg; 10039 } 10040 10041 /** 10042 * Commits the package scan and modifies system state. 10043 * <p><em>WARNING:</em> The method may throw an excpetion in the middle 10044 * of committing the package, leaving the system in an inconsistent state. 10045 * This needs to be fixed so, once we get to this point, no errors are 10046 * possible and the system is not left in an inconsistent state. 10047 */ 10048 @GuardedBy("mPackages") 10049 private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result) 10050 throws PackageManagerException { 10051 final PackageParser.Package pkg = request.pkg; 10052 final @ParseFlags int parseFlags = request.parseFlags; 10053 final @ScanFlags int scanFlags = request.scanFlags; 10054 final PackageSetting oldPkgSetting = request.oldPkgSetting; 10055 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10056 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10057 final UserHandle user = request.user; 10058 final String realPkgName = request.realPkgName; 10059 final PackageSetting pkgSetting = result.pkgSetting; 10060 final List<String> changedAbiCodePath = result.changedAbiCodePath; 10061 final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting); 10062 10063 if (newPkgSettingCreated) { 10064 if (originalPkgSetting != null) { 10065 mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name); 10066 } 10067 // THROWS: when we can't allocate a user id. add call to check if there's 10068 // enough space to ensure we won't throw; otherwise, don't modify state 10069 mSettings.addUserToSettingLPw(pkgSetting); 10070 10071 if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) { 10072 mTransferedPackages.add(originalPkgSetting.name); 10073 } 10074 } 10075 // TODO(toddke): Consider a method specifically for modifying the Package object 10076 // post scan; or, moving this stuff out of the Package object since it has nothing 10077 // to do with the package on disk. 10078 // We need to have this here because addUserToSettingLPw() is sometimes responsible 10079 // for creating the application ID. If we did this earlier, we would be saving the 10080 // correct ID. 10081 pkg.applicationInfo.uid = pkgSetting.appId; 10082 10083 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 10084 10085 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) { 10086 mTransferedPackages.add(pkg.packageName); 10087 } 10088 10089 // THROWS: when requested libraries that can't be found. it only changes 10090 // the state of the passed in pkg object, so, move to the top of the method 10091 // and allow it to abort 10092 if ((scanFlags & SCAN_BOOTING) == 0 10093 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10094 // Check all shared libraries and map to their actual file path. 10095 // We only do this here for apps not on a system dir, because those 10096 // are the only ones that can fail an install due to this. We 10097 // will take care of the system apps by updating all of their 10098 // library paths after the scan is done. Also during the initial 10099 // scan don't update any libs as we do this wholesale after all 10100 // apps are scanned to avoid dependency based scanning. 10101 updateSharedLibrariesLPr(pkg, null); 10102 } 10103 10104 // All versions of a static shared library are referenced with the same 10105 // package name. Internally, we use a synthetic package name to allow 10106 // multiple versions of the same shared library to be installed. So, 10107 // we need to generate the synthetic package name of the latest shared 10108 // library in order to compare signatures. 10109 PackageSetting signatureCheckPs = pkgSetting; 10110 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10111 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 10112 if (libraryEntry != null) { 10113 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 10114 } 10115 } 10116 10117 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10118 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 10119 if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 10120 // We just determined the app is signed correctly, so bring 10121 // over the latest parsed certs. 10122 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10123 } else { 10124 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10125 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10126 "Package " + pkg.packageName + " upgrade keys do not match the " 10127 + "previously installed version"); 10128 } else { 10129 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10130 String msg = "System package " + pkg.packageName 10131 + " signature changed; retaining data."; 10132 reportSettingsProblem(Log.WARN, msg); 10133 } 10134 } 10135 } else { 10136 try { 10137 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 10138 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 10139 final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting, 10140 pkg.mSigningDetails, compareCompat, compareRecover); 10141 // The new KeySets will be re-added later in the scanning process. 10142 if (compatMatch) { 10143 synchronized (mPackages) { 10144 ksms.removeAppKeySetDataLPw(pkg.packageName); 10145 } 10146 } 10147 // We just determined the app is signed correctly, so bring 10148 // over the latest parsed certs. 10149 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10150 } catch (PackageManagerException e) { 10151 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10152 throw e; 10153 } 10154 // The signature has changed, but this package is in the system 10155 // image... let's recover! 10156 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10157 // However... if this package is part of a shared user, but it 10158 // doesn't match the signature of the shared user, let's fail. 10159 // What this means is that you can't change the signatures 10160 // associated with an overall shared user, which doesn't seem all 10161 // that unreasonable. 10162 if (signatureCheckPs.sharedUser != null) { 10163 if (compareSignatures( 10164 signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures, 10165 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) { 10166 throw new PackageManagerException( 10167 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10168 "Signature mismatch for shared user: " 10169 + pkgSetting.sharedUser); 10170 } 10171 } 10172 // File a report about this. 10173 String msg = "System package " + pkg.packageName 10174 + " signature changed; retaining data."; 10175 reportSettingsProblem(Log.WARN, msg); 10176 } 10177 } 10178 10179 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 10180 // This package wants to adopt ownership of permissions from 10181 // another package. 10182 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 10183 final String origName = pkg.mAdoptPermissions.get(i); 10184 final PackageSetting orig = mSettings.getPackageLPr(origName); 10185 if (orig != null) { 10186 if (verifyPackageUpdateLPr(orig, pkg)) { 10187 Slog.i(TAG, "Adopting permissions from " + origName + " to " 10188 + pkg.packageName); 10189 mSettings.mPermissions.transferPermissions(origName, pkg.packageName); 10190 } 10191 } 10192 } 10193 } 10194 10195 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 10196 for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) { 10197 final String codePathString = changedAbiCodePath.get(i); 10198 try { 10199 mInstaller.rmdex(codePathString, 10200 getDexCodeInstructionSet(getPreferredInstructionSet())); 10201 } catch (InstallerException ignored) { 10202 } 10203 } 10204 } 10205 10206 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10207 if (oldPkgSetting != null) { 10208 synchronized (mPackages) { 10209 mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting); 10210 } 10211 } 10212 } else { 10213 final int userId = user == null ? 0 : user.getIdentifier(); 10214 // Modify state for the given package setting 10215 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 10216 (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 10217 if (pkgSetting.getInstantApp(userId)) { 10218 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 10219 } 10220 } 10221 } 10222 10223 /** 10224 * Returns the "real" name of the package. 10225 * <p>This may differ from the package's actual name if the application has already 10226 * been installed under one of this package's original names. 10227 */ 10228 private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg, 10229 @Nullable String renamedPkgName) { 10230 if (isPackageRenamed(pkg, renamedPkgName)) { 10231 return pkg.mRealPackage; 10232 } 10233 return null; 10234 } 10235 10236 /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */ 10237 private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg, 10238 @Nullable String renamedPkgName) { 10239 return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName); 10240 } 10241 10242 /** 10243 * Returns the original package setting. 10244 * <p>A package can migrate its name during an update. In this scenario, a package 10245 * designates a set of names that it considers as one of its original names. 10246 * <p>An original package must be signed identically and it must have the same 10247 * shared user [if any]. 10248 */ 10249 @GuardedBy("mPackages") 10250 private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg, 10251 @Nullable String renamedPkgName) { 10252 if (!isPackageRenamed(pkg, renamedPkgName)) { 10253 return null; 10254 } 10255 for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) { 10256 final PackageSetting originalPs = 10257 mSettings.getPackageLPr(pkg.mOriginalPackages.get(i)); 10258 if (originalPs != null) { 10259 // the package is already installed under its original name... 10260 // but, should we use it? 10261 if (!verifyPackageUpdateLPr(originalPs, pkg)) { 10262 // the new package is incompatible with the original 10263 continue; 10264 } else if (originalPs.sharedUser != null) { 10265 if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) { 10266 // the shared user id is incompatible with the original 10267 Slog.w(TAG, "Unable to migrate data from " + originalPs.name 10268 + " to " + pkg.packageName + ": old uid " 10269 + originalPs.sharedUser.name 10270 + " differs from " + pkg.mSharedUserId); 10271 continue; 10272 } 10273 // TODO: Add case when shared user id is added [b/28144775] 10274 } else { 10275 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 10276 + pkg.packageName + " to old name " + originalPs.name); 10277 } 10278 return originalPs; 10279 } 10280 } 10281 return null; 10282 } 10283 10284 /** 10285 * Renames the package if it was installed under a different name. 10286 * <p>When we've already installed the package under an original name, update 10287 * the new package so we can continue to have the old name. 10288 */ 10289 private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg, 10290 @NonNull String renamedPackageName) { 10291 if (pkg.mOriginalPackages == null 10292 || !pkg.mOriginalPackages.contains(renamedPackageName) 10293 || pkg.packageName.equals(renamedPackageName)) { 10294 return; 10295 } 10296 pkg.setPackageName(renamedPackageName); 10297 } 10298 10299 /** 10300 * Just scans the package without any side effects. 10301 * <p>Not entirely true at the moment. There is still one side effect -- this 10302 * method potentially modifies a live {@link PackageSetting} object representing 10303 * the package being scanned. This will be resolved in the future. 10304 * 10305 * @param request Information about the package to be scanned 10306 * @param isUnderFactoryTest Whether or not the device is under factory test 10307 * @param currentTime The current time, in millis 10308 * @return The results of the scan 10309 */ 10310 @GuardedBy("mInstallLock") 10311 private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request, 10312 boolean isUnderFactoryTest, long currentTime) 10313 throws PackageManagerException { 10314 final PackageParser.Package pkg = request.pkg; 10315 PackageSetting pkgSetting = request.pkgSetting; 10316 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10317 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10318 final @ParseFlags int parseFlags = request.parseFlags; 10319 final @ScanFlags int scanFlags = request.scanFlags; 10320 final String realPkgName = request.realPkgName; 10321 final SharedUserSetting sharedUserSetting = request.sharedUserSetting; 10322 final UserHandle user = request.user; 10323 final boolean isPlatformPackage = request.isPlatformPackage; 10324 10325 List<String> changedAbiCodePath = null; 10326 10327 if (DEBUG_PACKAGE_SCANNING) { 10328 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10329 Log.d(TAG, "Scanning package " + pkg.packageName); 10330 } 10331 10332 if (Build.IS_DEBUGGABLE && 10333 pkg.isPrivileged() && 10334 !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) { 10335 PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg); 10336 } 10337 10338 // Initialize package source and resource directories 10339 final File scanFile = new File(pkg.codePath); 10340 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 10341 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 10342 10343 // We keep references to the derived CPU Abis from settings in oder to reuse 10344 // them in the case where we're not upgrading or booting for the first time. 10345 String primaryCpuAbiFromSettings = null; 10346 String secondaryCpuAbiFromSettings = null; 10347 boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0; 10348 10349 if (!needToDeriveAbi) { 10350 if (pkgSetting != null) { 10351 primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString; 10352 secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString; 10353 } else { 10354 // Re-scanning a system package after uninstalling updates; need to derive ABI 10355 needToDeriveAbi = true; 10356 } 10357 } 10358 10359 if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) { 10360 PackageManagerService.reportSettingsProblem(Log.WARN, 10361 "Package " + pkg.packageName + " shared user changed from " 10362 + (pkgSetting.sharedUser != null 10363 ? pkgSetting.sharedUser.name : "<nothing>") 10364 + " to " 10365 + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>") 10366 + "; replacing with new"); 10367 pkgSetting = null; 10368 } 10369 10370 String[] usesStaticLibraries = null; 10371 if (pkg.usesStaticLibraries != null) { 10372 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 10373 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 10374 } 10375 final boolean createNewPackage = (pkgSetting == null); 10376 if (createNewPackage) { 10377 final String parentPackageName = (pkg.parentPackage != null) 10378 ? pkg.parentPackage.packageName : null; 10379 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10380 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0; 10381 // REMOVE SharedUserSetting from method; update in a separate call 10382 pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting, 10383 disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile, 10384 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 10385 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10386 pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10387 user, true /*allowInstall*/, instantApp, virtualPreload, 10388 parentPackageName, pkg.getChildPackageNames(), 10389 UserManagerService.getInstance(), usesStaticLibraries, 10390 pkg.usesStaticLibrariesVersions); 10391 } else { 10392 // REMOVE SharedUserSetting from method; update in a separate call. 10393 // 10394 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 10395 // secondaryCpuAbi are not known at this point so we always update them 10396 // to null here, only to reset them at a later point. 10397 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting, 10398 destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir, 10399 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10400 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10401 pkg.getChildPackageNames(), UserManagerService.getInstance(), 10402 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 10403 } 10404 if (createNewPackage && originalPkgSetting != null) { 10405 // This is the initial transition from the original package, so, 10406 // fix up the new package's name now. We must do this after looking 10407 // up the package under its new name, so getPackageLP takes care of 10408 // fiddling things correctly. 10409 pkg.setPackageName(originalPkgSetting.name); 10410 10411 // File a report about this. 10412 String msg = "New package " + pkgSetting.realName 10413 + " renamed to replace old package " + pkgSetting.name; 10414 reportSettingsProblem(Log.WARN, msg); 10415 } 10416 10417 if (disabledPkgSetting != null) { 10418 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10419 } 10420 10421 // SELinux sandboxes become more restrictive as targetSdkVersion increases. 10422 // To ensure that apps with sharedUserId are placed in the same selinux domain 10423 // without breaking any assumptions about access, put them into the least 10424 // restrictive targetSdkVersion=25 domain. 10425 // TODO(b/72290969): Base this on the actual targetSdkVersion(s) of the apps within the 10426 // sharedUserSetting, instead of defaulting to the least restrictive domain. 10427 final int targetSdk = (sharedUserSetting != null) ? 25 10428 : pkg.applicationInfo.targetSdkVersion; 10429 // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync. 10430 // They currently can be if the sharedUser apps are signed with the platform key. 10431 final boolean isPrivileged = (sharedUserSetting != null) ? sharedUserSetting.isPrivileged() 10432 : pkg.applicationInfo.isPrivilegedApp(); 10433 SELinuxMMAC.assignSeInfoValue(pkg, isPrivileged, targetSdk); 10434 10435 pkg.mExtras = pkgSetting; 10436 pkg.applicationInfo.processName = fixProcessName( 10437 pkg.applicationInfo.packageName, 10438 pkg.applicationInfo.processName); 10439 10440 if (!isPlatformPackage) { 10441 // Get all of our default paths setup 10442 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 10443 } 10444 10445 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 10446 10447 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 10448 if (needToDeriveAbi) { 10449 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 10450 final boolean extractNativeLibs = !pkg.isLibrary(); 10451 derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs); 10452 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10453 10454 // Some system apps still use directory structure for native libraries 10455 // in which case we might end up not detecting abi solely based on apk 10456 // structure. Try to detect abi based on directory structure. 10457 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 10458 pkg.applicationInfo.primaryCpuAbi == null) { 10459 setBundledAppAbisAndRoots(pkg, pkgSetting); 10460 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10461 } 10462 } else { 10463 // This is not a first boot or an upgrade, don't bother deriving the 10464 // ABI during the scan. Instead, trust the value that was stored in the 10465 // package setting. 10466 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 10467 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 10468 10469 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10470 10471 if (DEBUG_ABI_SELECTION) { 10472 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 10473 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 10474 pkg.applicationInfo.secondaryCpuAbi); 10475 } 10476 } 10477 } else { 10478 if ((scanFlags & SCAN_MOVE) != 0) { 10479 // We haven't run dex-opt for this move (since we've moved the compiled output too) 10480 // but we already have this packages package info in the PackageSetting. We just 10481 // use that and derive the native library path based on the new codepath. 10482 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 10483 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 10484 } 10485 10486 // Set native library paths again. For moves, the path will be updated based on the 10487 // ABIs we've determined above. For non-moves, the path will be updated based on the 10488 // ABIs we determined during compilation, but the path will depend on the final 10489 // package path (after the rename away from the stage path). 10490 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10491 } 10492 10493 // This is a special case for the "system" package, where the ABI is 10494 // dictated by the zygote configuration (and init.rc). We should keep track 10495 // of this ABI so that we can deal with "normal" applications that run under 10496 // the same UID correctly. 10497 if (isPlatformPackage) { 10498 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 10499 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 10500 } 10501 10502 // If there's a mismatch between the abi-override in the package setting 10503 // and the abiOverride specified for the install. Warn about this because we 10504 // would've already compiled the app without taking the package setting into 10505 // account. 10506 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 10507 if (cpuAbiOverride == null && pkg.packageName != null) { 10508 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 10509 " for package " + pkg.packageName); 10510 } 10511 } 10512 10513 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10514 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10515 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 10516 10517 // Copy the derived override back to the parsed package, so that we can 10518 // update the package settings accordingly. 10519 pkg.cpuAbiOverride = cpuAbiOverride; 10520 10521 if (DEBUG_ABI_SELECTION) { 10522 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName 10523 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 10524 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 10525 } 10526 10527 // Push the derived path down into PackageSettings so we know what to 10528 // clean up at uninstall time. 10529 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 10530 10531 if (DEBUG_ABI_SELECTION) { 10532 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 10533 " primary=" + pkg.applicationInfo.primaryCpuAbi + 10534 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 10535 } 10536 10537 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 10538 // We don't do this here during boot because we can do it all 10539 // at once after scanning all existing packages. 10540 // 10541 // We also do this *before* we perform dexopt on this package, so that 10542 // we can avoid redundant dexopts, and also to make sure we've got the 10543 // code and package path correct. 10544 changedAbiCodePath = 10545 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 10546 } 10547 10548 if (isUnderFactoryTest && pkg.requestedPermissions.contains( 10549 android.Manifest.permission.FACTORY_TEST)) { 10550 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 10551 } 10552 10553 if (isSystemApp(pkg)) { 10554 pkgSetting.isOrphaned = true; 10555 } 10556 10557 // Take care of first install / last update times. 10558 final long scanFileTime = getLastModifiedTime(pkg); 10559 if (currentTime != 0) { 10560 if (pkgSetting.firstInstallTime == 0) { 10561 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 10562 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 10563 pkgSetting.lastUpdateTime = currentTime; 10564 } 10565 } else if (pkgSetting.firstInstallTime == 0) { 10566 // We need *something*. Take time time stamp of the file. 10567 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 10568 } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 10569 if (scanFileTime != pkgSetting.timeStamp) { 10570 // A package on the system image has changed; consider this 10571 // to be an update. 10572 pkgSetting.lastUpdateTime = scanFileTime; 10573 } 10574 } 10575 pkgSetting.setTimeStamp(scanFileTime); 10576 10577 pkgSetting.pkg = pkg; 10578 pkgSetting.pkgFlags = pkg.applicationInfo.flags; 10579 if (pkg.getLongVersionCode() != pkgSetting.versionCode) { 10580 pkgSetting.versionCode = pkg.getLongVersionCode(); 10581 } 10582 // Update volume if needed 10583 final String volumeUuid = pkg.applicationInfo.volumeUuid; 10584 if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) { 10585 Slog.i(PackageManagerService.TAG, 10586 "Update" + (pkgSetting.isSystem() ? " system" : "") 10587 + " package " + pkg.packageName 10588 + " volume from " + pkgSetting.volumeUuid 10589 + " to " + volumeUuid); 10590 pkgSetting.volumeUuid = volumeUuid; 10591 } 10592 10593 return new ScanResult(true, pkgSetting, changedAbiCodePath); 10594 } 10595 10596 /** 10597 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 10598 */ 10599 private static boolean apkHasCode(String fileName) { 10600 StrictJarFile jarFile = null; 10601 try { 10602 jarFile = new StrictJarFile(fileName, 10603 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 10604 return jarFile.findEntry("classes.dex") != null; 10605 } catch (IOException ignore) { 10606 } finally { 10607 try { 10608 if (jarFile != null) { 10609 jarFile.close(); 10610 } 10611 } catch (IOException ignore) {} 10612 } 10613 return false; 10614 } 10615 10616 /** 10617 * Enforces code policy for the package. This ensures that if an APK has 10618 * declared hasCode="true" in its manifest that the APK actually contains 10619 * code. 10620 * 10621 * @throws PackageManagerException If bytecode could not be found when it should exist 10622 */ 10623 private static void assertCodePolicy(PackageParser.Package pkg) 10624 throws PackageManagerException { 10625 final boolean shouldHaveCode = 10626 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 10627 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 10628 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10629 "Package " + pkg.baseCodePath + " code is missing"); 10630 } 10631 10632 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 10633 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 10634 final boolean splitShouldHaveCode = 10635 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 10636 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 10637 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10638 "Package " + pkg.splitCodePaths[i] + " code is missing"); 10639 } 10640 } 10641 } 10642 } 10643 10644 /** 10645 * Applies policy to the parsed package based upon the given policy flags. 10646 * Ensures the package is in a good state. 10647 * <p> 10648 * Implementation detail: This method must NOT have any side effect. It would 10649 * ideally be static, but, it requires locks to read system state. 10650 */ 10651 private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10652 final @ScanFlags int scanFlags) { 10653 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 10654 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 10655 if (pkg.applicationInfo.isDirectBootAware()) { 10656 // we're direct boot aware; set for all components 10657 for (PackageParser.Service s : pkg.services) { 10658 s.info.encryptionAware = s.info.directBootAware = true; 10659 } 10660 for (PackageParser.Provider p : pkg.providers) { 10661 p.info.encryptionAware = p.info.directBootAware = true; 10662 } 10663 for (PackageParser.Activity a : pkg.activities) { 10664 a.info.encryptionAware = a.info.directBootAware = true; 10665 } 10666 for (PackageParser.Activity r : pkg.receivers) { 10667 r.info.encryptionAware = r.info.directBootAware = true; 10668 } 10669 } 10670 if (compressedFileExists(pkg.codePath)) { 10671 pkg.isStub = true; 10672 } 10673 } else { 10674 // non system apps can't be flagged as core 10675 pkg.coreApp = false; 10676 // clear flags not applicable to regular apps 10677 pkg.applicationInfo.flags &= 10678 ~ApplicationInfo.FLAG_PERSISTENT; 10679 pkg.applicationInfo.privateFlags &= 10680 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10681 pkg.applicationInfo.privateFlags &= 10682 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10683 // clear protected broadcasts 10684 pkg.protectedBroadcasts = null; 10685 // cap permission priorities 10686 if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) { 10687 for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) { 10688 pkg.permissionGroups.get(i).info.priority = 0; 10689 } 10690 } 10691 } 10692 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10693 // ignore export request for single user receivers 10694 if (pkg.receivers != null) { 10695 for (int i = pkg.receivers.size() - 1; i >= 0; --i) { 10696 final PackageParser.Activity receiver = pkg.receivers.get(i); 10697 if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 10698 receiver.info.exported = false; 10699 } 10700 } 10701 } 10702 // ignore export request for single user services 10703 if (pkg.services != null) { 10704 for (int i = pkg.services.size() - 1; i >= 0; --i) { 10705 final PackageParser.Service service = pkg.services.get(i); 10706 if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 10707 service.info.exported = false; 10708 } 10709 } 10710 } 10711 // ignore export request for single user providers 10712 if (pkg.providers != null) { 10713 for (int i = pkg.providers.size() - 1; i >= 0; --i) { 10714 final PackageParser.Provider provider = pkg.providers.get(i); 10715 if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) { 10716 provider.info.exported = false; 10717 } 10718 } 10719 } 10720 } 10721 10722 if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) { 10723 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10724 } 10725 10726 if ((scanFlags & SCAN_AS_OEM) != 0) { 10727 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 10728 } 10729 10730 if ((scanFlags & SCAN_AS_VENDOR) != 0) { 10731 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR; 10732 } 10733 10734 if ((scanFlags & SCAN_AS_PRODUCT) != 0) { 10735 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT; 10736 } 10737 10738 if (!isSystemApp(pkg)) { 10739 // Only system apps can use these features. 10740 pkg.mOriginalPackages = null; 10741 pkg.mRealPackage = null; 10742 pkg.mAdoptPermissions = null; 10743 } 10744 } 10745 10746 private static @NonNull <T> T assertNotNull(@Nullable T object, String message) 10747 throws PackageManagerException { 10748 if (object == null) { 10749 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message); 10750 } 10751 return object; 10752 } 10753 10754 /** 10755 * Asserts the parsed package is valid according to the given policy. If the 10756 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10757 * <p> 10758 * Implementation detail: This method must NOT have any side effects. It would 10759 * ideally be static, but, it requires locks to read system state. 10760 * 10761 * @throws PackageManagerException If the package fails any of the validation checks 10762 */ 10763 private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10764 final @ScanFlags int scanFlags) 10765 throws PackageManagerException { 10766 if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10767 assertCodePolicy(pkg); 10768 } 10769 10770 if (pkg.applicationInfo.getCodePath() == null || 10771 pkg.applicationInfo.getResourcePath() == null) { 10772 // Bail out. The resource and code paths haven't been set. 10773 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10774 "Code and resource paths haven't been set correctly"); 10775 } 10776 10777 // Make sure we're not adding any bogus keyset info 10778 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10779 ksms.assertScannedPackageValid(pkg); 10780 10781 synchronized (mPackages) { 10782 // The special "android" package can only be defined once 10783 if (pkg.packageName.equals("android")) { 10784 if (mAndroidApplication != null) { 10785 Slog.w(TAG, "*************************************************"); 10786 Slog.w(TAG, "Core android package being redefined. Skipping."); 10787 Slog.w(TAG, " codePath=" + pkg.codePath); 10788 Slog.w(TAG, "*************************************************"); 10789 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10790 "Core android package being redefined. Skipping."); 10791 } 10792 } 10793 10794 // A package name must be unique; don't allow duplicates 10795 if (mPackages.containsKey(pkg.packageName)) { 10796 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10797 "Application package " + pkg.packageName 10798 + " already installed. Skipping duplicate."); 10799 } 10800 10801 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10802 // Static libs have a synthetic package name containing the version 10803 // but we still want the base name to be unique. 10804 if (mPackages.containsKey(pkg.manifestPackageName)) { 10805 throw new PackageManagerException( 10806 "Duplicate static shared lib provider package"); 10807 } 10808 10809 // Static shared libraries should have at least O target SDK 10810 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10811 throw new PackageManagerException( 10812 "Packages declaring static-shared libs must target O SDK or higher"); 10813 } 10814 10815 // Package declaring static a shared lib cannot be instant apps 10816 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10817 throw new PackageManagerException( 10818 "Packages declaring static-shared libs cannot be instant apps"); 10819 } 10820 10821 // Package declaring static a shared lib cannot be renamed since the package 10822 // name is synthetic and apps can't code around package manager internals. 10823 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10824 throw new PackageManagerException( 10825 "Packages declaring static-shared libs cannot be renamed"); 10826 } 10827 10828 // Package declaring static a shared lib cannot declare child packages 10829 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10830 throw new PackageManagerException( 10831 "Packages declaring static-shared libs cannot have child packages"); 10832 } 10833 10834 // Package declaring static a shared lib cannot declare dynamic libs 10835 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10836 throw new PackageManagerException( 10837 "Packages declaring static-shared libs cannot declare dynamic libs"); 10838 } 10839 10840 // Package declaring static a shared lib cannot declare shared users 10841 if (pkg.mSharedUserId != null) { 10842 throw new PackageManagerException( 10843 "Packages declaring static-shared libs cannot declare shared users"); 10844 } 10845 10846 // Static shared libs cannot declare activities 10847 if (!pkg.activities.isEmpty()) { 10848 throw new PackageManagerException( 10849 "Static shared libs cannot declare activities"); 10850 } 10851 10852 // Static shared libs cannot declare services 10853 if (!pkg.services.isEmpty()) { 10854 throw new PackageManagerException( 10855 "Static shared libs cannot declare services"); 10856 } 10857 10858 // Static shared libs cannot declare providers 10859 if (!pkg.providers.isEmpty()) { 10860 throw new PackageManagerException( 10861 "Static shared libs cannot declare content providers"); 10862 } 10863 10864 // Static shared libs cannot declare receivers 10865 if (!pkg.receivers.isEmpty()) { 10866 throw new PackageManagerException( 10867 "Static shared libs cannot declare broadcast receivers"); 10868 } 10869 10870 // Static shared libs cannot declare permission groups 10871 if (!pkg.permissionGroups.isEmpty()) { 10872 throw new PackageManagerException( 10873 "Static shared libs cannot declare permission groups"); 10874 } 10875 10876 // Static shared libs cannot declare permissions 10877 if (!pkg.permissions.isEmpty()) { 10878 throw new PackageManagerException( 10879 "Static shared libs cannot declare permissions"); 10880 } 10881 10882 // Static shared libs cannot declare protected broadcasts 10883 if (pkg.protectedBroadcasts != null) { 10884 throw new PackageManagerException( 10885 "Static shared libs cannot declare protected broadcasts"); 10886 } 10887 10888 // Static shared libs cannot be overlay targets 10889 if (pkg.mOverlayTarget != null) { 10890 throw new PackageManagerException( 10891 "Static shared libs cannot be overlay targets"); 10892 } 10893 10894 // The version codes must be ordered as lib versions 10895 long minVersionCode = Long.MIN_VALUE; 10896 long maxVersionCode = Long.MAX_VALUE; 10897 10898 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10899 pkg.staticSharedLibName); 10900 if (versionedLib != null) { 10901 final int versionCount = versionedLib.size(); 10902 for (int i = 0; i < versionCount; i++) { 10903 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10904 final long libVersionCode = libInfo.getDeclaringPackage() 10905 .getLongVersionCode(); 10906 if (libInfo.getLongVersion() < pkg.staticSharedLibVersion) { 10907 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10908 } else if (libInfo.getLongVersion() > pkg.staticSharedLibVersion) { 10909 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10910 } else { 10911 minVersionCode = maxVersionCode = libVersionCode; 10912 break; 10913 } 10914 } 10915 } 10916 if (pkg.getLongVersionCode() < minVersionCode 10917 || pkg.getLongVersionCode() > maxVersionCode) { 10918 throw new PackageManagerException("Static shared" 10919 + " lib version codes must be ordered as lib versions"); 10920 } 10921 } 10922 10923 // Only privileged apps and updated privileged apps can add child packages. 10924 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10925 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10926 throw new PackageManagerException("Only privileged apps can add child " 10927 + "packages. Ignoring package " + pkg.packageName); 10928 } 10929 final int childCount = pkg.childPackages.size(); 10930 for (int i = 0; i < childCount; i++) { 10931 PackageParser.Package childPkg = pkg.childPackages.get(i); 10932 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10933 childPkg.packageName)) { 10934 throw new PackageManagerException("Can't override child of " 10935 + "another disabled app. Ignoring package " + pkg.packageName); 10936 } 10937 } 10938 } 10939 10940 // If we're only installing presumed-existing packages, require that the 10941 // scanned APK is both already known and at the path previously established 10942 // for it. Previously unknown packages we pick up normally, but if we have an 10943 // a priori expectation about this package's install presence, enforce it. 10944 // With a singular exception for new system packages. When an OTA contains 10945 // a new system package, we allow the codepath to change from a system location 10946 // to the user-installed location. If we don't allow this change, any newer, 10947 // user-installed version of the application will be ignored. 10948 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10949 if (mExpectingBetter.containsKey(pkg.packageName)) { 10950 logCriticalInfo(Log.WARN, 10951 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10952 } else { 10953 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10954 if (known != null) { 10955 if (DEBUG_PACKAGE_SCANNING) { 10956 Log.d(TAG, "Examining " + pkg.codePath 10957 + " and requiring known paths " + known.codePathString 10958 + " & " + known.resourcePathString); 10959 } 10960 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10961 || !pkg.applicationInfo.getResourcePath().equals( 10962 known.resourcePathString)) { 10963 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10964 "Application package " + pkg.packageName 10965 + " found at " + pkg.applicationInfo.getCodePath() 10966 + " but expected at " + known.codePathString 10967 + "; ignoring."); 10968 } 10969 } else { 10970 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10971 "Application package " + pkg.packageName 10972 + " not found; ignoring."); 10973 } 10974 } 10975 } 10976 10977 // Verify that this new package doesn't have any content providers 10978 // that conflict with existing packages. Only do this if the 10979 // package isn't already installed, since we don't want to break 10980 // things that are installed. 10981 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 10982 final int N = pkg.providers.size(); 10983 int i; 10984 for (i=0; i<N; i++) { 10985 PackageParser.Provider p = pkg.providers.get(i); 10986 if (p.info.authority != null) { 10987 String names[] = p.info.authority.split(";"); 10988 for (int j = 0; j < names.length; j++) { 10989 if (mProvidersByAuthority.containsKey(names[j])) { 10990 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10991 final String otherPackageName = 10992 ((other != null && other.getComponentName() != null) ? 10993 other.getComponentName().getPackageName() : "?"); 10994 throw new PackageManagerException( 10995 INSTALL_FAILED_CONFLICTING_PROVIDER, 10996 "Can't install because provider name " + names[j] 10997 + " (in package " + pkg.applicationInfo.packageName 10998 + ") is already used by " + otherPackageName); 10999 } 11000 } 11001 } 11002 } 11003 } 11004 11005 // Verify that packages sharing a user with a privileged app are marked as privileged. 11006 if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) { 11007 SharedUserSetting sharedUserSetting = null; 11008 try { 11009 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 11010 } catch (PackageManagerException ignore) {} 11011 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 11012 // Exempt SharedUsers signed with the platform key. 11013 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 11014 if ((platformPkgSetting.signatures.mSigningDetails 11015 != PackageParser.SigningDetails.UNKNOWN) 11016 && (compareSignatures( 11017 platformPkgSetting.signatures.mSigningDetails.signatures, 11018 pkg.mSigningDetails.signatures) 11019 != PackageManager.SIGNATURE_MATCH)) { 11020 throw new PackageManagerException("Apps that share a user with a " + 11021 "privileged app must themselves be marked as privileged. " + 11022 pkg.packageName + " shares privileged user " + 11023 pkg.mSharedUserId + "."); 11024 } 11025 } 11026 } 11027 11028 // Apply policies specific for runtime resource overlays (RROs). 11029 if (pkg.mOverlayTarget != null) { 11030 // System overlays have some restrictions on their use of the 'static' state. 11031 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 11032 // We are scanning a system overlay. This can be the first scan of the 11033 // system/vendor/oem partition, or an update to the system overlay. 11034 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 11035 // This must be an update to a system overlay. 11036 final PackageSetting previousPkg = assertNotNull( 11037 mSettings.getPackageLPr(pkg.packageName), 11038 "previous package state not present"); 11039 11040 // Static overlays cannot be updated. 11041 if (previousPkg.pkg.mOverlayIsStatic) { 11042 throw new PackageManagerException("Overlay " + pkg.packageName + 11043 " is static and cannot be upgraded."); 11044 // Non-static overlays cannot be converted to static overlays. 11045 } else if (pkg.mOverlayIsStatic) { 11046 throw new PackageManagerException("Overlay " + pkg.packageName + 11047 " cannot be upgraded into a static overlay."); 11048 } 11049 } 11050 } else { 11051 // The overlay is a non-system overlay. Non-system overlays cannot be static. 11052 if (pkg.mOverlayIsStatic) { 11053 throw new PackageManagerException("Overlay " + pkg.packageName + 11054 " is static but not pre-installed."); 11055 } 11056 11057 // The only case where we allow installation of a non-system overlay is when 11058 // its signature is signed with the platform certificate. 11059 PackageSetting platformPkgSetting = mSettings.getPackageLPr("android"); 11060 if ((platformPkgSetting.signatures.mSigningDetails 11061 != PackageParser.SigningDetails.UNKNOWN) 11062 && (compareSignatures( 11063 platformPkgSetting.signatures.mSigningDetails.signatures, 11064 pkg.mSigningDetails.signatures) 11065 != PackageManager.SIGNATURE_MATCH)) { 11066 throw new PackageManagerException("Overlay " + pkg.packageName + 11067 " must be signed with the platform certificate."); 11068 } 11069 } 11070 } 11071 } 11072 } 11073 11074 private boolean addSharedLibraryLPw(String path, String apk, String name, long version, 11075 int type, String declaringPackageName, long declaringVersionCode) { 11076 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11077 if (versionedLib == null) { 11078 versionedLib = new LongSparseArray<>(); 11079 mSharedLibraries.put(name, versionedLib); 11080 if (type == SharedLibraryInfo.TYPE_STATIC) { 11081 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 11082 } 11083 } else if (versionedLib.indexOfKey(version) >= 0) { 11084 return false; 11085 } 11086 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 11087 version, type, declaringPackageName, declaringVersionCode); 11088 versionedLib.put(version, libEntry); 11089 return true; 11090 } 11091 11092 private boolean removeSharedLibraryLPw(String name, long version) { 11093 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11094 if (versionedLib == null) { 11095 return false; 11096 } 11097 final int libIdx = versionedLib.indexOfKey(version); 11098 if (libIdx < 0) { 11099 return false; 11100 } 11101 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 11102 versionedLib.remove(version); 11103 if (versionedLib.size() <= 0) { 11104 mSharedLibraries.remove(name); 11105 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 11106 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 11107 .getPackageName()); 11108 } 11109 } 11110 return true; 11111 } 11112 11113 /** 11114 * Adds a scanned package to the system. When this method is finished, the package will 11115 * be available for query, resolution, etc... 11116 */ 11117 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 11118 UserHandle user, final @ScanFlags int scanFlags, boolean chatty) { 11119 final String pkgName = pkg.packageName; 11120 if (mCustomResolverComponentName != null && 11121 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 11122 setUpCustomResolverActivity(pkg); 11123 } 11124 11125 if (pkg.packageName.equals("android")) { 11126 synchronized (mPackages) { 11127 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 11128 // Set up information for our fall-back user intent resolution activity. 11129 mPlatformPackage = pkg; 11130 pkg.mVersionCode = mSdkVersion; 11131 pkg.mVersionCodeMajor = 0; 11132 mAndroidApplication = pkg.applicationInfo; 11133 if (!mResolverReplaced) { 11134 mResolveActivity.applicationInfo = mAndroidApplication; 11135 mResolveActivity.name = ResolverActivity.class.getName(); 11136 mResolveActivity.packageName = mAndroidApplication.packageName; 11137 mResolveActivity.processName = "system:ui"; 11138 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11139 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 11140 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 11141 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 11142 mResolveActivity.exported = true; 11143 mResolveActivity.enabled = true; 11144 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 11145 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 11146 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 11147 | ActivityInfo.CONFIG_SCREEN_LAYOUT 11148 | ActivityInfo.CONFIG_ORIENTATION 11149 | ActivityInfo.CONFIG_KEYBOARD 11150 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 11151 mResolveInfo.activityInfo = mResolveActivity; 11152 mResolveInfo.priority = 0; 11153 mResolveInfo.preferredOrder = 0; 11154 mResolveInfo.match = 0; 11155 mResolveComponentName = new ComponentName( 11156 mAndroidApplication.packageName, mResolveActivity.name); 11157 } 11158 } 11159 } 11160 } 11161 11162 ArrayList<PackageParser.Package> clientLibPkgs = null; 11163 // writer 11164 synchronized (mPackages) { 11165 boolean hasStaticSharedLibs = false; 11166 11167 // Any app can add new static shared libraries 11168 if (pkg.staticSharedLibName != null) { 11169 // Static shared libs don't allow renaming as they have synthetic package 11170 // names to allow install of multiple versions, so use name from manifest. 11171 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 11172 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 11173 pkg.manifestPackageName, pkg.getLongVersionCode())) { 11174 hasStaticSharedLibs = true; 11175 } else { 11176 Slog.w(TAG, "Package " + pkg.packageName + " library " 11177 + pkg.staticSharedLibName + " already exists; skipping"); 11178 } 11179 // Static shared libs cannot be updated once installed since they 11180 // use synthetic package name which includes the version code, so 11181 // not need to update other packages's shared lib dependencies. 11182 } 11183 11184 if (!hasStaticSharedLibs 11185 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11186 // Only system apps can add new dynamic shared libraries. 11187 if (pkg.libraryNames != null) { 11188 for (int i = 0; i < pkg.libraryNames.size(); i++) { 11189 String name = pkg.libraryNames.get(i); 11190 boolean allowed = false; 11191 if (pkg.isUpdatedSystemApp()) { 11192 // New library entries can only be added through the 11193 // system image. This is important to get rid of a lot 11194 // of nasty edge cases: for example if we allowed a non- 11195 // system update of the app to add a library, then uninstalling 11196 // the update would make the library go away, and assumptions 11197 // we made such as through app install filtering would now 11198 // have allowed apps on the device which aren't compatible 11199 // with it. Better to just have the restriction here, be 11200 // conservative, and create many fewer cases that can negatively 11201 // impact the user experience. 11202 final PackageSetting sysPs = mSettings 11203 .getDisabledSystemPkgLPr(pkg.packageName); 11204 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 11205 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 11206 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 11207 allowed = true; 11208 break; 11209 } 11210 } 11211 } 11212 } else { 11213 allowed = true; 11214 } 11215 if (allowed) { 11216 if (!addSharedLibraryLPw(null, pkg.packageName, name, 11217 SharedLibraryInfo.VERSION_UNDEFINED, 11218 SharedLibraryInfo.TYPE_DYNAMIC, 11219 pkg.packageName, pkg.getLongVersionCode())) { 11220 Slog.w(TAG, "Package " + pkg.packageName + " library " 11221 + name + " already exists; skipping"); 11222 } 11223 } else { 11224 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 11225 + name + " that is not declared on system image; skipping"); 11226 } 11227 } 11228 11229 if ((scanFlags & SCAN_BOOTING) == 0) { 11230 // If we are not booting, we need to update any applications 11231 // that are clients of our shared library. If we are booting, 11232 // this will all be done once the scan is complete. 11233 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 11234 } 11235 } 11236 } 11237 } 11238 11239 if ((scanFlags & SCAN_BOOTING) != 0) { 11240 // No apps can run during boot scan, so they don't need to be frozen 11241 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 11242 // Caller asked to not kill app, so it's probably not frozen 11243 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 11244 // Caller asked us to ignore frozen check for some reason; they 11245 // probably didn't know the package name 11246 } else { 11247 // We're doing major surgery on this package, so it better be frozen 11248 // right now to keep it from launching 11249 checkPackageFrozen(pkgName); 11250 } 11251 11252 // Also need to kill any apps that are dependent on the library. 11253 if (clientLibPkgs != null) { 11254 for (int i=0; i<clientLibPkgs.size(); i++) { 11255 PackageParser.Package clientPkg = clientLibPkgs.get(i); 11256 killApplication(clientPkg.applicationInfo.packageName, 11257 clientPkg.applicationInfo.uid, "update lib"); 11258 } 11259 } 11260 11261 // writer 11262 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 11263 11264 synchronized (mPackages) { 11265 // We don't expect installation to fail beyond this point 11266 11267 // Add the new setting to mSettings 11268 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 11269 // Add the new setting to mPackages 11270 mPackages.put(pkg.applicationInfo.packageName, pkg); 11271 // Make sure we don't accidentally delete its data. 11272 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 11273 while (iter.hasNext()) { 11274 PackageCleanItem item = iter.next(); 11275 if (pkgName.equals(item.packageName)) { 11276 iter.remove(); 11277 } 11278 } 11279 11280 // Add the package's KeySets to the global KeySetManagerService 11281 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11282 ksms.addScannedPackageLPw(pkg); 11283 11284 int N = pkg.providers.size(); 11285 StringBuilder r = null; 11286 int i; 11287 for (i=0; i<N; i++) { 11288 PackageParser.Provider p = pkg.providers.get(i); 11289 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 11290 p.info.processName); 11291 mProviders.addProvider(p); 11292 p.syncable = p.info.isSyncable; 11293 if (p.info.authority != null) { 11294 String names[] = p.info.authority.split(";"); 11295 p.info.authority = null; 11296 for (int j = 0; j < names.length; j++) { 11297 if (j == 1 && p.syncable) { 11298 // We only want the first authority for a provider to possibly be 11299 // syncable, so if we already added this provider using a different 11300 // authority clear the syncable flag. We copy the provider before 11301 // changing it because the mProviders object contains a reference 11302 // to a provider that we don't want to change. 11303 // Only do this for the second authority since the resulting provider 11304 // object can be the same for all future authorities for this provider. 11305 p = new PackageParser.Provider(p); 11306 p.syncable = false; 11307 } 11308 if (!mProvidersByAuthority.containsKey(names[j])) { 11309 mProvidersByAuthority.put(names[j], p); 11310 if (p.info.authority == null) { 11311 p.info.authority = names[j]; 11312 } else { 11313 p.info.authority = p.info.authority + ";" + names[j]; 11314 } 11315 if (DEBUG_PACKAGE_SCANNING) { 11316 if (chatty) 11317 Log.d(TAG, "Registered content provider: " + names[j] 11318 + ", className = " + p.info.name + ", isSyncable = " 11319 + p.info.isSyncable); 11320 } 11321 } else { 11322 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11323 Slog.w(TAG, "Skipping provider name " + names[j] + 11324 " (in package " + pkg.applicationInfo.packageName + 11325 "): name already used by " 11326 + ((other != null && other.getComponentName() != null) 11327 ? other.getComponentName().getPackageName() : "?")); 11328 } 11329 } 11330 } 11331 if (chatty) { 11332 if (r == null) { 11333 r = new StringBuilder(256); 11334 } else { 11335 r.append(' '); 11336 } 11337 r.append(p.info.name); 11338 } 11339 } 11340 if (r != null) { 11341 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 11342 } 11343 11344 N = pkg.services.size(); 11345 r = null; 11346 for (i=0; i<N; i++) { 11347 PackageParser.Service s = pkg.services.get(i); 11348 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 11349 s.info.processName); 11350 mServices.addService(s); 11351 if (chatty) { 11352 if (r == null) { 11353 r = new StringBuilder(256); 11354 } else { 11355 r.append(' '); 11356 } 11357 r.append(s.info.name); 11358 } 11359 } 11360 if (r != null) { 11361 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 11362 } 11363 11364 N = pkg.receivers.size(); 11365 r = null; 11366 for (i=0; i<N; i++) { 11367 PackageParser.Activity a = pkg.receivers.get(i); 11368 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11369 a.info.processName); 11370 mReceivers.addActivity(a, "receiver"); 11371 if (chatty) { 11372 if (r == null) { 11373 r = new StringBuilder(256); 11374 } else { 11375 r.append(' '); 11376 } 11377 r.append(a.info.name); 11378 } 11379 } 11380 if (r != null) { 11381 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 11382 } 11383 11384 N = pkg.activities.size(); 11385 r = null; 11386 for (i=0; i<N; i++) { 11387 PackageParser.Activity a = pkg.activities.get(i); 11388 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11389 a.info.processName); 11390 mActivities.addActivity(a, "activity"); 11391 if (chatty) { 11392 if (r == null) { 11393 r = new StringBuilder(256); 11394 } else { 11395 r.append(' '); 11396 } 11397 r.append(a.info.name); 11398 } 11399 } 11400 if (r != null) { 11401 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11402 } 11403 11404 // Don't allow ephemeral applications to define new permissions groups. 11405 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11406 Slog.w(TAG, "Permission groups from package " + pkg.packageName 11407 + " ignored: instant apps cannot define new permission groups."); 11408 } else { 11409 mPermissionManager.addAllPermissionGroups(pkg, chatty); 11410 } 11411 11412 // Don't allow ephemeral applications to define new permissions. 11413 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11414 Slog.w(TAG, "Permissions from package " + pkg.packageName 11415 + " ignored: instant apps cannot define new permissions."); 11416 } else { 11417 mPermissionManager.addAllPermissions(pkg, chatty); 11418 } 11419 11420 N = pkg.instrumentation.size(); 11421 r = null; 11422 for (i=0; i<N; i++) { 11423 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11424 a.info.packageName = pkg.applicationInfo.packageName; 11425 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11426 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11427 a.info.splitNames = pkg.splitNames; 11428 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11429 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11430 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11431 a.info.dataDir = pkg.applicationInfo.dataDir; 11432 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11433 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11434 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11435 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11436 mInstrumentation.put(a.getComponentName(), a); 11437 if (chatty) { 11438 if (r == null) { 11439 r = new StringBuilder(256); 11440 } else { 11441 r.append(' '); 11442 } 11443 r.append(a.info.name); 11444 } 11445 } 11446 if (r != null) { 11447 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11448 } 11449 11450 if (pkg.protectedBroadcasts != null) { 11451 N = pkg.protectedBroadcasts.size(); 11452 synchronized (mProtectedBroadcasts) { 11453 for (i = 0; i < N; i++) { 11454 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 11455 } 11456 } 11457 } 11458 } 11459 11460 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11461 } 11462 11463 /** 11464 * Derive the ABI of a non-system package located at {@code scanFile}. This information 11465 * is derived purely on the basis of the contents of {@code scanFile} and 11466 * {@code cpuAbiOverride}. 11467 * 11468 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 11469 */ 11470 private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride, 11471 boolean extractLibs) 11472 throws PackageManagerException { 11473 // Give ourselves some initial paths; we'll come back for another 11474 // pass once we've determined ABI below. 11475 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11476 11477 // We would never need to extract libs for forward-locked and external packages, 11478 // since the container service will do it for us. We shouldn't attempt to 11479 // extract libs from system app when it was not updated. 11480 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 11481 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 11482 extractLibs = false; 11483 } 11484 11485 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 11486 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 11487 11488 NativeLibraryHelper.Handle handle = null; 11489 try { 11490 handle = NativeLibraryHelper.Handle.create(pkg); 11491 // TODO(multiArch): This can be null for apps that didn't go through the 11492 // usual installation process. We can calculate it again, like we 11493 // do during install time. 11494 // 11495 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 11496 // unnecessary. 11497 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 11498 11499 // Null out the abis so that they can be recalculated. 11500 pkg.applicationInfo.primaryCpuAbi = null; 11501 pkg.applicationInfo.secondaryCpuAbi = null; 11502 if (isMultiArch(pkg.applicationInfo)) { 11503 // Warn if we've set an abiOverride for multi-lib packages.. 11504 // By definition, we need to copy both 32 and 64 bit libraries for 11505 // such packages. 11506 if (pkg.cpuAbiOverride != null 11507 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 11508 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 11509 } 11510 11511 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 11512 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 11513 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 11514 if (extractLibs) { 11515 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11516 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11517 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 11518 useIsaSpecificSubdirs); 11519 } else { 11520 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11521 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 11522 } 11523 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11524 } 11525 11526 // Shared library native code should be in the APK zip aligned 11527 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 11528 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11529 "Shared library native lib extraction not supported"); 11530 } 11531 11532 maybeThrowExceptionForMultiArchCopy( 11533 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 11534 11535 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 11536 if (extractLibs) { 11537 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11538 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11539 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 11540 useIsaSpecificSubdirs); 11541 } else { 11542 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11543 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 11544 } 11545 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11546 } 11547 11548 maybeThrowExceptionForMultiArchCopy( 11549 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 11550 11551 if (abi64 >= 0) { 11552 // Shared library native libs should be in the APK zip aligned 11553 if (extractLibs && pkg.isLibrary()) { 11554 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11555 "Shared library native lib extraction not supported"); 11556 } 11557 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11558 } 11559 11560 if (abi32 >= 0) { 11561 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11562 if (abi64 >= 0) { 11563 if (pkg.use32bitAbi) { 11564 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11565 pkg.applicationInfo.primaryCpuAbi = abi; 11566 } else { 11567 pkg.applicationInfo.secondaryCpuAbi = abi; 11568 } 11569 } else { 11570 pkg.applicationInfo.primaryCpuAbi = abi; 11571 } 11572 } 11573 } else { 11574 String[] abiList = (cpuAbiOverride != null) ? 11575 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11576 11577 // Enable gross and lame hacks for apps that are built with old 11578 // SDK tools. We must scan their APKs for renderscript bitcode and 11579 // not launch them if it's present. Don't bother checking on devices 11580 // that don't have 64 bit support. 11581 boolean needsRenderScriptOverride = false; 11582 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11583 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11584 abiList = Build.SUPPORTED_32_BIT_ABIS; 11585 needsRenderScriptOverride = true; 11586 } 11587 11588 final int copyRet; 11589 if (extractLibs) { 11590 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11591 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11592 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11593 } else { 11594 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11595 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11596 } 11597 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11598 11599 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11600 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11601 "Error unpackaging native libs for app, errorCode=" + copyRet); 11602 } 11603 11604 if (copyRet >= 0) { 11605 // Shared libraries that have native libs must be multi-architecture 11606 if (pkg.isLibrary()) { 11607 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11608 "Shared library with native libs must be multiarch"); 11609 } 11610 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11611 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11612 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11613 } else if (needsRenderScriptOverride) { 11614 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11615 } 11616 } 11617 } catch (IOException ioe) { 11618 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11619 } finally { 11620 IoUtils.closeQuietly(handle); 11621 } 11622 11623 // Now that we've calculated the ABIs and determined if it's an internal app, 11624 // we will go ahead and populate the nativeLibraryPath. 11625 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11626 } 11627 11628 /** 11629 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11630 * i.e, so that all packages can be run inside a single process if required. 11631 * 11632 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11633 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11634 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11635 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11636 * updating a package that belongs to a shared user. 11637 * 11638 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11639 * adds unnecessary complexity. 11640 */ 11641 private static @Nullable List<String> adjustCpuAbisForSharedUserLPw( 11642 Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) { 11643 List<String> changedAbiCodePath = null; 11644 String requiredInstructionSet = null; 11645 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11646 requiredInstructionSet = VMRuntime.getInstructionSet( 11647 scannedPackage.applicationInfo.primaryCpuAbi); 11648 } 11649 11650 PackageSetting requirer = null; 11651 for (PackageSetting ps : packagesForUser) { 11652 // If packagesForUser contains scannedPackage, we skip it. This will happen 11653 // when scannedPackage is an update of an existing package. Without this check, 11654 // we will never be able to change the ABI of any package belonging to a shared 11655 // user, even if it's compatible with other packages. 11656 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11657 if (ps.primaryCpuAbiString == null) { 11658 continue; 11659 } 11660 11661 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11662 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11663 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11664 // this but there's not much we can do. 11665 String errorMessage = "Instruction set mismatch, " 11666 + ((requirer == null) ? "[caller]" : requirer) 11667 + " requires " + requiredInstructionSet + " whereas " + ps 11668 + " requires " + instructionSet; 11669 Slog.w(TAG, errorMessage); 11670 } 11671 11672 if (requiredInstructionSet == null) { 11673 requiredInstructionSet = instructionSet; 11674 requirer = ps; 11675 } 11676 } 11677 } 11678 11679 if (requiredInstructionSet != null) { 11680 String adjustedAbi; 11681 if (requirer != null) { 11682 // requirer != null implies that either scannedPackage was null or that scannedPackage 11683 // did not require an ABI, in which case we have to adjust scannedPackage to match 11684 // the ABI of the set (which is the same as requirer's ABI) 11685 adjustedAbi = requirer.primaryCpuAbiString; 11686 if (scannedPackage != null) { 11687 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11688 } 11689 } else { 11690 // requirer == null implies that we're updating all ABIs in the set to 11691 // match scannedPackage. 11692 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11693 } 11694 11695 for (PackageSetting ps : packagesForUser) { 11696 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11697 if (ps.primaryCpuAbiString != null) { 11698 continue; 11699 } 11700 11701 ps.primaryCpuAbiString = adjustedAbi; 11702 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11703 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11704 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11705 if (DEBUG_ABI_SELECTION) { 11706 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11707 + " (requirer=" 11708 + (requirer != null ? requirer.pkg : "null") 11709 + ", scannedPackage=" 11710 + (scannedPackage != null ? scannedPackage : "null") 11711 + ")"); 11712 } 11713 if (changedAbiCodePath == null) { 11714 changedAbiCodePath = new ArrayList<>(); 11715 } 11716 changedAbiCodePath.add(ps.codePathString); 11717 } 11718 } 11719 } 11720 } 11721 return changedAbiCodePath; 11722 } 11723 11724 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11725 synchronized (mPackages) { 11726 mResolverReplaced = true; 11727 // Set up information for custom user intent resolution activity. 11728 mResolveActivity.applicationInfo = pkg.applicationInfo; 11729 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11730 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11731 mResolveActivity.processName = pkg.applicationInfo.packageName; 11732 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11733 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11734 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11735 mResolveActivity.theme = 0; 11736 mResolveActivity.exported = true; 11737 mResolveActivity.enabled = true; 11738 mResolveInfo.activityInfo = mResolveActivity; 11739 mResolveInfo.priority = 0; 11740 mResolveInfo.preferredOrder = 0; 11741 mResolveInfo.match = 0; 11742 mResolveComponentName = mCustomResolverComponentName; 11743 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11744 mResolveComponentName); 11745 } 11746 } 11747 11748 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11749 if (installerActivity == null) { 11750 if (DEBUG_INSTANT) { 11751 Slog.d(TAG, "Clear ephemeral installer activity"); 11752 } 11753 mInstantAppInstallerActivity = null; 11754 return; 11755 } 11756 11757 if (DEBUG_INSTANT) { 11758 Slog.d(TAG, "Set ephemeral installer activity: " 11759 + installerActivity.getComponentName()); 11760 } 11761 // Set up information for ephemeral installer activity 11762 mInstantAppInstallerActivity = installerActivity; 11763 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11764 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11765 mInstantAppInstallerActivity.exported = true; 11766 mInstantAppInstallerActivity.enabled = true; 11767 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11768 mInstantAppInstallerInfo.priority = 1; 11769 mInstantAppInstallerInfo.preferredOrder = 1; 11770 mInstantAppInstallerInfo.isDefault = true; 11771 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11772 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11773 } 11774 11775 private static String calculateBundledApkRoot(final String codePathString) { 11776 final File codePath = new File(codePathString); 11777 final File codeRoot; 11778 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11779 codeRoot = Environment.getRootDirectory(); 11780 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11781 codeRoot = Environment.getOemDirectory(); 11782 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11783 codeRoot = Environment.getVendorDirectory(); 11784 } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) { 11785 codeRoot = Environment.getProductDirectory(); 11786 } else { 11787 // Unrecognized code path; take its top real segment as the apk root: 11788 // e.g. /something/app/blah.apk => /something 11789 try { 11790 File f = codePath.getCanonicalFile(); 11791 File parent = f.getParentFile(); // non-null because codePath is a file 11792 File tmp; 11793 while ((tmp = parent.getParentFile()) != null) { 11794 f = parent; 11795 parent = tmp; 11796 } 11797 codeRoot = f; 11798 Slog.w(TAG, "Unrecognized code path " 11799 + codePath + " - using " + codeRoot); 11800 } catch (IOException e) { 11801 // Can't canonicalize the code path -- shenanigans? 11802 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11803 return Environment.getRootDirectory().getPath(); 11804 } 11805 } 11806 return codeRoot.getPath(); 11807 } 11808 11809 /** 11810 * Derive and set the location of native libraries for the given package, 11811 * which varies depending on where and how the package was installed. 11812 */ 11813 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11814 final ApplicationInfo info = pkg.applicationInfo; 11815 final String codePath = pkg.codePath; 11816 final File codeFile = new File(codePath); 11817 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11818 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11819 11820 info.nativeLibraryRootDir = null; 11821 info.nativeLibraryRootRequiresIsa = false; 11822 info.nativeLibraryDir = null; 11823 info.secondaryNativeLibraryDir = null; 11824 11825 if (isApkFile(codeFile)) { 11826 // Monolithic install 11827 if (bundledApp) { 11828 // If "/system/lib64/apkname" exists, assume that is the per-package 11829 // native library directory to use; otherwise use "/system/lib/apkname". 11830 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11831 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11832 getPrimaryInstructionSet(info)); 11833 11834 // This is a bundled system app so choose the path based on the ABI. 11835 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11836 // is just the default path. 11837 final String apkName = deriveCodePathName(codePath); 11838 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11839 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11840 apkName).getAbsolutePath(); 11841 11842 if (info.secondaryCpuAbi != null) { 11843 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11844 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11845 secondaryLibDir, apkName).getAbsolutePath(); 11846 } 11847 } else if (asecApp) { 11848 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11849 .getAbsolutePath(); 11850 } else { 11851 final String apkName = deriveCodePathName(codePath); 11852 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11853 .getAbsolutePath(); 11854 } 11855 11856 info.nativeLibraryRootRequiresIsa = false; 11857 info.nativeLibraryDir = info.nativeLibraryRootDir; 11858 } else { 11859 // Cluster install 11860 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11861 info.nativeLibraryRootRequiresIsa = true; 11862 11863 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11864 getPrimaryInstructionSet(info)).getAbsolutePath(); 11865 11866 if (info.secondaryCpuAbi != null) { 11867 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11868 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11869 } 11870 } 11871 } 11872 11873 /** 11874 * Calculate the abis and roots for a bundled app. These can uniquely 11875 * be determined from the contents of the system partition, i.e whether 11876 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11877 * of this information, and instead assume that the system was built 11878 * sensibly. 11879 */ 11880 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11881 PackageSetting pkgSetting) { 11882 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11883 11884 // If "/system/lib64/apkname" exists, assume that is the per-package 11885 // native library directory to use; otherwise use "/system/lib/apkname". 11886 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11887 setBundledAppAbi(pkg, apkRoot, apkName); 11888 // pkgSetting might be null during rescan following uninstall of updates 11889 // to a bundled app, so accommodate that possibility. The settings in 11890 // that case will be established later from the parsed package. 11891 // 11892 // If the settings aren't null, sync them up with what we've just derived. 11893 // note that apkRoot isn't stored in the package settings. 11894 if (pkgSetting != null) { 11895 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11896 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11897 } 11898 } 11899 11900 /** 11901 * Deduces the ABI of a bundled app and sets the relevant fields on the 11902 * parsed pkg object. 11903 * 11904 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11905 * under which system libraries are installed. 11906 * @param apkName the name of the installed package. 11907 */ 11908 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11909 final File codeFile = new File(pkg.codePath); 11910 11911 final boolean has64BitLibs; 11912 final boolean has32BitLibs; 11913 if (isApkFile(codeFile)) { 11914 // Monolithic install 11915 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11916 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11917 } else { 11918 // Cluster install 11919 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11920 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11921 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11922 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11923 has64BitLibs = (new File(rootDir, isa)).exists(); 11924 } else { 11925 has64BitLibs = false; 11926 } 11927 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11928 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11929 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11930 has32BitLibs = (new File(rootDir, isa)).exists(); 11931 } else { 11932 has32BitLibs = false; 11933 } 11934 } 11935 11936 if (has64BitLibs && !has32BitLibs) { 11937 // The package has 64 bit libs, but not 32 bit libs. Its primary 11938 // ABI should be 64 bit. We can safely assume here that the bundled 11939 // native libraries correspond to the most preferred ABI in the list. 11940 11941 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11942 pkg.applicationInfo.secondaryCpuAbi = null; 11943 } else if (has32BitLibs && !has64BitLibs) { 11944 // The package has 32 bit libs but not 64 bit libs. Its primary 11945 // ABI should be 32 bit. 11946 11947 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11948 pkg.applicationInfo.secondaryCpuAbi = null; 11949 } else if (has32BitLibs && has64BitLibs) { 11950 // The application has both 64 and 32 bit bundled libraries. We check 11951 // here that the app declares multiArch support, and warn if it doesn't. 11952 // 11953 // We will be lenient here and record both ABIs. The primary will be the 11954 // ABI that's higher on the list, i.e, a device that's configured to prefer 11955 // 64 bit apps will see a 64 bit primary ABI, 11956 11957 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11958 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11959 } 11960 11961 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11962 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11963 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11964 } else { 11965 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11966 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11967 } 11968 } else { 11969 pkg.applicationInfo.primaryCpuAbi = null; 11970 pkg.applicationInfo.secondaryCpuAbi = null; 11971 } 11972 } 11973 11974 private void killApplication(String pkgName, int appId, String reason) { 11975 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11976 } 11977 11978 private void killApplication(String pkgName, int appId, int userId, String reason) { 11979 // Request the ActivityManager to kill the process(only for existing packages) 11980 // so that we do not end up in a confused state while the user is still using the older 11981 // version of the application while the new one gets installed. 11982 final long token = Binder.clearCallingIdentity(); 11983 try { 11984 IActivityManager am = ActivityManager.getService(); 11985 if (am != null) { 11986 try { 11987 am.killApplication(pkgName, appId, userId, reason); 11988 } catch (RemoteException e) { 11989 } 11990 } 11991 } finally { 11992 Binder.restoreCallingIdentity(token); 11993 } 11994 } 11995 11996 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 11997 // Remove the parent package setting 11998 PackageSetting ps = (PackageSetting) pkg.mExtras; 11999 if (ps != null) { 12000 removePackageLI(ps, chatty); 12001 } 12002 // Remove the child package setting 12003 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12004 for (int i = 0; i < childCount; i++) { 12005 PackageParser.Package childPkg = pkg.childPackages.get(i); 12006 ps = (PackageSetting) childPkg.mExtras; 12007 if (ps != null) { 12008 removePackageLI(ps, chatty); 12009 } 12010 } 12011 } 12012 12013 void removePackageLI(PackageSetting ps, boolean chatty) { 12014 if (DEBUG_INSTALL) { 12015 if (chatty) 12016 Log.d(TAG, "Removing package " + ps.name); 12017 } 12018 12019 // writer 12020 synchronized (mPackages) { 12021 mPackages.remove(ps.name); 12022 final PackageParser.Package pkg = ps.pkg; 12023 if (pkg != null) { 12024 cleanPackageDataStructuresLILPw(pkg, chatty); 12025 } 12026 } 12027 } 12028 12029 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 12030 if (DEBUG_INSTALL) { 12031 if (chatty) 12032 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 12033 } 12034 12035 // writer 12036 synchronized (mPackages) { 12037 // Remove the parent package 12038 mPackages.remove(pkg.applicationInfo.packageName); 12039 cleanPackageDataStructuresLILPw(pkg, chatty); 12040 12041 // Remove the child packages 12042 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12043 for (int i = 0; i < childCount; i++) { 12044 PackageParser.Package childPkg = pkg.childPackages.get(i); 12045 mPackages.remove(childPkg.applicationInfo.packageName); 12046 cleanPackageDataStructuresLILPw(childPkg, chatty); 12047 } 12048 } 12049 } 12050 12051 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 12052 int N = pkg.providers.size(); 12053 StringBuilder r = null; 12054 int i; 12055 for (i=0; i<N; i++) { 12056 PackageParser.Provider p = pkg.providers.get(i); 12057 mProviders.removeProvider(p); 12058 if (p.info.authority == null) { 12059 12060 /* There was another ContentProvider with this authority when 12061 * this app was installed so this authority is null, 12062 * Ignore it as we don't have to unregister the provider. 12063 */ 12064 continue; 12065 } 12066 String names[] = p.info.authority.split(";"); 12067 for (int j = 0; j < names.length; j++) { 12068 if (mProvidersByAuthority.get(names[j]) == p) { 12069 mProvidersByAuthority.remove(names[j]); 12070 if (DEBUG_REMOVE) { 12071 if (chatty) 12072 Log.d(TAG, "Unregistered content provider: " + names[j] 12073 + ", className = " + p.info.name + ", isSyncable = " 12074 + p.info.isSyncable); 12075 } 12076 } 12077 } 12078 if (DEBUG_REMOVE && chatty) { 12079 if (r == null) { 12080 r = new StringBuilder(256); 12081 } else { 12082 r.append(' '); 12083 } 12084 r.append(p.info.name); 12085 } 12086 } 12087 if (r != null) { 12088 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 12089 } 12090 12091 N = pkg.services.size(); 12092 r = null; 12093 for (i=0; i<N; i++) { 12094 PackageParser.Service s = pkg.services.get(i); 12095 mServices.removeService(s); 12096 if (chatty) { 12097 if (r == null) { 12098 r = new StringBuilder(256); 12099 } else { 12100 r.append(' '); 12101 } 12102 r.append(s.info.name); 12103 } 12104 } 12105 if (r != null) { 12106 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 12107 } 12108 12109 N = pkg.receivers.size(); 12110 r = null; 12111 for (i=0; i<N; i++) { 12112 PackageParser.Activity a = pkg.receivers.get(i); 12113 mReceivers.removeActivity(a, "receiver"); 12114 if (DEBUG_REMOVE && chatty) { 12115 if (r == null) { 12116 r = new StringBuilder(256); 12117 } else { 12118 r.append(' '); 12119 } 12120 r.append(a.info.name); 12121 } 12122 } 12123 if (r != null) { 12124 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 12125 } 12126 12127 N = pkg.activities.size(); 12128 r = null; 12129 for (i=0; i<N; i++) { 12130 PackageParser.Activity a = pkg.activities.get(i); 12131 mActivities.removeActivity(a, "activity"); 12132 if (DEBUG_REMOVE && chatty) { 12133 if (r == null) { 12134 r = new StringBuilder(256); 12135 } else { 12136 r.append(' '); 12137 } 12138 r.append(a.info.name); 12139 } 12140 } 12141 if (r != null) { 12142 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 12143 } 12144 12145 mPermissionManager.removeAllPermissions(pkg, chatty); 12146 12147 N = pkg.instrumentation.size(); 12148 r = null; 12149 for (i=0; i<N; i++) { 12150 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 12151 mInstrumentation.remove(a.getComponentName()); 12152 if (DEBUG_REMOVE && chatty) { 12153 if (r == null) { 12154 r = new StringBuilder(256); 12155 } else { 12156 r.append(' '); 12157 } 12158 r.append(a.info.name); 12159 } 12160 } 12161 if (r != null) { 12162 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 12163 } 12164 12165 r = null; 12166 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 12167 // Only system apps can hold shared libraries. 12168 if (pkg.libraryNames != null) { 12169 for (i = 0; i < pkg.libraryNames.size(); i++) { 12170 String name = pkg.libraryNames.get(i); 12171 if (removeSharedLibraryLPw(name, 0)) { 12172 if (DEBUG_REMOVE && chatty) { 12173 if (r == null) { 12174 r = new StringBuilder(256); 12175 } else { 12176 r.append(' '); 12177 } 12178 r.append(name); 12179 } 12180 } 12181 } 12182 } 12183 } 12184 12185 r = null; 12186 12187 // Any package can hold static shared libraries. 12188 if (pkg.staticSharedLibName != null) { 12189 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 12190 if (DEBUG_REMOVE && chatty) { 12191 if (r == null) { 12192 r = new StringBuilder(256); 12193 } else { 12194 r.append(' '); 12195 } 12196 r.append(pkg.staticSharedLibName); 12197 } 12198 } 12199 } 12200 12201 if (r != null) { 12202 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 12203 } 12204 } 12205 12206 12207 final class ActivityIntentResolver 12208 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 12209 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12210 boolean defaultOnly, int userId) { 12211 if (!sUserManager.exists(userId)) return null; 12212 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 12213 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12214 } 12215 12216 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12217 int userId) { 12218 if (!sUserManager.exists(userId)) return null; 12219 mFlags = flags; 12220 return super.queryIntent(intent, resolvedType, 12221 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12222 userId); 12223 } 12224 12225 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12226 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 12227 if (!sUserManager.exists(userId)) return null; 12228 if (packageActivities == null) { 12229 return null; 12230 } 12231 mFlags = flags; 12232 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12233 final int N = packageActivities.size(); 12234 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 12235 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 12236 12237 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 12238 for (int i = 0; i < N; ++i) { 12239 intentFilters = packageActivities.get(i).intents; 12240 if (intentFilters != null && intentFilters.size() > 0) { 12241 PackageParser.ActivityIntentInfo[] array = 12242 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 12243 intentFilters.toArray(array); 12244 listCut.add(array); 12245 } 12246 } 12247 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12248 } 12249 12250 /** 12251 * Finds a privileged activity that matches the specified activity names. 12252 */ 12253 private PackageParser.Activity findMatchingActivity( 12254 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 12255 for (PackageParser.Activity sysActivity : activityList) { 12256 if (sysActivity.info.name.equals(activityInfo.name)) { 12257 return sysActivity; 12258 } 12259 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 12260 return sysActivity; 12261 } 12262 if (sysActivity.info.targetActivity != null) { 12263 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 12264 return sysActivity; 12265 } 12266 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 12267 return sysActivity; 12268 } 12269 } 12270 } 12271 return null; 12272 } 12273 12274 public class IterGenerator<E> { 12275 public Iterator<E> generate(ActivityIntentInfo info) { 12276 return null; 12277 } 12278 } 12279 12280 public class ActionIterGenerator extends IterGenerator<String> { 12281 @Override 12282 public Iterator<String> generate(ActivityIntentInfo info) { 12283 return info.actionsIterator(); 12284 } 12285 } 12286 12287 public class CategoriesIterGenerator extends IterGenerator<String> { 12288 @Override 12289 public Iterator<String> generate(ActivityIntentInfo info) { 12290 return info.categoriesIterator(); 12291 } 12292 } 12293 12294 public class SchemesIterGenerator extends IterGenerator<String> { 12295 @Override 12296 public Iterator<String> generate(ActivityIntentInfo info) { 12297 return info.schemesIterator(); 12298 } 12299 } 12300 12301 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 12302 @Override 12303 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 12304 return info.authoritiesIterator(); 12305 } 12306 } 12307 12308 /** 12309 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12310 * MODIFIED. Do not pass in a list that should not be changed. 12311 */ 12312 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12313 IterGenerator<T> generator, Iterator<T> searchIterator) { 12314 // loop through the set of actions; every one must be found in the intent filter 12315 while (searchIterator.hasNext()) { 12316 // we must have at least one filter in the list to consider a match 12317 if (intentList.size() == 0) { 12318 break; 12319 } 12320 12321 final T searchAction = searchIterator.next(); 12322 12323 // loop through the set of intent filters 12324 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12325 while (intentIter.hasNext()) { 12326 final ActivityIntentInfo intentInfo = intentIter.next(); 12327 boolean selectionFound = false; 12328 12329 // loop through the intent filter's selection criteria; at least one 12330 // of them must match the searched criteria 12331 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12332 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12333 final T intentSelection = intentSelectionIter.next(); 12334 if (intentSelection != null && intentSelection.equals(searchAction)) { 12335 selectionFound = true; 12336 break; 12337 } 12338 } 12339 12340 // the selection criteria wasn't found in this filter's set; this filter 12341 // is not a potential match 12342 if (!selectionFound) { 12343 intentIter.remove(); 12344 } 12345 } 12346 } 12347 } 12348 12349 private boolean isProtectedAction(ActivityIntentInfo filter) { 12350 final Iterator<String> actionsIter = filter.actionsIterator(); 12351 while (actionsIter != null && actionsIter.hasNext()) { 12352 final String filterAction = actionsIter.next(); 12353 if (PROTECTED_ACTIONS.contains(filterAction)) { 12354 return true; 12355 } 12356 } 12357 return false; 12358 } 12359 12360 /** 12361 * Adjusts the priority of the given intent filter according to policy. 12362 * <p> 12363 * <ul> 12364 * <li>The priority for non privileged applications is capped to '0'</li> 12365 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12366 * <li>The priority for unbundled updates to privileged applications is capped to the 12367 * priority defined on the system partition</li> 12368 * </ul> 12369 * <p> 12370 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12371 * allowed to obtain any priority on any action. 12372 */ 12373 private void adjustPriority( 12374 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12375 // nothing to do; priority is fine as-is 12376 if (intent.getPriority() <= 0) { 12377 return; 12378 } 12379 12380 final ActivityInfo activityInfo = intent.activity.info; 12381 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12382 12383 final boolean privilegedApp = 12384 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12385 if (!privilegedApp) { 12386 // non-privileged applications can never define a priority >0 12387 if (DEBUG_FILTERS) { 12388 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 12389 + " package: " + applicationInfo.packageName 12390 + " activity: " + intent.activity.className 12391 + " origPrio: " + intent.getPriority()); 12392 } 12393 intent.setPriority(0); 12394 return; 12395 } 12396 12397 if (systemActivities == null) { 12398 // the system package is not disabled; we're parsing the system partition 12399 if (isProtectedAction(intent)) { 12400 if (mDeferProtectedFilters) { 12401 // We can't deal with these just yet. No component should ever obtain a 12402 // >0 priority for a protected actions, with ONE exception -- the setup 12403 // wizard. The setup wizard, however, cannot be known until we're able to 12404 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12405 // until all intent filters have been processed. Chicken, meet egg. 12406 // Let the filter temporarily have a high priority and rectify the 12407 // priorities after all system packages have been scanned. 12408 mProtectedFilters.add(intent); 12409 if (DEBUG_FILTERS) { 12410 Slog.i(TAG, "Protected action; save for later;" 12411 + " package: " + applicationInfo.packageName 12412 + " activity: " + intent.activity.className 12413 + " origPrio: " + intent.getPriority()); 12414 } 12415 return; 12416 } else { 12417 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12418 Slog.i(TAG, "No setup wizard;" 12419 + " All protected intents capped to priority 0"); 12420 } 12421 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12422 if (DEBUG_FILTERS) { 12423 Slog.i(TAG, "Found setup wizard;" 12424 + " allow priority " + intent.getPriority() + ";" 12425 + " package: " + intent.activity.info.packageName 12426 + " activity: " + intent.activity.className 12427 + " priority: " + intent.getPriority()); 12428 } 12429 // setup wizard gets whatever it wants 12430 return; 12431 } 12432 if (DEBUG_FILTERS) { 12433 Slog.i(TAG, "Protected action; cap priority to 0;" 12434 + " package: " + intent.activity.info.packageName 12435 + " activity: " + intent.activity.className 12436 + " origPrio: " + intent.getPriority()); 12437 } 12438 intent.setPriority(0); 12439 return; 12440 } 12441 } 12442 // privileged apps on the system image get whatever priority they request 12443 return; 12444 } 12445 12446 // privileged app unbundled update ... try to find the same activity 12447 final PackageParser.Activity foundActivity = 12448 findMatchingActivity(systemActivities, activityInfo); 12449 if (foundActivity == null) { 12450 // this is a new activity; it cannot obtain >0 priority 12451 if (DEBUG_FILTERS) { 12452 Slog.i(TAG, "New activity; cap priority to 0;" 12453 + " package: " + applicationInfo.packageName 12454 + " activity: " + intent.activity.className 12455 + " origPrio: " + intent.getPriority()); 12456 } 12457 intent.setPriority(0); 12458 return; 12459 } 12460 12461 // found activity, now check for filter equivalence 12462 12463 // a shallow copy is enough; we modify the list, not its contents 12464 final List<ActivityIntentInfo> intentListCopy = 12465 new ArrayList<>(foundActivity.intents); 12466 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12467 12468 // find matching action subsets 12469 final Iterator<String> actionsIterator = intent.actionsIterator(); 12470 if (actionsIterator != null) { 12471 getIntentListSubset( 12472 intentListCopy, new ActionIterGenerator(), actionsIterator); 12473 if (intentListCopy.size() == 0) { 12474 // no more intents to match; we're not equivalent 12475 if (DEBUG_FILTERS) { 12476 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12477 + " package: " + applicationInfo.packageName 12478 + " activity: " + intent.activity.className 12479 + " origPrio: " + intent.getPriority()); 12480 } 12481 intent.setPriority(0); 12482 return; 12483 } 12484 } 12485 12486 // find matching category subsets 12487 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12488 if (categoriesIterator != null) { 12489 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12490 categoriesIterator); 12491 if (intentListCopy.size() == 0) { 12492 // no more intents to match; we're not equivalent 12493 if (DEBUG_FILTERS) { 12494 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12495 + " package: " + applicationInfo.packageName 12496 + " activity: " + intent.activity.className 12497 + " origPrio: " + intent.getPriority()); 12498 } 12499 intent.setPriority(0); 12500 return; 12501 } 12502 } 12503 12504 // find matching schemes subsets 12505 final Iterator<String> schemesIterator = intent.schemesIterator(); 12506 if (schemesIterator != null) { 12507 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12508 schemesIterator); 12509 if (intentListCopy.size() == 0) { 12510 // no more intents to match; we're not equivalent 12511 if (DEBUG_FILTERS) { 12512 Slog.i(TAG, "Mismatched scheme; 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 12522 // find matching authorities subsets 12523 final Iterator<IntentFilter.AuthorityEntry> 12524 authoritiesIterator = intent.authoritiesIterator(); 12525 if (authoritiesIterator != null) { 12526 getIntentListSubset(intentListCopy, 12527 new AuthoritiesIterGenerator(), 12528 authoritiesIterator); 12529 if (intentListCopy.size() == 0) { 12530 // no more intents to match; we're not equivalent 12531 if (DEBUG_FILTERS) { 12532 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12533 + " package: " + applicationInfo.packageName 12534 + " activity: " + intent.activity.className 12535 + " origPrio: " + intent.getPriority()); 12536 } 12537 intent.setPriority(0); 12538 return; 12539 } 12540 } 12541 12542 // we found matching filter(s); app gets the max priority of all intents 12543 int cappedPriority = 0; 12544 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12545 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12546 } 12547 if (intent.getPriority() > cappedPriority) { 12548 if (DEBUG_FILTERS) { 12549 Slog.i(TAG, "Found matching filter(s);" 12550 + " cap priority to " + cappedPriority + ";" 12551 + " package: " + applicationInfo.packageName 12552 + " activity: " + intent.activity.className 12553 + " origPrio: " + intent.getPriority()); 12554 } 12555 intent.setPriority(cappedPriority); 12556 return; 12557 } 12558 // all this for nothing; the requested priority was <= what was on the system 12559 } 12560 12561 public final void addActivity(PackageParser.Activity a, String type) { 12562 mActivities.put(a.getComponentName(), a); 12563 if (DEBUG_SHOW_INFO) 12564 Log.v( 12565 TAG, " " + type + " " + 12566 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12567 if (DEBUG_SHOW_INFO) 12568 Log.v(TAG, " Class=" + a.info.name); 12569 final int NI = a.intents.size(); 12570 for (int j=0; j<NI; j++) { 12571 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12572 if ("activity".equals(type)) { 12573 final PackageSetting ps = 12574 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12575 final List<PackageParser.Activity> systemActivities = 12576 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12577 adjustPriority(systemActivities, intent); 12578 } 12579 if (DEBUG_SHOW_INFO) { 12580 Log.v(TAG, " IntentFilter:"); 12581 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12582 } 12583 if (!intent.debugCheck()) { 12584 Log.w(TAG, "==> For Activity " + a.info.name); 12585 } 12586 addFilter(intent); 12587 } 12588 } 12589 12590 public final void removeActivity(PackageParser.Activity a, String type) { 12591 mActivities.remove(a.getComponentName()); 12592 if (DEBUG_SHOW_INFO) { 12593 Log.v(TAG, " " + type + " " 12594 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12595 : a.info.name) + ":"); 12596 Log.v(TAG, " Class=" + a.info.name); 12597 } 12598 final int NI = a.intents.size(); 12599 for (int j=0; j<NI; j++) { 12600 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12601 if (DEBUG_SHOW_INFO) { 12602 Log.v(TAG, " IntentFilter:"); 12603 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12604 } 12605 removeFilter(intent); 12606 } 12607 } 12608 12609 @Override 12610 protected boolean allowFilterResult( 12611 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12612 ActivityInfo filterAi = filter.activity.info; 12613 for (int i=dest.size()-1; i>=0; i--) { 12614 ActivityInfo destAi = dest.get(i).activityInfo; 12615 if (destAi.name == filterAi.name 12616 && destAi.packageName == filterAi.packageName) { 12617 return false; 12618 } 12619 } 12620 return true; 12621 } 12622 12623 @Override 12624 protected ActivityIntentInfo[] newArray(int size) { 12625 return new ActivityIntentInfo[size]; 12626 } 12627 12628 @Override 12629 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12630 if (!sUserManager.exists(userId)) return true; 12631 PackageParser.Package p = filter.activity.owner; 12632 if (p != null) { 12633 PackageSetting ps = (PackageSetting)p.mExtras; 12634 if (ps != null) { 12635 // System apps are never considered stopped for purposes of 12636 // filtering, because there may be no way for the user to 12637 // actually re-launch them. 12638 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12639 && ps.getStopped(userId); 12640 } 12641 } 12642 return false; 12643 } 12644 12645 @Override 12646 protected boolean isPackageForFilter(String packageName, 12647 PackageParser.ActivityIntentInfo info) { 12648 return packageName.equals(info.activity.owner.packageName); 12649 } 12650 12651 @Override 12652 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12653 int match, int userId) { 12654 if (!sUserManager.exists(userId)) return null; 12655 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12656 return null; 12657 } 12658 final PackageParser.Activity activity = info.activity; 12659 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12660 if (ps == null) { 12661 return null; 12662 } 12663 final PackageUserState userState = ps.readUserState(userId); 12664 ActivityInfo ai = 12665 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 12666 if (ai == null) { 12667 return null; 12668 } 12669 final boolean matchExplicitlyVisibleOnly = 12670 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12671 final boolean matchVisibleToInstantApp = 12672 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12673 final boolean componentVisible = 12674 matchVisibleToInstantApp 12675 && info.isVisibleToInstantApp() 12676 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12677 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12678 // throw out filters that aren't visible to ephemeral apps 12679 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12680 return null; 12681 } 12682 // throw out instant app filters if we're not explicitly requesting them 12683 if (!matchInstantApp && userState.instantApp) { 12684 return null; 12685 } 12686 // throw out instant app filters if updates are available; will trigger 12687 // instant app resolution 12688 if (userState.instantApp && ps.isUpdateAvailable()) { 12689 return null; 12690 } 12691 final ResolveInfo res = new ResolveInfo(); 12692 res.activityInfo = ai; 12693 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12694 res.filter = info; 12695 } 12696 if (info != null) { 12697 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12698 } 12699 res.priority = info.getPriority(); 12700 res.preferredOrder = activity.owner.mPreferredOrder; 12701 //System.out.println("Result: " + res.activityInfo.className + 12702 // " = " + res.priority); 12703 res.match = match; 12704 res.isDefault = info.hasDefault; 12705 res.labelRes = info.labelRes; 12706 res.nonLocalizedLabel = info.nonLocalizedLabel; 12707 if (userNeedsBadging(userId)) { 12708 res.noResourceId = true; 12709 } else { 12710 res.icon = info.icon; 12711 } 12712 res.iconResourceId = info.icon; 12713 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12714 res.isInstantAppAvailable = userState.instantApp; 12715 return res; 12716 } 12717 12718 @Override 12719 protected void sortResults(List<ResolveInfo> results) { 12720 Collections.sort(results, mResolvePrioritySorter); 12721 } 12722 12723 @Override 12724 protected void dumpFilter(PrintWriter out, String prefix, 12725 PackageParser.ActivityIntentInfo filter) { 12726 out.print(prefix); out.print( 12727 Integer.toHexString(System.identityHashCode(filter.activity))); 12728 out.print(' '); 12729 filter.activity.printComponentShortName(out); 12730 out.print(" filter "); 12731 out.println(Integer.toHexString(System.identityHashCode(filter))); 12732 } 12733 12734 @Override 12735 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12736 return filter.activity; 12737 } 12738 12739 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12740 PackageParser.Activity activity = (PackageParser.Activity)label; 12741 out.print(prefix); out.print( 12742 Integer.toHexString(System.identityHashCode(activity))); 12743 out.print(' '); 12744 activity.printComponentShortName(out); 12745 if (count > 1) { 12746 out.print(" ("); out.print(count); out.print(" filters)"); 12747 } 12748 out.println(); 12749 } 12750 12751 // Keys are String (activity class name), values are Activity. 12752 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12753 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12754 private int mFlags; 12755 } 12756 12757 private final class ServiceIntentResolver 12758 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12759 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12760 boolean defaultOnly, int userId) { 12761 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12762 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12763 } 12764 12765 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12766 int userId) { 12767 if (!sUserManager.exists(userId)) return null; 12768 mFlags = flags; 12769 return super.queryIntent(intent, resolvedType, 12770 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12771 userId); 12772 } 12773 12774 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12775 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12776 if (!sUserManager.exists(userId)) return null; 12777 if (packageServices == null) { 12778 return null; 12779 } 12780 mFlags = flags; 12781 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12782 final int N = packageServices.size(); 12783 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12784 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12785 12786 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12787 for (int i = 0; i < N; ++i) { 12788 intentFilters = packageServices.get(i).intents; 12789 if (intentFilters != null && intentFilters.size() > 0) { 12790 PackageParser.ServiceIntentInfo[] array = 12791 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12792 intentFilters.toArray(array); 12793 listCut.add(array); 12794 } 12795 } 12796 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12797 } 12798 12799 public final void addService(PackageParser.Service s) { 12800 mServices.put(s.getComponentName(), s); 12801 if (DEBUG_SHOW_INFO) { 12802 Log.v(TAG, " " 12803 + (s.info.nonLocalizedLabel != null 12804 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12805 Log.v(TAG, " Class=" + s.info.name); 12806 } 12807 final int NI = s.intents.size(); 12808 int j; 12809 for (j=0; j<NI; j++) { 12810 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12811 if (DEBUG_SHOW_INFO) { 12812 Log.v(TAG, " IntentFilter:"); 12813 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12814 } 12815 if (!intent.debugCheck()) { 12816 Log.w(TAG, "==> For Service " + s.info.name); 12817 } 12818 addFilter(intent); 12819 } 12820 } 12821 12822 public final void removeService(PackageParser.Service s) { 12823 mServices.remove(s.getComponentName()); 12824 if (DEBUG_SHOW_INFO) { 12825 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12826 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12827 Log.v(TAG, " Class=" + s.info.name); 12828 } 12829 final int NI = s.intents.size(); 12830 int j; 12831 for (j=0; j<NI; j++) { 12832 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12833 if (DEBUG_SHOW_INFO) { 12834 Log.v(TAG, " IntentFilter:"); 12835 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12836 } 12837 removeFilter(intent); 12838 } 12839 } 12840 12841 @Override 12842 protected boolean allowFilterResult( 12843 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12844 ServiceInfo filterSi = filter.service.info; 12845 for (int i=dest.size()-1; i>=0; i--) { 12846 ServiceInfo destAi = dest.get(i).serviceInfo; 12847 if (destAi.name == filterSi.name 12848 && destAi.packageName == filterSi.packageName) { 12849 return false; 12850 } 12851 } 12852 return true; 12853 } 12854 12855 @Override 12856 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12857 return new PackageParser.ServiceIntentInfo[size]; 12858 } 12859 12860 @Override 12861 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12862 if (!sUserManager.exists(userId)) return true; 12863 PackageParser.Package p = filter.service.owner; 12864 if (p != null) { 12865 PackageSetting ps = (PackageSetting)p.mExtras; 12866 if (ps != null) { 12867 // System apps are never considered stopped for purposes of 12868 // filtering, because there may be no way for the user to 12869 // actually re-launch them. 12870 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12871 && ps.getStopped(userId); 12872 } 12873 } 12874 return false; 12875 } 12876 12877 @Override 12878 protected boolean isPackageForFilter(String packageName, 12879 PackageParser.ServiceIntentInfo info) { 12880 return packageName.equals(info.service.owner.packageName); 12881 } 12882 12883 @Override 12884 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12885 int match, int userId) { 12886 if (!sUserManager.exists(userId)) return null; 12887 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12888 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12889 return null; 12890 } 12891 final PackageParser.Service service = info.service; 12892 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12893 if (ps == null) { 12894 return null; 12895 } 12896 final PackageUserState userState = ps.readUserState(userId); 12897 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12898 userState, userId); 12899 if (si == null) { 12900 return null; 12901 } 12902 final boolean matchVisibleToInstantApp = 12903 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12904 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12905 // throw out filters that aren't visible to ephemeral apps 12906 if (matchVisibleToInstantApp 12907 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12908 return null; 12909 } 12910 // throw out ephemeral filters if we're not explicitly requesting them 12911 if (!isInstantApp && userState.instantApp) { 12912 return null; 12913 } 12914 // throw out instant app filters if updates are available; will trigger 12915 // instant app resolution 12916 if (userState.instantApp && ps.isUpdateAvailable()) { 12917 return null; 12918 } 12919 final ResolveInfo res = new ResolveInfo(); 12920 res.serviceInfo = si; 12921 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12922 res.filter = filter; 12923 } 12924 res.priority = info.getPriority(); 12925 res.preferredOrder = service.owner.mPreferredOrder; 12926 res.match = match; 12927 res.isDefault = info.hasDefault; 12928 res.labelRes = info.labelRes; 12929 res.nonLocalizedLabel = info.nonLocalizedLabel; 12930 res.icon = info.icon; 12931 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12932 return res; 12933 } 12934 12935 @Override 12936 protected void sortResults(List<ResolveInfo> results) { 12937 Collections.sort(results, mResolvePrioritySorter); 12938 } 12939 12940 @Override 12941 protected void dumpFilter(PrintWriter out, String prefix, 12942 PackageParser.ServiceIntentInfo filter) { 12943 out.print(prefix); out.print( 12944 Integer.toHexString(System.identityHashCode(filter.service))); 12945 out.print(' '); 12946 filter.service.printComponentShortName(out); 12947 out.print(" filter "); 12948 out.print(Integer.toHexString(System.identityHashCode(filter))); 12949 if (filter.service.info.permission != null) { 12950 out.print(" permission "); out.println(filter.service.info.permission); 12951 } else { 12952 out.println(); 12953 } 12954 } 12955 12956 @Override 12957 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12958 return filter.service; 12959 } 12960 12961 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12962 PackageParser.Service service = (PackageParser.Service)label; 12963 out.print(prefix); out.print( 12964 Integer.toHexString(System.identityHashCode(service))); 12965 out.print(' '); 12966 service.printComponentShortName(out); 12967 if (count > 1) { 12968 out.print(" ("); out.print(count); out.print(" filters)"); 12969 } 12970 out.println(); 12971 } 12972 12973// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12974// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12975// final List<ResolveInfo> retList = Lists.newArrayList(); 12976// while (i.hasNext()) { 12977// final ResolveInfo resolveInfo = (ResolveInfo) i; 12978// if (isEnabledLP(resolveInfo.serviceInfo)) { 12979// retList.add(resolveInfo); 12980// } 12981// } 12982// return retList; 12983// } 12984 12985 // Keys are String (activity class name), values are Activity. 12986 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12987 = new ArrayMap<ComponentName, PackageParser.Service>(); 12988 private int mFlags; 12989 } 12990 12991 private final class ProviderIntentResolver 12992 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12993 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12994 boolean defaultOnly, int userId) { 12995 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12996 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12997 } 12998 12999 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 13000 int userId) { 13001 if (!sUserManager.exists(userId)) 13002 return null; 13003 mFlags = flags; 13004 return super.queryIntent(intent, resolvedType, 13005 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 13006 userId); 13007 } 13008 13009 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 13010 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 13011 if (!sUserManager.exists(userId)) 13012 return null; 13013 if (packageProviders == null) { 13014 return null; 13015 } 13016 mFlags = flags; 13017 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 13018 final int N = packageProviders.size(); 13019 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 13020 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 13021 13022 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 13023 for (int i = 0; i < N; ++i) { 13024 intentFilters = packageProviders.get(i).intents; 13025 if (intentFilters != null && intentFilters.size() > 0) { 13026 PackageParser.ProviderIntentInfo[] array = 13027 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 13028 intentFilters.toArray(array); 13029 listCut.add(array); 13030 } 13031 } 13032 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 13033 } 13034 13035 public final void addProvider(PackageParser.Provider p) { 13036 if (mProviders.containsKey(p.getComponentName())) { 13037 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 13038 return; 13039 } 13040 13041 mProviders.put(p.getComponentName(), p); 13042 if (DEBUG_SHOW_INFO) { 13043 Log.v(TAG, " " 13044 + (p.info.nonLocalizedLabel != null 13045 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13046 Log.v(TAG, " Class=" + p.info.name); 13047 } 13048 final int NI = p.intents.size(); 13049 int j; 13050 for (j = 0; j < NI; j++) { 13051 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13052 if (DEBUG_SHOW_INFO) { 13053 Log.v(TAG, " IntentFilter:"); 13054 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13055 } 13056 if (!intent.debugCheck()) { 13057 Log.w(TAG, "==> For Provider " + p.info.name); 13058 } 13059 addFilter(intent); 13060 } 13061 } 13062 13063 public final void removeProvider(PackageParser.Provider p) { 13064 mProviders.remove(p.getComponentName()); 13065 if (DEBUG_SHOW_INFO) { 13066 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 13067 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13068 Log.v(TAG, " Class=" + p.info.name); 13069 } 13070 final int NI = p.intents.size(); 13071 int j; 13072 for (j = 0; j < NI; j++) { 13073 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13074 if (DEBUG_SHOW_INFO) { 13075 Log.v(TAG, " IntentFilter:"); 13076 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13077 } 13078 removeFilter(intent); 13079 } 13080 } 13081 13082 @Override 13083 protected boolean allowFilterResult( 13084 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 13085 ProviderInfo filterPi = filter.provider.info; 13086 for (int i = dest.size() - 1; i >= 0; i--) { 13087 ProviderInfo destPi = dest.get(i).providerInfo; 13088 if (destPi.name == filterPi.name 13089 && destPi.packageName == filterPi.packageName) { 13090 return false; 13091 } 13092 } 13093 return true; 13094 } 13095 13096 @Override 13097 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 13098 return new PackageParser.ProviderIntentInfo[size]; 13099 } 13100 13101 @Override 13102 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 13103 if (!sUserManager.exists(userId)) 13104 return true; 13105 PackageParser.Package p = filter.provider.owner; 13106 if (p != null) { 13107 PackageSetting ps = (PackageSetting) p.mExtras; 13108 if (ps != null) { 13109 // System apps are never considered stopped for purposes of 13110 // filtering, because there may be no way for the user to 13111 // actually re-launch them. 13112 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 13113 && ps.getStopped(userId); 13114 } 13115 } 13116 return false; 13117 } 13118 13119 @Override 13120 protected boolean isPackageForFilter(String packageName, 13121 PackageParser.ProviderIntentInfo info) { 13122 return packageName.equals(info.provider.owner.packageName); 13123 } 13124 13125 @Override 13126 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 13127 int match, int userId) { 13128 if (!sUserManager.exists(userId)) 13129 return null; 13130 final PackageParser.ProviderIntentInfo info = filter; 13131 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 13132 return null; 13133 } 13134 final PackageParser.Provider provider = info.provider; 13135 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 13136 if (ps == null) { 13137 return null; 13138 } 13139 final PackageUserState userState = ps.readUserState(userId); 13140 final boolean matchVisibleToInstantApp = 13141 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13142 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13143 // throw out filters that aren't visible to instant applications 13144 if (matchVisibleToInstantApp 13145 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 13146 return null; 13147 } 13148 // throw out instant application filters if we're not explicitly requesting them 13149 if (!isInstantApp && userState.instantApp) { 13150 return null; 13151 } 13152 // throw out instant application filters if updates are available; will trigger 13153 // instant application resolution 13154 if (userState.instantApp && ps.isUpdateAvailable()) { 13155 return null; 13156 } 13157 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 13158 userState, userId); 13159 if (pi == null) { 13160 return null; 13161 } 13162 final ResolveInfo res = new ResolveInfo(); 13163 res.providerInfo = pi; 13164 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 13165 res.filter = filter; 13166 } 13167 res.priority = info.getPriority(); 13168 res.preferredOrder = provider.owner.mPreferredOrder; 13169 res.match = match; 13170 res.isDefault = info.hasDefault; 13171 res.labelRes = info.labelRes; 13172 res.nonLocalizedLabel = info.nonLocalizedLabel; 13173 res.icon = info.icon; 13174 res.system = res.providerInfo.applicationInfo.isSystemApp(); 13175 return res; 13176 } 13177 13178 @Override 13179 protected void sortResults(List<ResolveInfo> results) { 13180 Collections.sort(results, mResolvePrioritySorter); 13181 } 13182 13183 @Override 13184 protected void dumpFilter(PrintWriter out, String prefix, 13185 PackageParser.ProviderIntentInfo filter) { 13186 out.print(prefix); 13187 out.print( 13188 Integer.toHexString(System.identityHashCode(filter.provider))); 13189 out.print(' '); 13190 filter.provider.printComponentShortName(out); 13191 out.print(" filter "); 13192 out.println(Integer.toHexString(System.identityHashCode(filter))); 13193 } 13194 13195 @Override 13196 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 13197 return filter.provider; 13198 } 13199 13200 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13201 PackageParser.Provider provider = (PackageParser.Provider)label; 13202 out.print(prefix); out.print( 13203 Integer.toHexString(System.identityHashCode(provider))); 13204 out.print(' '); 13205 provider.printComponentShortName(out); 13206 if (count > 1) { 13207 out.print(" ("); out.print(count); out.print(" filters)"); 13208 } 13209 out.println(); 13210 } 13211 13212 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 13213 = new ArrayMap<ComponentName, PackageParser.Provider>(); 13214 private int mFlags; 13215 } 13216 13217 static final class InstantAppIntentResolver 13218 extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter, 13219 AuxiliaryResolveInfo.AuxiliaryFilter> { 13220 /** 13221 * The result that has the highest defined order. Ordering applies on a 13222 * per-package basis. Mapping is from package name to Pair of order and 13223 * EphemeralResolveInfo. 13224 * <p> 13225 * NOTE: This is implemented as a field variable for convenience and efficiency. 13226 * By having a field variable, we're able to track filter ordering as soon as 13227 * a non-zero order is defined. Otherwise, multiple loops across the result set 13228 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 13229 * this needs to be contained entirely within {@link #filterResults}. 13230 */ 13231 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 13232 13233 @Override 13234 protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) { 13235 return new AuxiliaryResolveInfo.AuxiliaryFilter[size]; 13236 } 13237 13238 @Override 13239 protected boolean isPackageForFilter(String packageName, 13240 AuxiliaryResolveInfo.AuxiliaryFilter responseObj) { 13241 return true; 13242 } 13243 13244 @Override 13245 protected AuxiliaryResolveInfo.AuxiliaryFilter newResult( 13246 AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) { 13247 if (!sUserManager.exists(userId)) { 13248 return null; 13249 } 13250 final String packageName = responseObj.resolveInfo.getPackageName(); 13251 final Integer order = responseObj.getOrder(); 13252 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 13253 mOrderResult.get(packageName); 13254 // ordering is enabled and this item's order isn't high enough 13255 if (lastOrderResult != null && lastOrderResult.first >= order) { 13256 return null; 13257 } 13258 final InstantAppResolveInfo res = responseObj.resolveInfo; 13259 if (order > 0) { 13260 // non-zero order, enable ordering 13261 mOrderResult.put(packageName, new Pair<>(order, res)); 13262 } 13263 return responseObj; 13264 } 13265 13266 @Override 13267 protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) { 13268 // only do work if ordering is enabled [most of the time it won't be] 13269 if (mOrderResult.size() == 0) { 13270 return; 13271 } 13272 int resultSize = results.size(); 13273 for (int i = 0; i < resultSize; i++) { 13274 final InstantAppResolveInfo info = results.get(i).resolveInfo; 13275 final String packageName = info.getPackageName(); 13276 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 13277 if (savedInfo == null) { 13278 // package doesn't having ordering 13279 continue; 13280 } 13281 if (savedInfo.second == info) { 13282 // circled back to the highest ordered item; remove from order list 13283 mOrderResult.remove(packageName); 13284 if (mOrderResult.size() == 0) { 13285 // no more ordered items 13286 break; 13287 } 13288 continue; 13289 } 13290 // item has a worse order, remove it from the result list 13291 results.remove(i); 13292 resultSize--; 13293 i--; 13294 } 13295 } 13296 } 13297 13298 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 13299 new Comparator<ResolveInfo>() { 13300 public int compare(ResolveInfo r1, ResolveInfo r2) { 13301 int v1 = r1.priority; 13302 int v2 = r2.priority; 13303 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 13304 if (v1 != v2) { 13305 return (v1 > v2) ? -1 : 1; 13306 } 13307 v1 = r1.preferredOrder; 13308 v2 = r2.preferredOrder; 13309 if (v1 != v2) { 13310 return (v1 > v2) ? -1 : 1; 13311 } 13312 if (r1.isDefault != r2.isDefault) { 13313 return r1.isDefault ? -1 : 1; 13314 } 13315 v1 = r1.match; 13316 v2 = r2.match; 13317 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13318 if (v1 != v2) { 13319 return (v1 > v2) ? -1 : 1; 13320 } 13321 if (r1.system != r2.system) { 13322 return r1.system ? -1 : 1; 13323 } 13324 if (r1.activityInfo != null) { 13325 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13326 } 13327 if (r1.serviceInfo != null) { 13328 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13329 } 13330 if (r1.providerInfo != null) { 13331 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13332 } 13333 return 0; 13334 } 13335 }; 13336 13337 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13338 new Comparator<ProviderInfo>() { 13339 public int compare(ProviderInfo p1, ProviderInfo p2) { 13340 final int v1 = p1.initOrder; 13341 final int v2 = p2.initOrder; 13342 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13343 } 13344 }; 13345 13346 @Override 13347 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13348 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13349 final int[] userIds, int[] instantUserIds) { 13350 mHandler.post(new Runnable() { 13351 @Override 13352 public void run() { 13353 try { 13354 final IActivityManager am = ActivityManager.getService(); 13355 if (am == null) return; 13356 final int[] resolvedUserIds; 13357 if (userIds == null) { 13358 resolvedUserIds = am.getRunningUserIds(); 13359 } else { 13360 resolvedUserIds = userIds; 13361 } 13362 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13363 resolvedUserIds, false); 13364 if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) { 13365 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13366 instantUserIds, true); 13367 } 13368 } catch (RemoteException ex) { 13369 } 13370 } 13371 }); 13372 } 13373 13374 @Override 13375 public void notifyPackageAdded(String packageName) { 13376 final PackageListObserver[] observers; 13377 synchronized (mPackages) { 13378 if (mPackageListObservers.size() == 0) { 13379 return; 13380 } 13381 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13382 } 13383 for (int i = observers.length - 1; i >= 0; --i) { 13384 observers[i].onPackageAdded(packageName); 13385 } 13386 } 13387 13388 @Override 13389 public void notifyPackageRemoved(String packageName) { 13390 final PackageListObserver[] observers; 13391 synchronized (mPackages) { 13392 if (mPackageListObservers.size() == 0) { 13393 return; 13394 } 13395 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13396 } 13397 for (int i = observers.length - 1; i >= 0; --i) { 13398 observers[i].onPackageRemoved(packageName); 13399 } 13400 } 13401 13402 /** 13403 * Sends a broadcast for the given action. 13404 * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with 13405 * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows 13406 * the system and applications allowed to see instant applications to receive package 13407 * lifecycle events for instant applications. 13408 */ 13409 private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras, 13410 int flags, String targetPkg, IIntentReceiver finishedReceiver, 13411 int[] userIds, boolean isInstantApp) 13412 throws RemoteException { 13413 for (int id : userIds) { 13414 final Intent intent = new Intent(action, 13415 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13416 final String[] requiredPermissions = 13417 isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null; 13418 if (extras != null) { 13419 intent.putExtras(extras); 13420 } 13421 if (targetPkg != null) { 13422 intent.setPackage(targetPkg); 13423 } 13424 // Modify the UID when posting to other users 13425 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13426 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13427 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13428 intent.putExtra(Intent.EXTRA_UID, uid); 13429 } 13430 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13431 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13432 if (DEBUG_BROADCASTS) { 13433 RuntimeException here = new RuntimeException("here"); 13434 here.fillInStackTrace(); 13435 Slog.d(TAG, "Sending to user " + id + ": " 13436 + intent.toShortString(false, true, false, false) 13437 + " " + intent.getExtras(), here); 13438 } 13439 am.broadcastIntent(null, intent, null, finishedReceiver, 13440 0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE, 13441 null, finishedReceiver != null, false, id); 13442 } 13443 } 13444 13445 /** 13446 * Check if the external storage media is available. This is true if there 13447 * is a mounted external storage medium or if the external storage is 13448 * emulated. 13449 */ 13450 private boolean isExternalMediaAvailable() { 13451 return mMediaMounted || Environment.isExternalStorageEmulated(); 13452 } 13453 13454 @Override 13455 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13456 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 13457 return null; 13458 } 13459 if (!isExternalMediaAvailable()) { 13460 // If the external storage is no longer mounted at this point, 13461 // the caller may not have been able to delete all of this 13462 // packages files and can not delete any more. Bail. 13463 return null; 13464 } 13465 synchronized (mPackages) { 13466 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13467 if (lastPackage != null) { 13468 pkgs.remove(lastPackage); 13469 } 13470 if (pkgs.size() > 0) { 13471 return pkgs.get(0); 13472 } 13473 } 13474 return null; 13475 } 13476 13477 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13478 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13479 userId, andCode ? 1 : 0, packageName); 13480 if (mSystemReady) { 13481 msg.sendToTarget(); 13482 } else { 13483 if (mPostSystemReadyMessages == null) { 13484 mPostSystemReadyMessages = new ArrayList<>(); 13485 } 13486 mPostSystemReadyMessages.add(msg); 13487 } 13488 } 13489 13490 void startCleaningPackages() { 13491 // reader 13492 if (!isExternalMediaAvailable()) { 13493 return; 13494 } 13495 synchronized (mPackages) { 13496 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13497 return; 13498 } 13499 } 13500 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13501 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13502 IActivityManager am = ActivityManager.getService(); 13503 if (am != null) { 13504 int dcsUid = -1; 13505 synchronized (mPackages) { 13506 if (!mDefaultContainerWhitelisted) { 13507 mDefaultContainerWhitelisted = true; 13508 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13509 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13510 } 13511 } 13512 try { 13513 if (dcsUid > 0) { 13514 am.backgroundWhitelistUid(dcsUid); 13515 } 13516 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13517 UserHandle.USER_SYSTEM); 13518 } catch (RemoteException e) { 13519 } 13520 } 13521 } 13522 13523 /** 13524 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13525 * it is acting on behalf on an enterprise or the user). 13526 * 13527 * Note that the ordering of the conditionals in this method is important. The checks we perform 13528 * are as follows, in this order: 13529 * 13530 * 1) If the install is being performed by a system app, we can trust the app to have set the 13531 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13532 * what it is. 13533 * 2) If the install is being performed by a device or profile owner app, the install reason 13534 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13535 * set the install reason correctly. If the app targets an older SDK version where install 13536 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13537 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13538 * 3) In all other cases, the install is being performed by a regular app that is neither part 13539 * of the system nor a device or profile owner. We have no reason to believe that this app is 13540 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13541 * set to enterprise policy and if so, change it to unknown instead. 13542 */ 13543 private int fixUpInstallReason(String installerPackageName, int installerUid, 13544 int installReason) { 13545 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13546 == PERMISSION_GRANTED) { 13547 // If the install is being performed by a system app, we trust that app to have set the 13548 // install reason correctly. 13549 return installReason; 13550 } 13551 13552 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13553 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13554 if (dpm != null) { 13555 ComponentName owner = null; 13556 try { 13557 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13558 if (owner == null) { 13559 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13560 } 13561 } catch (RemoteException e) { 13562 } 13563 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13564 // If the install is being performed by a device or profile owner, the install 13565 // reason should be enterprise policy. 13566 return PackageManager.INSTALL_REASON_POLICY; 13567 } 13568 } 13569 13570 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13571 // If the install is being performed by a regular app (i.e. neither system app nor 13572 // device or profile owner), we have no reason to believe that the app is acting on 13573 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13574 // change it to unknown instead. 13575 return PackageManager.INSTALL_REASON_UNKNOWN; 13576 } 13577 13578 // If the install is being performed by a regular app and the install reason was set to any 13579 // value but enterprise policy, leave the install reason unchanged. 13580 return installReason; 13581 } 13582 13583 void installStage(String packageName, File stagedDir, 13584 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13585 String installerPackageName, int installerUid, UserHandle user, 13586 PackageParser.SigningDetails signingDetails) { 13587 if (DEBUG_INSTANT) { 13588 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13589 Slog.d(TAG, "Ephemeral install of " + packageName); 13590 } 13591 } 13592 final VerificationInfo verificationInfo = new VerificationInfo( 13593 sessionParams.originatingUri, sessionParams.referrerUri, 13594 sessionParams.originatingUid, installerUid); 13595 13596 final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir); 13597 13598 final Message msg = mHandler.obtainMessage(INIT_COPY); 13599 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13600 sessionParams.installReason); 13601 final InstallParams params = new InstallParams(origin, null, observer, 13602 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13603 verificationInfo, user, sessionParams.abiOverride, 13604 sessionParams.grantedRuntimePermissions, signingDetails, installReason); 13605 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13606 msg.obj = params; 13607 13608 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13609 System.identityHashCode(msg.obj)); 13610 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13611 System.identityHashCode(msg.obj)); 13612 13613 mHandler.sendMessage(msg); 13614 } 13615 13616 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13617 int userId) { 13618 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13619 final boolean isInstantApp = pkgSetting.getInstantApp(userId); 13620 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 13621 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 13622 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 13623 false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds); 13624 13625 // Send a session commit broadcast 13626 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 13627 info.installReason = pkgSetting.getInstallReason(userId); 13628 info.appPackageName = packageName; 13629 sendSessionCommitBroadcast(info, userId); 13630 } 13631 13632 @Override 13633 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 13634 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) { 13635 if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) { 13636 return; 13637 } 13638 Bundle extras = new Bundle(1); 13639 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13640 final int uid = UserHandle.getUid( 13641 (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId); 13642 extras.putInt(Intent.EXTRA_UID, uid); 13643 13644 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13645 packageName, extras, 0, null, null, userIds, instantUserIds); 13646 if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) { 13647 mHandler.post(() -> { 13648 for (int userId : userIds) { 13649 sendBootCompletedBroadcastToSystemApp( 13650 packageName, includeStopped, userId); 13651 } 13652 } 13653 ); 13654 } 13655 } 13656 13657 /** 13658 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13659 * automatically without needing an explicit launch. 13660 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13661 */ 13662 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 13663 int userId) { 13664 // If user is not running, the app didn't miss any broadcast 13665 if (!mUserManagerInternal.isUserRunning(userId)) { 13666 return; 13667 } 13668 final IActivityManager am = ActivityManager.getService(); 13669 try { 13670 // Deliver LOCKED_BOOT_COMPLETED first 13671 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13672 .setPackage(packageName); 13673 if (includeStopped) { 13674 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13675 } 13676 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13677 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13678 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13679 13680 // Deliver BOOT_COMPLETED only if user is unlocked 13681 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13682 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13683 if (includeStopped) { 13684 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13685 } 13686 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13687 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13688 } 13689 } catch (RemoteException e) { 13690 throw e.rethrowFromSystemServer(); 13691 } 13692 } 13693 13694 @Override 13695 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13696 int userId) { 13697 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13698 PackageSetting pkgSetting; 13699 final int callingUid = Binder.getCallingUid(); 13700 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13701 true /* requireFullPermission */, true /* checkShell */, 13702 "setApplicationHiddenSetting for user " + userId); 13703 13704 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13705 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13706 return false; 13707 } 13708 13709 long callingId = Binder.clearCallingIdentity(); 13710 try { 13711 boolean sendAdded = false; 13712 boolean sendRemoved = false; 13713 // writer 13714 synchronized (mPackages) { 13715 pkgSetting = mSettings.mPackages.get(packageName); 13716 if (pkgSetting == null) { 13717 return false; 13718 } 13719 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13720 return false; 13721 } 13722 // Do not allow "android" is being disabled 13723 if ("android".equals(packageName)) { 13724 Slog.w(TAG, "Cannot hide package: android"); 13725 return false; 13726 } 13727 // Cannot hide static shared libs as they are considered 13728 // a part of the using app (emulating static linking). Also 13729 // static libs are installed always on internal storage. 13730 PackageParser.Package pkg = mPackages.get(packageName); 13731 if (pkg != null && pkg.staticSharedLibName != null) { 13732 Slog.w(TAG, "Cannot hide package: " + packageName 13733 + " providing static shared library: " 13734 + pkg.staticSharedLibName); 13735 return false; 13736 } 13737 // Only allow protected packages to hide themselves. 13738 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 13739 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13740 Slog.w(TAG, "Not hiding protected package: " + packageName); 13741 return false; 13742 } 13743 13744 if (pkgSetting.getHidden(userId) != hidden) { 13745 pkgSetting.setHidden(hidden, userId); 13746 mSettings.writePackageRestrictionsLPr(userId); 13747 if (hidden) { 13748 sendRemoved = true; 13749 } else { 13750 sendAdded = true; 13751 } 13752 } 13753 } 13754 if (sendAdded) { 13755 sendPackageAddedForUser(packageName, pkgSetting, userId); 13756 return true; 13757 } 13758 if (sendRemoved) { 13759 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13760 "hiding pkg"); 13761 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13762 return true; 13763 } 13764 } finally { 13765 Binder.restoreCallingIdentity(callingId); 13766 } 13767 return false; 13768 } 13769 13770 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13771 int userId) { 13772 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13773 info.removedPackage = packageName; 13774 info.installerPackageName = pkgSetting.installerPackageName; 13775 info.removedUsers = new int[] {userId}; 13776 info.broadcastUsers = new int[] {userId}; 13777 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13778 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13779 } 13780 13781 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13782 if (pkgList.length > 0) { 13783 Bundle extras = new Bundle(1); 13784 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13785 13786 sendPackageBroadcast( 13787 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13788 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13789 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13790 new int[] {userId}, null); 13791 } 13792 } 13793 13794 /** 13795 * Returns true if application is not found or there was an error. Otherwise it returns 13796 * the hidden state of the package for the given user. 13797 */ 13798 @Override 13799 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13800 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13801 final int callingUid = Binder.getCallingUid(); 13802 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13803 true /* requireFullPermission */, false /* checkShell */, 13804 "getApplicationHidden for user " + userId); 13805 PackageSetting ps; 13806 long callingId = Binder.clearCallingIdentity(); 13807 try { 13808 // writer 13809 synchronized (mPackages) { 13810 ps = mSettings.mPackages.get(packageName); 13811 if (ps == null) { 13812 return true; 13813 } 13814 if (filterAppAccessLPr(ps, callingUid, userId)) { 13815 return true; 13816 } 13817 return ps.getHidden(userId); 13818 } 13819 } finally { 13820 Binder.restoreCallingIdentity(callingId); 13821 } 13822 } 13823 13824 /** 13825 * @hide 13826 */ 13827 @Override 13828 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13829 int installReason) { 13830 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13831 null); 13832 PackageSetting pkgSetting; 13833 final int callingUid = Binder.getCallingUid(); 13834 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13835 true /* requireFullPermission */, true /* checkShell */, 13836 "installExistingPackage for user " + userId); 13837 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13838 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13839 } 13840 13841 long callingId = Binder.clearCallingIdentity(); 13842 try { 13843 boolean installed = false; 13844 final boolean instantApp = 13845 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13846 final boolean fullApp = 13847 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13848 13849 // writer 13850 synchronized (mPackages) { 13851 pkgSetting = mSettings.mPackages.get(packageName); 13852 if (pkgSetting == null) { 13853 return PackageManager.INSTALL_FAILED_INVALID_URI; 13854 } 13855 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 13856 // only allow the existing package to be used if it's installed as a full 13857 // application for at least one user 13858 boolean installAllowed = false; 13859 for (int checkUserId : sUserManager.getUserIds()) { 13860 installAllowed = !pkgSetting.getInstantApp(checkUserId); 13861 if (installAllowed) { 13862 break; 13863 } 13864 } 13865 if (!installAllowed) { 13866 return PackageManager.INSTALL_FAILED_INVALID_URI; 13867 } 13868 } 13869 if (!pkgSetting.getInstalled(userId)) { 13870 pkgSetting.setInstalled(true, userId); 13871 pkgSetting.setHidden(false, userId); 13872 pkgSetting.setInstallReason(installReason, userId); 13873 mSettings.writePackageRestrictionsLPr(userId); 13874 mSettings.writeKernelMappingLPr(pkgSetting); 13875 installed = true; 13876 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13877 // upgrade app from instant to full; we don't allow app downgrade 13878 installed = true; 13879 } 13880 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13881 } 13882 13883 if (installed) { 13884 if (pkgSetting.pkg != null) { 13885 synchronized (mInstallLock) { 13886 // We don't need to freeze for a brand new install 13887 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13888 } 13889 } 13890 sendPackageAddedForUser(packageName, pkgSetting, userId); 13891 synchronized (mPackages) { 13892 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 13893 } 13894 } 13895 } finally { 13896 Binder.restoreCallingIdentity(callingId); 13897 } 13898 13899 return PackageManager.INSTALL_SUCCEEDED; 13900 } 13901 13902 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13903 boolean instantApp, boolean fullApp) { 13904 // no state specified; do nothing 13905 if (!instantApp && !fullApp) { 13906 return; 13907 } 13908 if (userId != UserHandle.USER_ALL) { 13909 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13910 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13911 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13912 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13913 } 13914 } else { 13915 for (int currentUserId : sUserManager.getUserIds()) { 13916 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13917 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13918 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13919 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13920 } 13921 } 13922 } 13923 } 13924 13925 boolean isUserRestricted(int userId, String restrictionKey) { 13926 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13927 if (restrictions.getBoolean(restrictionKey, false)) { 13928 Log.w(TAG, "User is restricted: " + restrictionKey); 13929 return true; 13930 } 13931 return false; 13932 } 13933 13934 @Override 13935 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13936 int userId) { 13937 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13938 final int callingUid = Binder.getCallingUid(); 13939 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13940 true /* requireFullPermission */, true /* checkShell */, 13941 "setPackagesSuspended for user " + userId); 13942 13943 if (ArrayUtils.isEmpty(packageNames)) { 13944 return packageNames; 13945 } 13946 13947 // List of package names for whom the suspended state has changed. 13948 List<String> changedPackages = new ArrayList<>(packageNames.length); 13949 // List of package names for whom the suspended state is not set as requested in this 13950 // method. 13951 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13952 long callingId = Binder.clearCallingIdentity(); 13953 try { 13954 for (int i = 0; i < packageNames.length; i++) { 13955 String packageName = packageNames[i]; 13956 boolean changed = false; 13957 final int appId; 13958 synchronized (mPackages) { 13959 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13960 if (pkgSetting == null 13961 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13962 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13963 + "\". Skipping suspending/un-suspending."); 13964 unactionedPackages.add(packageName); 13965 continue; 13966 } 13967 appId = pkgSetting.appId; 13968 if (pkgSetting.getSuspended(userId) != suspended) { 13969 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13970 unactionedPackages.add(packageName); 13971 continue; 13972 } 13973 pkgSetting.setSuspended(suspended, userId); 13974 mSettings.writePackageRestrictionsLPr(userId); 13975 changed = true; 13976 changedPackages.add(packageName); 13977 } 13978 } 13979 13980 if (changed && suspended) { 13981 killApplication(packageName, UserHandle.getUid(userId, appId), 13982 "suspending package"); 13983 } 13984 } 13985 } finally { 13986 Binder.restoreCallingIdentity(callingId); 13987 } 13988 13989 if (!changedPackages.isEmpty()) { 13990 sendPackagesSuspendedForUser(changedPackages.toArray( 13991 new String[changedPackages.size()]), userId, suspended); 13992 } 13993 13994 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13995 } 13996 13997 @Override 13998 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13999 final int callingUid = Binder.getCallingUid(); 14000 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 14001 true /* requireFullPermission */, false /* checkShell */, 14002 "isPackageSuspendedForUser for user " + userId); 14003 synchronized (mPackages) { 14004 final PackageSetting ps = mSettings.mPackages.get(packageName); 14005 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 14006 throw new IllegalArgumentException("Unknown target package: " + packageName); 14007 } 14008 return ps.getSuspended(userId); 14009 } 14010 } 14011 14012 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 14013 if (isPackageDeviceAdmin(packageName, userId)) { 14014 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14015 + "\": has an active device admin"); 14016 return false; 14017 } 14018 14019 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 14020 if (packageName.equals(activeLauncherPackageName)) { 14021 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14022 + "\": contains the active launcher"); 14023 return false; 14024 } 14025 14026 if (packageName.equals(mRequiredInstallerPackage)) { 14027 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14028 + "\": required for package installation"); 14029 return false; 14030 } 14031 14032 if (packageName.equals(mRequiredUninstallerPackage)) { 14033 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14034 + "\": required for package uninstallation"); 14035 return false; 14036 } 14037 14038 if (packageName.equals(mRequiredVerifierPackage)) { 14039 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14040 + "\": required for package verification"); 14041 return false; 14042 } 14043 14044 if (packageName.equals(getDefaultDialerPackageName(userId))) { 14045 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14046 + "\": is the default dialer"); 14047 return false; 14048 } 14049 14050 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 14051 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14052 + "\": protected package"); 14053 return false; 14054 } 14055 14056 // Cannot suspend static shared libs as they are considered 14057 // a part of the using app (emulating static linking). Also 14058 // static libs are installed always on internal storage. 14059 PackageParser.Package pkg = mPackages.get(packageName); 14060 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 14061 Slog.w(TAG, "Cannot suspend package: " + packageName 14062 + " providing static shared library: " 14063 + pkg.staticSharedLibName); 14064 return false; 14065 } 14066 14067 return true; 14068 } 14069 14070 private String getActiveLauncherPackageName(int userId) { 14071 Intent intent = new Intent(Intent.ACTION_MAIN); 14072 intent.addCategory(Intent.CATEGORY_HOME); 14073 ResolveInfo resolveInfo = resolveIntent( 14074 intent, 14075 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 14076 PackageManager.MATCH_DEFAULT_ONLY, 14077 userId); 14078 14079 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 14080 } 14081 14082 private String getDefaultDialerPackageName(int userId) { 14083 synchronized (mPackages) { 14084 return mSettings.getDefaultDialerPackageNameLPw(userId); 14085 } 14086 } 14087 14088 @Override 14089 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 14090 mContext.enforceCallingOrSelfPermission( 14091 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14092 "Only package verification agents can verify applications"); 14093 14094 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14095 final PackageVerificationResponse response = new PackageVerificationResponse( 14096 verificationCode, Binder.getCallingUid()); 14097 msg.arg1 = id; 14098 msg.obj = response; 14099 mHandler.sendMessage(msg); 14100 } 14101 14102 @Override 14103 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 14104 long millisecondsToDelay) { 14105 mContext.enforceCallingOrSelfPermission( 14106 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14107 "Only package verification agents can extend verification timeouts"); 14108 14109 final PackageVerificationState state = mPendingVerification.get(id); 14110 final PackageVerificationResponse response = new PackageVerificationResponse( 14111 verificationCodeAtTimeout, Binder.getCallingUid()); 14112 14113 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 14114 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 14115 } 14116 if (millisecondsToDelay < 0) { 14117 millisecondsToDelay = 0; 14118 } 14119 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 14120 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 14121 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 14122 } 14123 14124 if ((state != null) && !state.timeoutExtended()) { 14125 state.extendTimeout(); 14126 14127 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14128 msg.arg1 = id; 14129 msg.obj = response; 14130 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 14131 } 14132 } 14133 14134 private void broadcastPackageVerified(int verificationId, Uri packageUri, 14135 int verificationCode, UserHandle user) { 14136 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 14137 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 14138 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14139 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14140 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 14141 14142 mContext.sendBroadcastAsUser(intent, user, 14143 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 14144 } 14145 14146 private ComponentName matchComponentForVerifier(String packageName, 14147 List<ResolveInfo> receivers) { 14148 ActivityInfo targetReceiver = null; 14149 14150 final int NR = receivers.size(); 14151 for (int i = 0; i < NR; i++) { 14152 final ResolveInfo info = receivers.get(i); 14153 if (info.activityInfo == null) { 14154 continue; 14155 } 14156 14157 if (packageName.equals(info.activityInfo.packageName)) { 14158 targetReceiver = info.activityInfo; 14159 break; 14160 } 14161 } 14162 14163 if (targetReceiver == null) { 14164 return null; 14165 } 14166 14167 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 14168 } 14169 14170 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 14171 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 14172 if (pkgInfo.verifiers.length == 0) { 14173 return null; 14174 } 14175 14176 final int N = pkgInfo.verifiers.length; 14177 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 14178 for (int i = 0; i < N; i++) { 14179 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 14180 14181 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 14182 receivers); 14183 if (comp == null) { 14184 continue; 14185 } 14186 14187 final int verifierUid = getUidForVerifier(verifierInfo); 14188 if (verifierUid == -1) { 14189 continue; 14190 } 14191 14192 if (DEBUG_VERIFY) { 14193 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 14194 + " with the correct signature"); 14195 } 14196 sufficientVerifiers.add(comp); 14197 verificationState.addSufficientVerifier(verifierUid); 14198 } 14199 14200 return sufficientVerifiers; 14201 } 14202 14203 private int getUidForVerifier(VerifierInfo verifierInfo) { 14204 synchronized (mPackages) { 14205 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 14206 if (pkg == null) { 14207 return -1; 14208 } else if (pkg.mSigningDetails.signatures.length != 1) { 14209 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14210 + " has more than one signature; ignoring"); 14211 return -1; 14212 } 14213 14214 /* 14215 * If the public key of the package's signature does not match 14216 * our expected public key, then this is a different package and 14217 * we should skip. 14218 */ 14219 14220 final byte[] expectedPublicKey; 14221 try { 14222 final Signature verifierSig = pkg.mSigningDetails.signatures[0]; 14223 final PublicKey publicKey = verifierSig.getPublicKey(); 14224 expectedPublicKey = publicKey.getEncoded(); 14225 } catch (CertificateException e) { 14226 return -1; 14227 } 14228 14229 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 14230 14231 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 14232 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14233 + " does not have the expected public key; ignoring"); 14234 return -1; 14235 } 14236 14237 return pkg.applicationInfo.uid; 14238 } 14239 } 14240 14241 @Override 14242 public void finishPackageInstall(int token, boolean didLaunch) { 14243 enforceSystemOrRoot("Only the system is allowed to finish installs"); 14244 14245 if (DEBUG_INSTALL) { 14246 Slog.v(TAG, "BM finishing package install for " + token); 14247 } 14248 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14249 14250 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 14251 mHandler.sendMessage(msg); 14252 } 14253 14254 /** 14255 * Get the verification agent timeout. Used for both the APK verifier and the 14256 * intent filter verifier. 14257 * 14258 * @return verification timeout in milliseconds 14259 */ 14260 private long getVerificationTimeout() { 14261 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 14262 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 14263 DEFAULT_VERIFICATION_TIMEOUT); 14264 } 14265 14266 /** 14267 * Get the default verification agent response code. 14268 * 14269 * @return default verification response code 14270 */ 14271 private int getDefaultVerificationResponse(UserHandle user) { 14272 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 14273 return PackageManager.VERIFICATION_REJECT; 14274 } 14275 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14276 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 14277 DEFAULT_VERIFICATION_RESPONSE); 14278 } 14279 14280 /** 14281 * Check whether or not package verification has been enabled. 14282 * 14283 * @return true if verification should be performed 14284 */ 14285 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 14286 if (!DEFAULT_VERIFY_ENABLE) { 14287 return false; 14288 } 14289 14290 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14291 14292 // Check if installing from ADB 14293 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14294 // Do not run verification in a test harness environment 14295 if (ActivityManager.isRunningInTestHarness()) { 14296 return false; 14297 } 14298 if (ensureVerifyAppsEnabled) { 14299 return true; 14300 } 14301 // Check if the developer does not want package verification for ADB installs 14302 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14303 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14304 return false; 14305 } 14306 } else { 14307 // only when not installed from ADB, skip verification for instant apps when 14308 // the installer and verifier are the same. 14309 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14310 if (mInstantAppInstallerActivity != null 14311 && mInstantAppInstallerActivity.packageName.equals( 14312 mRequiredVerifierPackage)) { 14313 try { 14314 mContext.getSystemService(AppOpsManager.class) 14315 .checkPackage(installerUid, mRequiredVerifierPackage); 14316 if (DEBUG_VERIFY) { 14317 Slog.i(TAG, "disable verification for instant app"); 14318 } 14319 return false; 14320 } catch (SecurityException ignore) { } 14321 } 14322 } 14323 } 14324 14325 if (ensureVerifyAppsEnabled) { 14326 return true; 14327 } 14328 14329 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14330 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14331 } 14332 14333 @Override 14334 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14335 throws RemoteException { 14336 mContext.enforceCallingOrSelfPermission( 14337 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14338 "Only intentfilter verification agents can verify applications"); 14339 14340 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14341 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14342 Binder.getCallingUid(), verificationCode, failedDomains); 14343 msg.arg1 = id; 14344 msg.obj = response; 14345 mHandler.sendMessage(msg); 14346 } 14347 14348 @Override 14349 public int getIntentVerificationStatus(String packageName, int userId) { 14350 final int callingUid = Binder.getCallingUid(); 14351 if (UserHandle.getUserId(callingUid) != userId) { 14352 mContext.enforceCallingOrSelfPermission( 14353 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14354 "getIntentVerificationStatus" + userId); 14355 } 14356 if (getInstantAppPackageName(callingUid) != null) { 14357 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14358 } 14359 synchronized (mPackages) { 14360 final PackageSetting ps = mSettings.mPackages.get(packageName); 14361 if (ps == null 14362 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14363 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14364 } 14365 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14366 } 14367 } 14368 14369 @Override 14370 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14371 mContext.enforceCallingOrSelfPermission( 14372 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14373 14374 boolean result = false; 14375 synchronized (mPackages) { 14376 final PackageSetting ps = mSettings.mPackages.get(packageName); 14377 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14378 return false; 14379 } 14380 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14381 } 14382 if (result) { 14383 scheduleWritePackageRestrictionsLocked(userId); 14384 } 14385 return result; 14386 } 14387 14388 @Override 14389 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14390 String packageName) { 14391 final int callingUid = Binder.getCallingUid(); 14392 if (getInstantAppPackageName(callingUid) != null) { 14393 return ParceledListSlice.emptyList(); 14394 } 14395 synchronized (mPackages) { 14396 final PackageSetting ps = mSettings.mPackages.get(packageName); 14397 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14398 return ParceledListSlice.emptyList(); 14399 } 14400 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14401 } 14402 } 14403 14404 @Override 14405 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14406 if (TextUtils.isEmpty(packageName)) { 14407 return ParceledListSlice.emptyList(); 14408 } 14409 final int callingUid = Binder.getCallingUid(); 14410 final int callingUserId = UserHandle.getUserId(callingUid); 14411 synchronized (mPackages) { 14412 PackageParser.Package pkg = mPackages.get(packageName); 14413 if (pkg == null || pkg.activities == null) { 14414 return ParceledListSlice.emptyList(); 14415 } 14416 if (pkg.mExtras == null) { 14417 return ParceledListSlice.emptyList(); 14418 } 14419 final PackageSetting ps = (PackageSetting) pkg.mExtras; 14420 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 14421 return ParceledListSlice.emptyList(); 14422 } 14423 final int count = pkg.activities.size(); 14424 ArrayList<IntentFilter> result = new ArrayList<>(); 14425 for (int n=0; n<count; n++) { 14426 PackageParser.Activity activity = pkg.activities.get(n); 14427 if (activity.intents != null && activity.intents.size() > 0) { 14428 result.addAll(activity.intents); 14429 } 14430 } 14431 return new ParceledListSlice<>(result); 14432 } 14433 } 14434 14435 @Override 14436 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14437 mContext.enforceCallingOrSelfPermission( 14438 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14439 if (UserHandle.getCallingUserId() != userId) { 14440 mContext.enforceCallingOrSelfPermission( 14441 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14442 } 14443 14444 synchronized (mPackages) { 14445 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14446 if (packageName != null) { 14447 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser( 14448 packageName, userId); 14449 } 14450 return result; 14451 } 14452 } 14453 14454 @Override 14455 public String getDefaultBrowserPackageName(int userId) { 14456 if (UserHandle.getCallingUserId() != userId) { 14457 mContext.enforceCallingOrSelfPermission( 14458 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14459 } 14460 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14461 return null; 14462 } 14463 synchronized (mPackages) { 14464 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14465 } 14466 } 14467 14468 /** 14469 * Get the "allow unknown sources" setting. 14470 * 14471 * @return the current "allow unknown sources" setting 14472 */ 14473 private int getUnknownSourcesSettings() { 14474 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14475 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14476 -1); 14477 } 14478 14479 @Override 14480 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14481 final int callingUid = Binder.getCallingUid(); 14482 if (getInstantAppPackageName(callingUid) != null) { 14483 return; 14484 } 14485 // writer 14486 synchronized (mPackages) { 14487 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14488 if (targetPackageSetting == null 14489 || filterAppAccessLPr( 14490 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 14491 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14492 } 14493 14494 PackageSetting installerPackageSetting; 14495 if (installerPackageName != null) { 14496 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14497 if (installerPackageSetting == null) { 14498 throw new IllegalArgumentException("Unknown installer package: " 14499 + installerPackageName); 14500 } 14501 } else { 14502 installerPackageSetting = null; 14503 } 14504 14505 Signature[] callerSignature; 14506 Object obj = mSettings.getUserIdLPr(callingUid); 14507 if (obj != null) { 14508 if (obj instanceof SharedUserSetting) { 14509 callerSignature = 14510 ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 14511 } else if (obj instanceof PackageSetting) { 14512 callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures; 14513 } else { 14514 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 14515 } 14516 } else { 14517 throw new SecurityException("Unknown calling UID: " + callingUid); 14518 } 14519 14520 // Verify: can't set installerPackageName to a package that is 14521 // not signed with the same cert as the caller. 14522 if (installerPackageSetting != null) { 14523 if (compareSignatures(callerSignature, 14524 installerPackageSetting.signatures.mSigningDetails.signatures) 14525 != PackageManager.SIGNATURE_MATCH) { 14526 throw new SecurityException( 14527 "Caller does not have same cert as new installer package " 14528 + installerPackageName); 14529 } 14530 } 14531 14532 // Verify: if target already has an installer package, it must 14533 // be signed with the same cert as the caller. 14534 if (targetPackageSetting.installerPackageName != null) { 14535 PackageSetting setting = mSettings.mPackages.get( 14536 targetPackageSetting.installerPackageName); 14537 // If the currently set package isn't valid, then it's always 14538 // okay to change it. 14539 if (setting != null) { 14540 if (compareSignatures(callerSignature, 14541 setting.signatures.mSigningDetails.signatures) 14542 != PackageManager.SIGNATURE_MATCH) { 14543 throw new SecurityException( 14544 "Caller does not have same cert as old installer package " 14545 + targetPackageSetting.installerPackageName); 14546 } 14547 } 14548 } 14549 14550 // Okay! 14551 targetPackageSetting.installerPackageName = installerPackageName; 14552 if (installerPackageName != null) { 14553 mSettings.mInstallerPackages.add(installerPackageName); 14554 } 14555 scheduleWriteSettingsLocked(); 14556 } 14557 } 14558 14559 @Override 14560 public void setApplicationCategoryHint(String packageName, int categoryHint, 14561 String callerPackageName) { 14562 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14563 throw new SecurityException("Instant applications don't have access to this method"); 14564 } 14565 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14566 callerPackageName); 14567 synchronized (mPackages) { 14568 PackageSetting ps = mSettings.mPackages.get(packageName); 14569 if (ps == null) { 14570 throw new IllegalArgumentException("Unknown target package " + packageName); 14571 } 14572 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14573 throw new IllegalArgumentException("Unknown target package " + packageName); 14574 } 14575 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14576 throw new IllegalArgumentException("Calling package " + callerPackageName 14577 + " is not installer for " + packageName); 14578 } 14579 14580 if (ps.categoryHint != categoryHint) { 14581 ps.categoryHint = categoryHint; 14582 scheduleWriteSettingsLocked(); 14583 } 14584 } 14585 } 14586 14587 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14588 // Queue up an async operation since the package installation may take a little while. 14589 mHandler.post(new Runnable() { 14590 public void run() { 14591 mHandler.removeCallbacks(this); 14592 // Result object to be returned 14593 PackageInstalledInfo res = new PackageInstalledInfo(); 14594 res.setReturnCode(currentStatus); 14595 res.uid = -1; 14596 res.pkg = null; 14597 res.removedInfo = null; 14598 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14599 args.doPreInstall(res.returnCode); 14600 synchronized (mInstallLock) { 14601 installPackageTracedLI(args, res); 14602 } 14603 args.doPostInstall(res.returnCode, res.uid); 14604 } 14605 14606 // A restore should be performed at this point if (a) the install 14607 // succeeded, (b) the operation is not an update, and (c) the new 14608 // package has not opted out of backup participation. 14609 final boolean update = res.removedInfo != null 14610 && res.removedInfo.removedPackage != null; 14611 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14612 boolean doRestore = !update 14613 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14614 14615 // Set up the post-install work request bookkeeping. This will be used 14616 // and cleaned up by the post-install event handling regardless of whether 14617 // there's a restore pass performed. Token values are >= 1. 14618 int token; 14619 if (mNextInstallToken < 0) mNextInstallToken = 1; 14620 token = mNextInstallToken++; 14621 14622 PostInstallData data = new PostInstallData(args, res); 14623 mRunningInstalls.put(token, data); 14624 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14625 14626 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14627 // Pass responsibility to the Backup Manager. It will perform a 14628 // restore if appropriate, then pass responsibility back to the 14629 // Package Manager to run the post-install observer callbacks 14630 // and broadcasts. 14631 IBackupManager bm = IBackupManager.Stub.asInterface( 14632 ServiceManager.getService(Context.BACKUP_SERVICE)); 14633 if (bm != null) { 14634 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14635 + " to BM for possible restore"); 14636 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14637 try { 14638 // TODO: http://b/22388012 14639 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14640 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14641 } else { 14642 doRestore = false; 14643 } 14644 } catch (RemoteException e) { 14645 // can't happen; the backup manager is local 14646 } catch (Exception e) { 14647 Slog.e(TAG, "Exception trying to enqueue restore", e); 14648 doRestore = false; 14649 } 14650 } else { 14651 Slog.e(TAG, "Backup Manager not found!"); 14652 doRestore = false; 14653 } 14654 } 14655 14656 if (!doRestore) { 14657 // No restore possible, or the Backup Manager was mysteriously not 14658 // available -- just fire the post-install work request directly. 14659 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14660 14661 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14662 14663 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14664 mHandler.sendMessage(msg); 14665 } 14666 } 14667 }); 14668 } 14669 14670 /** 14671 * Callback from PackageSettings whenever an app is first transitioned out of the 14672 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14673 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14674 * here whether the app is the target of an ongoing install, and only send the 14675 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14676 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14677 * handling. 14678 */ 14679 void notifyFirstLaunch(final String packageName, final String installerPackage, 14680 final int userId) { 14681 // Serialize this with the rest of the install-process message chain. In the 14682 // restore-at-install case, this Runnable will necessarily run before the 14683 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14684 // are coherent. In the non-restore case, the app has already completed install 14685 // and been launched through some other means, so it is not in a problematic 14686 // state for observers to see the FIRST_LAUNCH signal. 14687 mHandler.post(new Runnable() { 14688 @Override 14689 public void run() { 14690 for (int i = 0; i < mRunningInstalls.size(); i++) { 14691 final PostInstallData data = mRunningInstalls.valueAt(i); 14692 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14693 continue; 14694 } 14695 if (packageName.equals(data.res.pkg.applicationInfo.packageName)) { 14696 // right package; but is it for the right user? 14697 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14698 if (userId == data.res.newUsers[uIndex]) { 14699 if (DEBUG_BACKUP) { 14700 Slog.i(TAG, "Package " + packageName 14701 + " being restored so deferring FIRST_LAUNCH"); 14702 } 14703 return; 14704 } 14705 } 14706 } 14707 } 14708 // didn't find it, so not being restored 14709 if (DEBUG_BACKUP) { 14710 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH"); 14711 } 14712 final boolean isInstantApp = isInstantApp(packageName, userId); 14713 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 14714 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 14715 sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds); 14716 } 14717 }); 14718 } 14719 14720 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, 14721 int[] userIds, int[] instantUserIds) { 14722 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14723 installerPkg, null, userIds, instantUserIds); 14724 } 14725 14726 private abstract class HandlerParams { 14727 private static final int MAX_RETRIES = 4; 14728 14729 /** 14730 * Number of times startCopy() has been attempted and had a non-fatal 14731 * error. 14732 */ 14733 private int mRetries = 0; 14734 14735 /** User handle for the user requesting the information or installation. */ 14736 private final UserHandle mUser; 14737 String traceMethod; 14738 int traceCookie; 14739 14740 HandlerParams(UserHandle user) { 14741 mUser = user; 14742 } 14743 14744 UserHandle getUser() { 14745 return mUser; 14746 } 14747 14748 HandlerParams setTraceMethod(String traceMethod) { 14749 this.traceMethod = traceMethod; 14750 return this; 14751 } 14752 14753 HandlerParams setTraceCookie(int traceCookie) { 14754 this.traceCookie = traceCookie; 14755 return this; 14756 } 14757 14758 final boolean startCopy() { 14759 boolean res; 14760 try { 14761 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14762 14763 if (++mRetries > MAX_RETRIES) { 14764 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14765 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14766 handleServiceError(); 14767 return false; 14768 } else { 14769 handleStartCopy(); 14770 res = true; 14771 } 14772 } catch (RemoteException e) { 14773 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14774 mHandler.sendEmptyMessage(MCS_RECONNECT); 14775 res = false; 14776 } 14777 handleReturnCode(); 14778 return res; 14779 } 14780 14781 final void serviceError() { 14782 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14783 handleServiceError(); 14784 handleReturnCode(); 14785 } 14786 14787 abstract void handleStartCopy() throws RemoteException; 14788 abstract void handleServiceError(); 14789 abstract void handleReturnCode(); 14790 } 14791 14792 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14793 for (File path : paths) { 14794 try { 14795 mcs.clearDirectory(path.getAbsolutePath()); 14796 } catch (RemoteException e) { 14797 } 14798 } 14799 } 14800 14801 static class OriginInfo { 14802 /** 14803 * Location where install is coming from, before it has been 14804 * copied/renamed into place. This could be a single monolithic APK 14805 * file, or a cluster directory. This location may be untrusted. 14806 */ 14807 final File file; 14808 14809 /** 14810 * Flag indicating that {@link #file} or {@link #cid} has already been 14811 * staged, meaning downstream users don't need to defensively copy the 14812 * contents. 14813 */ 14814 final boolean staged; 14815 14816 /** 14817 * Flag indicating that {@link #file} or {@link #cid} is an already 14818 * installed app that is being moved. 14819 */ 14820 final boolean existing; 14821 14822 final String resolvedPath; 14823 final File resolvedFile; 14824 14825 static OriginInfo fromNothing() { 14826 return new OriginInfo(null, false, false); 14827 } 14828 14829 static OriginInfo fromUntrustedFile(File file) { 14830 return new OriginInfo(file, false, false); 14831 } 14832 14833 static OriginInfo fromExistingFile(File file) { 14834 return new OriginInfo(file, false, true); 14835 } 14836 14837 static OriginInfo fromStagedFile(File file) { 14838 return new OriginInfo(file, true, false); 14839 } 14840 14841 private OriginInfo(File file, boolean staged, boolean existing) { 14842 this.file = file; 14843 this.staged = staged; 14844 this.existing = existing; 14845 14846 if (file != null) { 14847 resolvedPath = file.getAbsolutePath(); 14848 resolvedFile = file; 14849 } else { 14850 resolvedPath = null; 14851 resolvedFile = null; 14852 } 14853 } 14854 } 14855 14856 static class MoveInfo { 14857 final int moveId; 14858 final String fromUuid; 14859 final String toUuid; 14860 final String packageName; 14861 final String dataAppName; 14862 final int appId; 14863 final String seinfo; 14864 final int targetSdkVersion; 14865 14866 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14867 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14868 this.moveId = moveId; 14869 this.fromUuid = fromUuid; 14870 this.toUuid = toUuid; 14871 this.packageName = packageName; 14872 this.dataAppName = dataAppName; 14873 this.appId = appId; 14874 this.seinfo = seinfo; 14875 this.targetSdkVersion = targetSdkVersion; 14876 } 14877 } 14878 14879 static class VerificationInfo { 14880 /** A constant used to indicate that a uid value is not present. */ 14881 public static final int NO_UID = -1; 14882 14883 /** URI referencing where the package was downloaded from. */ 14884 final Uri originatingUri; 14885 14886 /** HTTP referrer URI associated with the originatingURI. */ 14887 final Uri referrer; 14888 14889 /** UID of the application that the install request originated from. */ 14890 final int originatingUid; 14891 14892 /** UID of application requesting the install */ 14893 final int installerUid; 14894 14895 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14896 this.originatingUri = originatingUri; 14897 this.referrer = referrer; 14898 this.originatingUid = originatingUid; 14899 this.installerUid = installerUid; 14900 } 14901 } 14902 14903 class InstallParams extends HandlerParams { 14904 final OriginInfo origin; 14905 final MoveInfo move; 14906 final IPackageInstallObserver2 observer; 14907 int installFlags; 14908 final String installerPackageName; 14909 final String volumeUuid; 14910 private InstallArgs mArgs; 14911 private int mRet; 14912 final String packageAbiOverride; 14913 final String[] grantedRuntimePermissions; 14914 final VerificationInfo verificationInfo; 14915 final PackageParser.SigningDetails signingDetails; 14916 final int installReason; 14917 14918 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14919 int installFlags, String installerPackageName, String volumeUuid, 14920 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14921 String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) { 14922 super(user); 14923 this.origin = origin; 14924 this.move = move; 14925 this.observer = observer; 14926 this.installFlags = installFlags; 14927 this.installerPackageName = installerPackageName; 14928 this.volumeUuid = volumeUuid; 14929 this.verificationInfo = verificationInfo; 14930 this.packageAbiOverride = packageAbiOverride; 14931 this.grantedRuntimePermissions = grantedPermissions; 14932 this.signingDetails = signingDetails; 14933 this.installReason = installReason; 14934 } 14935 14936 @Override 14937 public String toString() { 14938 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14939 + " file=" + origin.file + "}"; 14940 } 14941 14942 private int installLocationPolicy(PackageInfoLite pkgLite) { 14943 String packageName = pkgLite.packageName; 14944 int installLocation = pkgLite.installLocation; 14945 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14946 // reader 14947 synchronized (mPackages) { 14948 // Currently installed package which the new package is attempting to replace or 14949 // null if no such package is installed. 14950 PackageParser.Package installedPkg = mPackages.get(packageName); 14951 // Package which currently owns the data which the new package will own if installed. 14952 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14953 // will be null whereas dataOwnerPkg will contain information about the package 14954 // which was uninstalled while keeping its data. 14955 PackageParser.Package dataOwnerPkg = installedPkg; 14956 if (dataOwnerPkg == null) { 14957 PackageSetting ps = mSettings.mPackages.get(packageName); 14958 if (ps != null) { 14959 dataOwnerPkg = ps.pkg; 14960 } 14961 } 14962 14963 if (dataOwnerPkg != null) { 14964 // If installed, the package will get access to data left on the device by its 14965 // predecessor. As a security measure, this is permited only if this is not a 14966 // version downgrade or if the predecessor package is marked as debuggable and 14967 // a downgrade is explicitly requested. 14968 // 14969 // On debuggable platform builds, downgrades are permitted even for 14970 // non-debuggable packages to make testing easier. Debuggable platform builds do 14971 // not offer security guarantees and thus it's OK to disable some security 14972 // mechanisms to make debugging/testing easier on those builds. However, even on 14973 // debuggable builds downgrades of packages are permitted only if requested via 14974 // installFlags. This is because we aim to keep the behavior of debuggable 14975 // platform builds as close as possible to the behavior of non-debuggable 14976 // platform builds. 14977 final boolean downgradeRequested = 14978 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14979 final boolean packageDebuggable = 14980 (dataOwnerPkg.applicationInfo.flags 14981 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14982 final boolean downgradePermitted = 14983 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14984 if (!downgradePermitted) { 14985 try { 14986 checkDowngrade(dataOwnerPkg, pkgLite); 14987 } catch (PackageManagerException e) { 14988 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14989 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14990 } 14991 } 14992 } 14993 14994 if (installedPkg != null) { 14995 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14996 // Check for updated system application. 14997 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14998 if (onSd) { 14999 Slog.w(TAG, "Cannot install update to system app on sdcard"); 15000 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 15001 } 15002 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15003 } else { 15004 if (onSd) { 15005 // Install flag overrides everything. 15006 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15007 } 15008 // If current upgrade specifies particular preference 15009 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 15010 // Application explicitly specified internal. 15011 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15012 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 15013 // App explictly prefers external. Let policy decide 15014 } else { 15015 // Prefer previous location 15016 if (isExternal(installedPkg)) { 15017 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15018 } 15019 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15020 } 15021 } 15022 } else { 15023 // Invalid install. Return error code 15024 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 15025 } 15026 } 15027 } 15028 // All the special cases have been taken care of. 15029 // Return result based on recommended install location. 15030 if (onSd) { 15031 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15032 } 15033 return pkgLite.recommendedInstallLocation; 15034 } 15035 15036 /* 15037 * Invoke remote method to get package information and install 15038 * location values. Override install location based on default 15039 * policy if needed and then create install arguments based 15040 * on the install location. 15041 */ 15042 public void handleStartCopy() throws RemoteException { 15043 int ret = PackageManager.INSTALL_SUCCEEDED; 15044 15045 // If we're already staged, we've firmly committed to an install location 15046 if (origin.staged) { 15047 if (origin.file != null) { 15048 installFlags |= PackageManager.INSTALL_INTERNAL; 15049 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15050 } else { 15051 throw new IllegalStateException("Invalid stage location"); 15052 } 15053 } 15054 15055 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15056 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 15057 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15058 PackageInfoLite pkgLite = null; 15059 15060 if (onInt && onSd) { 15061 // Check if both bits are set. 15062 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 15063 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15064 } else if (onSd && ephemeral) { 15065 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 15066 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15067 } else { 15068 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 15069 packageAbiOverride); 15070 15071 if (DEBUG_INSTANT && ephemeral) { 15072 Slog.v(TAG, "pkgLite for install: " + pkgLite); 15073 } 15074 15075 /* 15076 * If we have too little free space, try to free cache 15077 * before giving up. 15078 */ 15079 if (!origin.staged && pkgLite.recommendedInstallLocation 15080 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15081 // TODO: focus freeing disk space on the target device 15082 final StorageManager storage = StorageManager.from(mContext); 15083 final long lowThreshold = storage.getStorageLowBytes( 15084 Environment.getDataDirectory()); 15085 15086 final long sizeBytes = mContainerService.calculateInstalledSize( 15087 origin.resolvedPath, packageAbiOverride); 15088 15089 try { 15090 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 15091 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 15092 installFlags, packageAbiOverride); 15093 } catch (InstallerException e) { 15094 Slog.w(TAG, "Failed to free cache", e); 15095 } 15096 15097 /* 15098 * The cache free must have deleted the file we 15099 * downloaded to install. 15100 * 15101 * TODO: fix the "freeCache" call to not delete 15102 * the file we care about. 15103 */ 15104 if (pkgLite.recommendedInstallLocation 15105 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15106 pkgLite.recommendedInstallLocation 15107 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 15108 } 15109 } 15110 } 15111 15112 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15113 int loc = pkgLite.recommendedInstallLocation; 15114 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 15115 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15116 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 15117 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 15118 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15119 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15120 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 15121 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 15122 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15123 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 15124 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 15125 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 15126 } else { 15127 // Override with defaults if needed. 15128 loc = installLocationPolicy(pkgLite); 15129 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 15130 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 15131 } else if (!onSd && !onInt) { 15132 // Override install location with flags 15133 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 15134 // Set the flag to install on external media. 15135 installFlags |= PackageManager.INSTALL_EXTERNAL; 15136 installFlags &= ~PackageManager.INSTALL_INTERNAL; 15137 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 15138 if (DEBUG_INSTANT) { 15139 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 15140 } 15141 installFlags |= PackageManager.INSTALL_INSTANT_APP; 15142 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 15143 |PackageManager.INSTALL_INTERNAL); 15144 } else { 15145 // Make sure the flag for installing on external 15146 // media is unset 15147 installFlags |= PackageManager.INSTALL_INTERNAL; 15148 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15149 } 15150 } 15151 } 15152 } 15153 15154 final InstallArgs args = createInstallArgs(this); 15155 mArgs = args; 15156 15157 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15158 // TODO: http://b/22976637 15159 // Apps installed for "all" users use the device owner to verify the app 15160 UserHandle verifierUser = getUser(); 15161 if (verifierUser == UserHandle.ALL) { 15162 verifierUser = UserHandle.SYSTEM; 15163 } 15164 15165 /* 15166 * Determine if we have any installed package verifiers. If we 15167 * do, then we'll defer to them to verify the packages. 15168 */ 15169 final int requiredUid = mRequiredVerifierPackage == null ? -1 15170 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15171 verifierUser.getIdentifier()); 15172 final int installerUid = 15173 verificationInfo == null ? -1 : verificationInfo.installerUid; 15174 if (!origin.existing && requiredUid != -1 15175 && isVerificationEnabled( 15176 verifierUser.getIdentifier(), installFlags, installerUid)) { 15177 final Intent verification = new Intent( 15178 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 15179 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 15180 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 15181 PACKAGE_MIME_TYPE); 15182 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15183 15184 // Query all live verifiers based on current user state 15185 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 15186 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 15187 false /*allowDynamicSplits*/); 15188 15189 if (DEBUG_VERIFY) { 15190 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 15191 + verification.toString() + " with " + pkgLite.verifiers.length 15192 + " optional verifiers"); 15193 } 15194 15195 final int verificationId = mPendingVerificationToken++; 15196 15197 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 15198 15199 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 15200 installerPackageName); 15201 15202 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 15203 installFlags); 15204 15205 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 15206 pkgLite.packageName); 15207 15208 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 15209 pkgLite.versionCode); 15210 15211 verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE, 15212 pkgLite.getLongVersionCode()); 15213 15214 if (verificationInfo != null) { 15215 if (verificationInfo.originatingUri != null) { 15216 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 15217 verificationInfo.originatingUri); 15218 } 15219 if (verificationInfo.referrer != null) { 15220 verification.putExtra(Intent.EXTRA_REFERRER, 15221 verificationInfo.referrer); 15222 } 15223 if (verificationInfo.originatingUid >= 0) { 15224 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 15225 verificationInfo.originatingUid); 15226 } 15227 if (verificationInfo.installerUid >= 0) { 15228 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 15229 verificationInfo.installerUid); 15230 } 15231 } 15232 15233 final PackageVerificationState verificationState = new PackageVerificationState( 15234 requiredUid, args); 15235 15236 mPendingVerification.append(verificationId, verificationState); 15237 15238 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 15239 receivers, verificationState); 15240 15241 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 15242 final long idleDuration = getVerificationTimeout(); 15243 15244 /* 15245 * If any sufficient verifiers were listed in the package 15246 * manifest, attempt to ask them. 15247 */ 15248 if (sufficientVerifiers != null) { 15249 final int N = sufficientVerifiers.size(); 15250 if (N == 0) { 15251 Slog.i(TAG, "Additional verifiers required, but none installed."); 15252 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 15253 } else { 15254 for (int i = 0; i < N; i++) { 15255 final ComponentName verifierComponent = sufficientVerifiers.get(i); 15256 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15257 verifierComponent.getPackageName(), idleDuration, 15258 verifierUser.getIdentifier(), false, "package verifier"); 15259 15260 final Intent sufficientIntent = new Intent(verification); 15261 sufficientIntent.setComponent(verifierComponent); 15262 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 15263 } 15264 } 15265 } 15266 15267 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 15268 mRequiredVerifierPackage, receivers); 15269 if (ret == PackageManager.INSTALL_SUCCEEDED 15270 && mRequiredVerifierPackage != null) { 15271 Trace.asyncTraceBegin( 15272 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 15273 /* 15274 * Send the intent to the required verification agent, 15275 * but only start the verification timeout after the 15276 * target BroadcastReceivers have run. 15277 */ 15278 verification.setComponent(requiredVerifierComponent); 15279 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15280 mRequiredVerifierPackage, idleDuration, 15281 verifierUser.getIdentifier(), false, "package verifier"); 15282 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 15283 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15284 new BroadcastReceiver() { 15285 @Override 15286 public void onReceive(Context context, Intent intent) { 15287 final Message msg = mHandler 15288 .obtainMessage(CHECK_PENDING_VERIFICATION); 15289 msg.arg1 = verificationId; 15290 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15291 } 15292 }, null, 0, null, null); 15293 15294 /* 15295 * We don't want the copy to proceed until verification 15296 * succeeds, so null out this field. 15297 */ 15298 mArgs = null; 15299 } 15300 } else { 15301 /* 15302 * No package verification is enabled, so immediately start 15303 * the remote call to initiate copy using temporary file. 15304 */ 15305 ret = args.copyApk(mContainerService, true); 15306 } 15307 } 15308 15309 mRet = ret; 15310 } 15311 15312 @Override 15313 void handleReturnCode() { 15314 // If mArgs is null, then MCS couldn't be reached. When it 15315 // reconnects, it will try again to install. At that point, this 15316 // will succeed. 15317 if (mArgs != null) { 15318 processPendingInstall(mArgs, mRet); 15319 } 15320 } 15321 15322 @Override 15323 void handleServiceError() { 15324 mArgs = createInstallArgs(this); 15325 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15326 } 15327 } 15328 15329 private InstallArgs createInstallArgs(InstallParams params) { 15330 if (params.move != null) { 15331 return new MoveInstallArgs(params); 15332 } else { 15333 return new FileInstallArgs(params); 15334 } 15335 } 15336 15337 /** 15338 * Create args that describe an existing installed package. Typically used 15339 * when cleaning up old installs, or used as a move source. 15340 */ 15341 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 15342 String resourcePath, String[] instructionSets) { 15343 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15344 } 15345 15346 static abstract class InstallArgs { 15347 /** @see InstallParams#origin */ 15348 final OriginInfo origin; 15349 /** @see InstallParams#move */ 15350 final MoveInfo move; 15351 15352 final IPackageInstallObserver2 observer; 15353 // Always refers to PackageManager flags only 15354 final int installFlags; 15355 final String installerPackageName; 15356 final String volumeUuid; 15357 final UserHandle user; 15358 final String abiOverride; 15359 final String[] installGrantPermissions; 15360 /** If non-null, drop an async trace when the install completes */ 15361 final String traceMethod; 15362 final int traceCookie; 15363 final PackageParser.SigningDetails signingDetails; 15364 final int installReason; 15365 15366 // The list of instruction sets supported by this app. This is currently 15367 // only used during the rmdex() phase to clean up resources. We can get rid of this 15368 // if we move dex files under the common app path. 15369 /* nullable */ String[] instructionSets; 15370 15371 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15372 int installFlags, String installerPackageName, String volumeUuid, 15373 UserHandle user, String[] instructionSets, 15374 String abiOverride, String[] installGrantPermissions, 15375 String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails, 15376 int installReason) { 15377 this.origin = origin; 15378 this.move = move; 15379 this.installFlags = installFlags; 15380 this.observer = observer; 15381 this.installerPackageName = installerPackageName; 15382 this.volumeUuid = volumeUuid; 15383 this.user = user; 15384 this.instructionSets = instructionSets; 15385 this.abiOverride = abiOverride; 15386 this.installGrantPermissions = installGrantPermissions; 15387 this.traceMethod = traceMethod; 15388 this.traceCookie = traceCookie; 15389 this.signingDetails = signingDetails; 15390 this.installReason = installReason; 15391 } 15392 15393 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15394 abstract int doPreInstall(int status); 15395 15396 /** 15397 * Rename package into final resting place. All paths on the given 15398 * scanned package should be updated to reflect the rename. 15399 */ 15400 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15401 abstract int doPostInstall(int status, int uid); 15402 15403 /** @see PackageSettingBase#codePathString */ 15404 abstract String getCodePath(); 15405 /** @see PackageSettingBase#resourcePathString */ 15406 abstract String getResourcePath(); 15407 15408 // Need installer lock especially for dex file removal. 15409 abstract void cleanUpResourcesLI(); 15410 abstract boolean doPostDeleteLI(boolean delete); 15411 15412 /** 15413 * Called before the source arguments are copied. This is used mostly 15414 * for MoveParams when it needs to read the source file to put it in the 15415 * destination. 15416 */ 15417 int doPreCopy() { 15418 return PackageManager.INSTALL_SUCCEEDED; 15419 } 15420 15421 /** 15422 * Called after the source arguments are copied. This is used mostly for 15423 * MoveParams when it needs to read the source file to put it in the 15424 * destination. 15425 */ 15426 int doPostCopy(int uid) { 15427 return PackageManager.INSTALL_SUCCEEDED; 15428 } 15429 15430 protected boolean isFwdLocked() { 15431 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15432 } 15433 15434 protected boolean isExternalAsec() { 15435 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15436 } 15437 15438 protected boolean isEphemeral() { 15439 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15440 } 15441 15442 UserHandle getUser() { 15443 return user; 15444 } 15445 } 15446 15447 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15448 if (!allCodePaths.isEmpty()) { 15449 if (instructionSets == null) { 15450 throw new IllegalStateException("instructionSet == null"); 15451 } 15452 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15453 for (String codePath : allCodePaths) { 15454 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15455 try { 15456 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15457 } catch (InstallerException ignored) { 15458 } 15459 } 15460 } 15461 } 15462 } 15463 15464 /** 15465 * Logic to handle installation of non-ASEC applications, including copying 15466 * and renaming logic. 15467 */ 15468 class FileInstallArgs extends InstallArgs { 15469 private File codeFile; 15470 private File resourceFile; 15471 15472 // Example topology: 15473 // /data/app/com.example/base.apk 15474 // /data/app/com.example/split_foo.apk 15475 // /data/app/com.example/lib/arm/libfoo.so 15476 // /data/app/com.example/lib/arm64/libfoo.so 15477 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15478 15479 /** New install */ 15480 FileInstallArgs(InstallParams params) { 15481 super(params.origin, params.move, params.observer, params.installFlags, 15482 params.installerPackageName, params.volumeUuid, 15483 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15484 params.grantedRuntimePermissions, 15485 params.traceMethod, params.traceCookie, params.signingDetails, 15486 params.installReason); 15487 if (isFwdLocked()) { 15488 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15489 } 15490 } 15491 15492 /** Existing install */ 15493 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15494 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15495 null, null, null, 0, PackageParser.SigningDetails.UNKNOWN, 15496 PackageManager.INSTALL_REASON_UNKNOWN); 15497 this.codeFile = (codePath != null) ? new File(codePath) : null; 15498 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15499 } 15500 15501 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15502 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15503 try { 15504 return doCopyApk(imcs, temp); 15505 } finally { 15506 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15507 } 15508 } 15509 15510 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15511 if (origin.staged) { 15512 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15513 codeFile = origin.file; 15514 resourceFile = origin.file; 15515 return PackageManager.INSTALL_SUCCEEDED; 15516 } 15517 15518 try { 15519 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15520 final File tempDir = 15521 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15522 codeFile = tempDir; 15523 resourceFile = tempDir; 15524 } catch (IOException e) { 15525 Slog.w(TAG, "Failed to create copy file: " + e); 15526 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15527 } 15528 15529 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15530 @Override 15531 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15532 if (!FileUtils.isValidExtFilename(name)) { 15533 throw new IllegalArgumentException("Invalid filename: " + name); 15534 } 15535 try { 15536 final File file = new File(codeFile, name); 15537 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15538 O_RDWR | O_CREAT, 0644); 15539 Os.chmod(file.getAbsolutePath(), 0644); 15540 return new ParcelFileDescriptor(fd); 15541 } catch (ErrnoException e) { 15542 throw new RemoteException("Failed to open: " + e.getMessage()); 15543 } 15544 } 15545 }; 15546 15547 int ret = PackageManager.INSTALL_SUCCEEDED; 15548 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15549 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15550 Slog.e(TAG, "Failed to copy package"); 15551 return ret; 15552 } 15553 15554 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15555 NativeLibraryHelper.Handle handle = null; 15556 try { 15557 handle = NativeLibraryHelper.Handle.create(codeFile); 15558 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15559 abiOverride); 15560 } catch (IOException e) { 15561 Slog.e(TAG, "Copying native libraries failed", e); 15562 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15563 } finally { 15564 IoUtils.closeQuietly(handle); 15565 } 15566 15567 return ret; 15568 } 15569 15570 int doPreInstall(int status) { 15571 if (status != PackageManager.INSTALL_SUCCEEDED) { 15572 cleanUp(); 15573 } 15574 return status; 15575 } 15576 15577 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15578 if (status != PackageManager.INSTALL_SUCCEEDED) { 15579 cleanUp(); 15580 return false; 15581 } 15582 15583 final File targetDir = codeFile.getParentFile(); 15584 final File beforeCodeFile = codeFile; 15585 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15586 15587 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15588 try { 15589 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15590 } catch (ErrnoException e) { 15591 Slog.w(TAG, "Failed to rename", e); 15592 return false; 15593 } 15594 15595 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15596 Slog.w(TAG, "Failed to restorecon"); 15597 return false; 15598 } 15599 15600 // Reflect the rename internally 15601 codeFile = afterCodeFile; 15602 resourceFile = afterCodeFile; 15603 15604 // Reflect the rename in scanned details 15605 try { 15606 pkg.setCodePath(afterCodeFile.getCanonicalPath()); 15607 } catch (IOException e) { 15608 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e); 15609 return false; 15610 } 15611 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15612 afterCodeFile, pkg.baseCodePath)); 15613 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15614 afterCodeFile, pkg.splitCodePaths)); 15615 15616 // Reflect the rename in app info 15617 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15618 pkg.setApplicationInfoCodePath(pkg.codePath); 15619 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15620 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15621 pkg.setApplicationInfoResourcePath(pkg.codePath); 15622 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15623 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15624 15625 return true; 15626 } 15627 15628 int doPostInstall(int status, int uid) { 15629 if (status != PackageManager.INSTALL_SUCCEEDED) { 15630 cleanUp(); 15631 } 15632 return status; 15633 } 15634 15635 @Override 15636 String getCodePath() { 15637 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15638 } 15639 15640 @Override 15641 String getResourcePath() { 15642 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15643 } 15644 15645 private boolean cleanUp() { 15646 if (codeFile == null || !codeFile.exists()) { 15647 return false; 15648 } 15649 15650 removeCodePathLI(codeFile); 15651 15652 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15653 resourceFile.delete(); 15654 } 15655 15656 return true; 15657 } 15658 15659 void cleanUpResourcesLI() { 15660 // Try enumerating all code paths before deleting 15661 List<String> allCodePaths = Collections.EMPTY_LIST; 15662 if (codeFile != null && codeFile.exists()) { 15663 try { 15664 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15665 allCodePaths = pkg.getAllCodePaths(); 15666 } catch (PackageParserException e) { 15667 // Ignored; we tried our best 15668 } 15669 } 15670 15671 cleanUp(); 15672 removeDexFiles(allCodePaths, instructionSets); 15673 } 15674 15675 boolean doPostDeleteLI(boolean delete) { 15676 // XXX err, shouldn't we respect the delete flag? 15677 cleanUpResourcesLI(); 15678 return true; 15679 } 15680 } 15681 15682 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15683 PackageManagerException { 15684 if (copyRet < 0) { 15685 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15686 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15687 throw new PackageManagerException(copyRet, message); 15688 } 15689 } 15690 } 15691 15692 /** 15693 * Extract the StorageManagerService "container ID" from the full code path of an 15694 * .apk. 15695 */ 15696 static String cidFromCodePath(String fullCodePath) { 15697 int eidx = fullCodePath.lastIndexOf("/"); 15698 String subStr1 = fullCodePath.substring(0, eidx); 15699 int sidx = subStr1.lastIndexOf("/"); 15700 return subStr1.substring(sidx+1, eidx); 15701 } 15702 15703 /** 15704 * Logic to handle movement of existing installed applications. 15705 */ 15706 class MoveInstallArgs extends InstallArgs { 15707 private File codeFile; 15708 private File resourceFile; 15709 15710 /** New install */ 15711 MoveInstallArgs(InstallParams params) { 15712 super(params.origin, params.move, params.observer, params.installFlags, 15713 params.installerPackageName, params.volumeUuid, 15714 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15715 params.grantedRuntimePermissions, 15716 params.traceMethod, params.traceCookie, params.signingDetails, 15717 params.installReason); 15718 } 15719 15720 int copyApk(IMediaContainerService imcs, boolean temp) { 15721 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15722 + move.fromUuid + " to " + move.toUuid); 15723 synchronized (mInstaller) { 15724 try { 15725 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15726 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15727 } catch (InstallerException e) { 15728 Slog.w(TAG, "Failed to move app", e); 15729 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15730 } 15731 } 15732 15733 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15734 resourceFile = codeFile; 15735 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15736 15737 return PackageManager.INSTALL_SUCCEEDED; 15738 } 15739 15740 int doPreInstall(int status) { 15741 if (status != PackageManager.INSTALL_SUCCEEDED) { 15742 cleanUp(move.toUuid); 15743 } 15744 return status; 15745 } 15746 15747 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15748 if (status != PackageManager.INSTALL_SUCCEEDED) { 15749 cleanUp(move.toUuid); 15750 return false; 15751 } 15752 15753 // Reflect the move in app info 15754 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15755 pkg.setApplicationInfoCodePath(pkg.codePath); 15756 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15757 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15758 pkg.setApplicationInfoResourcePath(pkg.codePath); 15759 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15760 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15761 15762 return true; 15763 } 15764 15765 int doPostInstall(int status, int uid) { 15766 if (status == PackageManager.INSTALL_SUCCEEDED) { 15767 cleanUp(move.fromUuid); 15768 } else { 15769 cleanUp(move.toUuid); 15770 } 15771 return status; 15772 } 15773 15774 @Override 15775 String getCodePath() { 15776 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15777 } 15778 15779 @Override 15780 String getResourcePath() { 15781 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15782 } 15783 15784 private boolean cleanUp(String volumeUuid) { 15785 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15786 move.dataAppName); 15787 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15788 final int[] userIds = sUserManager.getUserIds(); 15789 synchronized (mInstallLock) { 15790 // Clean up both app data and code 15791 // All package moves are frozen until finished 15792 for (int userId : userIds) { 15793 try { 15794 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15795 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15796 } catch (InstallerException e) { 15797 Slog.w(TAG, String.valueOf(e)); 15798 } 15799 } 15800 removeCodePathLI(codeFile); 15801 } 15802 return true; 15803 } 15804 15805 void cleanUpResourcesLI() { 15806 throw new UnsupportedOperationException(); 15807 } 15808 15809 boolean doPostDeleteLI(boolean delete) { 15810 throw new UnsupportedOperationException(); 15811 } 15812 } 15813 15814 static String getAsecPackageName(String packageCid) { 15815 int idx = packageCid.lastIndexOf("-"); 15816 if (idx == -1) { 15817 return packageCid; 15818 } 15819 return packageCid.substring(0, idx); 15820 } 15821 15822 // Utility method used to create code paths based on package name and available index. 15823 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15824 String idxStr = ""; 15825 int idx = 1; 15826 // Fall back to default value of idx=1 if prefix is not 15827 // part of oldCodePath 15828 if (oldCodePath != null) { 15829 String subStr = oldCodePath; 15830 // Drop the suffix right away 15831 if (suffix != null && subStr.endsWith(suffix)) { 15832 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15833 } 15834 // If oldCodePath already contains prefix find out the 15835 // ending index to either increment or decrement. 15836 int sidx = subStr.lastIndexOf(prefix); 15837 if (sidx != -1) { 15838 subStr = subStr.substring(sidx + prefix.length()); 15839 if (subStr != null) { 15840 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15841 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15842 } 15843 try { 15844 idx = Integer.parseInt(subStr); 15845 if (idx <= 1) { 15846 idx++; 15847 } else { 15848 idx--; 15849 } 15850 } catch(NumberFormatException e) { 15851 } 15852 } 15853 } 15854 } 15855 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15856 return prefix + idxStr; 15857 } 15858 15859 private File getNextCodePath(File targetDir, String packageName) { 15860 File result; 15861 SecureRandom random = new SecureRandom(); 15862 byte[] bytes = new byte[16]; 15863 do { 15864 random.nextBytes(bytes); 15865 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15866 result = new File(targetDir, packageName + "-" + suffix); 15867 } while (result.exists()); 15868 return result; 15869 } 15870 15871 // Utility method that returns the relative package path with respect 15872 // to the installation directory. Like say for /data/data/com.test-1.apk 15873 // string com.test-1 is returned. 15874 static String deriveCodePathName(String codePath) { 15875 if (codePath == null) { 15876 return null; 15877 } 15878 final File codeFile = new File(codePath); 15879 final String name = codeFile.getName(); 15880 if (codeFile.isDirectory()) { 15881 return name; 15882 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15883 final int lastDot = name.lastIndexOf('.'); 15884 return name.substring(0, lastDot); 15885 } else { 15886 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15887 return null; 15888 } 15889 } 15890 15891 static class PackageInstalledInfo { 15892 String name; 15893 int uid; 15894 // The set of users that originally had this package installed. 15895 int[] origUsers; 15896 // The set of users that now have this package installed. 15897 int[] newUsers; 15898 PackageParser.Package pkg; 15899 int returnCode; 15900 String returnMsg; 15901 String installerPackageName; 15902 PackageRemovedInfo removedInfo; 15903 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15904 15905 public void setError(int code, String msg) { 15906 setReturnCode(code); 15907 setReturnMessage(msg); 15908 Slog.w(TAG, msg); 15909 } 15910 15911 public void setError(String msg, PackageParserException e) { 15912 setReturnCode(e.error); 15913 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15914 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15915 for (int i = 0; i < childCount; i++) { 15916 addedChildPackages.valueAt(i).setError(msg, e); 15917 } 15918 Slog.w(TAG, msg, e); 15919 } 15920 15921 public void setError(String msg, PackageManagerException e) { 15922 returnCode = e.error; 15923 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15924 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15925 for (int i = 0; i < childCount; i++) { 15926 addedChildPackages.valueAt(i).setError(msg, e); 15927 } 15928 Slog.w(TAG, msg, e); 15929 } 15930 15931 public void setReturnCode(int returnCode) { 15932 this.returnCode = returnCode; 15933 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15934 for (int i = 0; i < childCount; i++) { 15935 addedChildPackages.valueAt(i).returnCode = returnCode; 15936 } 15937 } 15938 15939 private void setReturnMessage(String returnMsg) { 15940 this.returnMsg = returnMsg; 15941 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15942 for (int i = 0; i < childCount; i++) { 15943 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15944 } 15945 } 15946 15947 // In some error cases we want to convey more info back to the observer 15948 String origPackage; 15949 String origPermission; 15950 } 15951 15952 /* 15953 * Install a non-existing package. 15954 */ 15955 private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15956 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15957 String volumeUuid, PackageInstalledInfo res, int installReason) { 15958 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15959 15960 // Remember this for later, in case we need to rollback this install 15961 String pkgName = pkg.packageName; 15962 15963 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15964 15965 synchronized(mPackages) { 15966 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15967 if (renamedPackage != null) { 15968 // A package with the same name is already installed, though 15969 // it has been renamed to an older name. The package we 15970 // are trying to install should be installed as an update to 15971 // the existing one, but that has not been requested, so bail. 15972 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15973 + " without first uninstalling package running as " 15974 + renamedPackage); 15975 return; 15976 } 15977 if (mPackages.containsKey(pkgName)) { 15978 // Don't allow installation over an existing package with the same name. 15979 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15980 + " without first uninstalling."); 15981 return; 15982 } 15983 } 15984 15985 try { 15986 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 15987 System.currentTimeMillis(), user); 15988 15989 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15990 15991 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15992 prepareAppDataAfterInstallLIF(newPackage); 15993 15994 } else { 15995 // Remove package from internal structures, but keep around any 15996 // data that might have already existed 15997 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15998 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15999 } 16000 } catch (PackageManagerException e) { 16001 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16002 } 16003 16004 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16005 } 16006 16007 private static void updateDigest(MessageDigest digest, File file) throws IOException { 16008 try (DigestInputStream digestStream = 16009 new DigestInputStream(new FileInputStream(file), digest)) { 16010 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 16011 } 16012 } 16013 16014 private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 16015 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 16016 PackageInstalledInfo res, int installReason) { 16017 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16018 16019 final PackageParser.Package oldPackage; 16020 final PackageSetting ps; 16021 final String pkgName = pkg.packageName; 16022 final int[] allUsers; 16023 final int[] installedUsers; 16024 16025 synchronized(mPackages) { 16026 oldPackage = mPackages.get(pkgName); 16027 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 16028 16029 // don't allow upgrade to target a release SDK from a pre-release SDK 16030 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 16031 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16032 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 16033 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16034 if (oldTargetsPreRelease 16035 && !newTargetsPreRelease 16036 && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 16037 Slog.w(TAG, "Can't install package targeting released sdk"); 16038 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 16039 return; 16040 } 16041 16042 ps = mSettings.mPackages.get(pkgName); 16043 16044 // verify signatures are valid 16045 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16046 if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) { 16047 if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) { 16048 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16049 "New package not signed by keys specified by upgrade-keysets: " 16050 + pkgName); 16051 return; 16052 } 16053 } else { 16054 // default to original signature matching 16055 if (compareSignatures(oldPackage.mSigningDetails.signatures, 16056 pkg.mSigningDetails.signatures) 16057 != PackageManager.SIGNATURE_MATCH) { 16058 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16059 "New package has a different signature: " + pkgName); 16060 return; 16061 } 16062 } 16063 16064 // don't allow a system upgrade unless the upgrade hash matches 16065 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) { 16066 byte[] digestBytes = null; 16067 try { 16068 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 16069 updateDigest(digest, new File(pkg.baseCodePath)); 16070 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 16071 for (String path : pkg.splitCodePaths) { 16072 updateDigest(digest, new File(path)); 16073 } 16074 } 16075 digestBytes = digest.digest(); 16076 } catch (NoSuchAlgorithmException | IOException e) { 16077 res.setError(INSTALL_FAILED_INVALID_APK, 16078 "Could not compute hash: " + pkgName); 16079 return; 16080 } 16081 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 16082 res.setError(INSTALL_FAILED_INVALID_APK, 16083 "New package fails restrict-update check: " + pkgName); 16084 return; 16085 } 16086 // retain upgrade restriction 16087 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 16088 } 16089 16090 // Check for shared user id changes 16091 String invalidPackageName = 16092 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 16093 if (invalidPackageName != null) { 16094 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 16095 "Package " + invalidPackageName + " tried to change user " 16096 + oldPackage.mSharedUserId); 16097 return; 16098 } 16099 16100 // check if the new package supports all of the abis which the old package supports 16101 boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null; 16102 boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null; 16103 if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) { 16104 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16105 "Update to package " + pkgName + " doesn't support multi arch"); 16106 return; 16107 } 16108 16109 // In case of rollback, remember per-user/profile install state 16110 allUsers = sUserManager.getUserIds(); 16111 installedUsers = ps.queryInstalledUsers(allUsers, true); 16112 16113 // don't allow an upgrade from full to ephemeral 16114 if (isInstantApp) { 16115 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 16116 for (int currentUser : allUsers) { 16117 if (!ps.getInstantApp(currentUser)) { 16118 // can't downgrade from full to instant 16119 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16120 + " for user: " + currentUser); 16121 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16122 return; 16123 } 16124 } 16125 } else if (!ps.getInstantApp(user.getIdentifier())) { 16126 // can't downgrade from full to instant 16127 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16128 + " for user: " + user.getIdentifier()); 16129 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16130 return; 16131 } 16132 } 16133 } 16134 16135 // Update what is removed 16136 res.removedInfo = new PackageRemovedInfo(this); 16137 res.removedInfo.uid = oldPackage.applicationInfo.uid; 16138 res.removedInfo.removedPackage = oldPackage.packageName; 16139 res.removedInfo.installerPackageName = ps.installerPackageName; 16140 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 16141 res.removedInfo.isUpdate = true; 16142 res.removedInfo.origUsers = installedUsers; 16143 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16144 for (int i = 0; i < installedUsers.length; i++) { 16145 final int userId = installedUsers[i]; 16146 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16147 } 16148 16149 final int childCount = (oldPackage.childPackages != null) 16150 ? oldPackage.childPackages.size() : 0; 16151 for (int i = 0; i < childCount; i++) { 16152 boolean childPackageUpdated = false; 16153 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16154 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16155 if (res.addedChildPackages != null) { 16156 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16157 if (childRes != null) { 16158 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16159 childRes.removedInfo.removedPackage = childPkg.packageName; 16160 if (childPs != null) { 16161 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16162 } 16163 childRes.removedInfo.isUpdate = true; 16164 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16165 childPackageUpdated = true; 16166 } 16167 } 16168 if (!childPackageUpdated) { 16169 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 16170 childRemovedRes.removedPackage = childPkg.packageName; 16171 if (childPs != null) { 16172 childRemovedRes.installerPackageName = childPs.installerPackageName; 16173 } 16174 childRemovedRes.isUpdate = false; 16175 childRemovedRes.dataRemoved = true; 16176 synchronized (mPackages) { 16177 if (childPs != null) { 16178 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16179 } 16180 } 16181 if (res.removedInfo.removedChildPackages == null) { 16182 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16183 } 16184 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16185 } 16186 } 16187 16188 boolean sysPkg = (isSystemApp(oldPackage)); 16189 if (sysPkg) { 16190 // Set the system/privileged/oem/vendor/product flags as needed 16191 final boolean privileged = 16192 (oldPackage.applicationInfo.privateFlags 16193 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16194 final boolean oem = 16195 (oldPackage.applicationInfo.privateFlags 16196 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 16197 final boolean vendor = 16198 (oldPackage.applicationInfo.privateFlags 16199 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 16200 final boolean product = 16201 (oldPackage.applicationInfo.privateFlags 16202 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 16203 final @ParseFlags int systemParseFlags = parseFlags; 16204 final @ScanFlags int systemScanFlags = scanFlags 16205 | SCAN_AS_SYSTEM 16206 | (privileged ? SCAN_AS_PRIVILEGED : 0) 16207 | (oem ? SCAN_AS_OEM : 0) 16208 | (vendor ? SCAN_AS_VENDOR : 0) 16209 | (product ? SCAN_AS_PRODUCT : 0); 16210 16211 replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags, 16212 user, allUsers, installerPackageName, res, installReason); 16213 } else { 16214 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 16215 user, allUsers, installerPackageName, res, installReason); 16216 } 16217 } 16218 16219 @Override 16220 public List<String> getPreviousCodePaths(String packageName) { 16221 final int callingUid = Binder.getCallingUid(); 16222 final List<String> result = new ArrayList<>(); 16223 if (getInstantAppPackageName(callingUid) != null) { 16224 return result; 16225 } 16226 final PackageSetting ps = mSettings.mPackages.get(packageName); 16227 if (ps != null 16228 && ps.oldCodePaths != null 16229 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 16230 result.addAll(ps.oldCodePaths); 16231 } 16232 return result; 16233 } 16234 16235 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16236 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16237 final @ScanFlags int scanFlags, UserHandle user, int[] allUsers, 16238 String installerPackageName, PackageInstalledInfo res, int installReason) { 16239 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16240 + deletedPackage); 16241 16242 String pkgName = deletedPackage.packageName; 16243 boolean deletedPkg = true; 16244 boolean addedPkg = false; 16245 boolean updatedSettings = false; 16246 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16247 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16248 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16249 16250 final long origUpdateTime = (pkg.mExtras != null) 16251 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16252 16253 // First delete the existing package while retaining the data directory 16254 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16255 res.removedInfo, true, pkg)) { 16256 // If the existing package wasn't successfully deleted 16257 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16258 deletedPkg = false; 16259 } else { 16260 // Successfully deleted the old package; proceed with replace. 16261 16262 // If deleted package lived in a container, give users a chance to 16263 // relinquish resources before killing. 16264 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16265 if (DEBUG_INSTALL) { 16266 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16267 } 16268 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16269 final ArrayList<String> pkgList = new ArrayList<String>(1); 16270 pkgList.add(deletedPackage.applicationInfo.packageName); 16271 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16272 } 16273 16274 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16275 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16276 16277 try { 16278 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 16279 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16280 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16281 installReason); 16282 16283 // Update the in-memory copy of the previous code paths. 16284 PackageSetting ps = mSettings.mPackages.get(pkgName); 16285 if (!killApp) { 16286 if (ps.oldCodePaths == null) { 16287 ps.oldCodePaths = new ArraySet<>(); 16288 } 16289 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16290 if (deletedPackage.splitCodePaths != null) { 16291 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16292 } 16293 } else { 16294 ps.oldCodePaths = null; 16295 } 16296 if (ps.childPackageNames != null) { 16297 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16298 final String childPkgName = ps.childPackageNames.get(i); 16299 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16300 childPs.oldCodePaths = ps.oldCodePaths; 16301 } 16302 } 16303 // set instant app status, but, only if it's explicitly specified 16304 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16305 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16306 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16307 prepareAppDataAfterInstallLIF(newPackage); 16308 addedPkg = true; 16309 mDexManager.notifyPackageUpdated(newPackage.packageName, 16310 newPackage.baseCodePath, newPackage.splitCodePaths); 16311 } catch (PackageManagerException e) { 16312 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16313 } 16314 } 16315 16316 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16317 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16318 16319 // Revert all internal state mutations and added folders for the failed install 16320 if (addedPkg) { 16321 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16322 res.removedInfo, true, null); 16323 } 16324 16325 // Restore the old package 16326 if (deletedPkg) { 16327 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16328 File restoreFile = new File(deletedPackage.codePath); 16329 // Parse old package 16330 boolean oldExternal = isExternal(deletedPackage); 16331 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16332 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16333 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16334 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16335 try { 16336 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16337 null); 16338 } catch (PackageManagerException e) { 16339 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16340 + e.getMessage()); 16341 return; 16342 } 16343 16344 synchronized (mPackages) { 16345 // Ensure the installer package name up to date 16346 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16347 16348 // Update permissions for restored package 16349 mPermissionManager.updatePermissions( 16350 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16351 mPermissionCallback); 16352 16353 mSettings.writeLPr(); 16354 } 16355 16356 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16357 } 16358 } else { 16359 synchronized (mPackages) { 16360 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16361 if (ps != null) { 16362 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16363 if (res.removedInfo.removedChildPackages != null) { 16364 final int childCount = res.removedInfo.removedChildPackages.size(); 16365 // Iterate in reverse as we may modify the collection 16366 for (int i = childCount - 1; i >= 0; i--) { 16367 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16368 if (res.addedChildPackages.containsKey(childPackageName)) { 16369 res.removedInfo.removedChildPackages.removeAt(i); 16370 } else { 16371 PackageRemovedInfo childInfo = res.removedInfo 16372 .removedChildPackages.valueAt(i); 16373 childInfo.removedForAllUsers = mPackages.get( 16374 childInfo.removedPackage) == null; 16375 } 16376 } 16377 } 16378 } 16379 } 16380 } 16381 } 16382 16383 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16384 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16385 final @ScanFlags int scanFlags, UserHandle user, 16386 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16387 int installReason) { 16388 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16389 + ", old=" + deletedPackage); 16390 16391 final boolean disabledSystem; 16392 16393 // Remove existing system package 16394 removePackageLI(deletedPackage, true); 16395 16396 synchronized (mPackages) { 16397 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16398 } 16399 if (!disabledSystem) { 16400 // We didn't need to disable the .apk as a current system package, 16401 // which means we are replacing another update that is already 16402 // installed. We need to make sure to delete the older one's .apk. 16403 res.removedInfo.args = createInstallArgsForExisting(0, 16404 deletedPackage.applicationInfo.getCodePath(), 16405 deletedPackage.applicationInfo.getResourcePath(), 16406 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16407 } else { 16408 res.removedInfo.args = null; 16409 } 16410 16411 // Successfully disabled the old package. Now proceed with re-installation 16412 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16413 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16414 16415 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16416 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16417 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16418 16419 PackageParser.Package newPackage = null; 16420 try { 16421 // Add the package to the internal data structures 16422 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 16423 16424 // Set the update and install times 16425 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16426 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16427 System.currentTimeMillis()); 16428 16429 // Update the package dynamic state if succeeded 16430 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16431 // Now that the install succeeded make sure we remove data 16432 // directories for any child package the update removed. 16433 final int deletedChildCount = (deletedPackage.childPackages != null) 16434 ? deletedPackage.childPackages.size() : 0; 16435 final int newChildCount = (newPackage.childPackages != null) 16436 ? newPackage.childPackages.size() : 0; 16437 for (int i = 0; i < deletedChildCount; i++) { 16438 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16439 boolean childPackageDeleted = true; 16440 for (int j = 0; j < newChildCount; j++) { 16441 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16442 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16443 childPackageDeleted = false; 16444 break; 16445 } 16446 } 16447 if (childPackageDeleted) { 16448 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16449 deletedChildPkg.packageName); 16450 if (ps != null && res.removedInfo.removedChildPackages != null) { 16451 PackageRemovedInfo removedChildRes = res.removedInfo 16452 .removedChildPackages.get(deletedChildPkg.packageName); 16453 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16454 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16455 } 16456 } 16457 } 16458 16459 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16460 installReason); 16461 prepareAppDataAfterInstallLIF(newPackage); 16462 16463 mDexManager.notifyPackageUpdated(newPackage.packageName, 16464 newPackage.baseCodePath, newPackage.splitCodePaths); 16465 } 16466 } catch (PackageManagerException e) { 16467 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16468 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16469 } 16470 16471 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16472 // Re installation failed. Restore old information 16473 // Remove new pkg information 16474 if (newPackage != null) { 16475 removeInstalledPackageLI(newPackage, true); 16476 } 16477 // Add back the old system package 16478 try { 16479 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16480 } catch (PackageManagerException e) { 16481 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16482 } 16483 16484 synchronized (mPackages) { 16485 if (disabledSystem) { 16486 enableSystemPackageLPw(deletedPackage); 16487 } 16488 16489 // Ensure the installer package name up to date 16490 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16491 16492 // Update permissions for restored package 16493 mPermissionManager.updatePermissions( 16494 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16495 mPermissionCallback); 16496 16497 mSettings.writeLPr(); 16498 } 16499 16500 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16501 + " after failed upgrade"); 16502 } 16503 } 16504 16505 /** 16506 * Checks whether the parent or any of the child packages have a change shared 16507 * user. For a package to be a valid update the shred users of the parent and 16508 * the children should match. We may later support changing child shared users. 16509 * @param oldPkg The updated package. 16510 * @param newPkg The update package. 16511 * @return The shared user that change between the versions. 16512 */ 16513 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16514 PackageParser.Package newPkg) { 16515 // Check parent shared user 16516 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16517 return newPkg.packageName; 16518 } 16519 // Check child shared users 16520 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16521 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16522 for (int i = 0; i < newChildCount; i++) { 16523 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16524 // If this child was present, did it have the same shared user? 16525 for (int j = 0; j < oldChildCount; j++) { 16526 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16527 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16528 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16529 return newChildPkg.packageName; 16530 } 16531 } 16532 } 16533 return null; 16534 } 16535 16536 private void removeNativeBinariesLI(PackageSetting ps) { 16537 // Remove the lib path for the parent package 16538 if (ps != null) { 16539 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16540 // Remove the lib path for the child packages 16541 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16542 for (int i = 0; i < childCount; i++) { 16543 PackageSetting childPs = null; 16544 synchronized (mPackages) { 16545 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16546 } 16547 if (childPs != null) { 16548 NativeLibraryHelper.removeNativeBinariesLI(childPs 16549 .legacyNativeLibraryPathString); 16550 } 16551 } 16552 } 16553 } 16554 16555 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16556 // Enable the parent package 16557 mSettings.enableSystemPackageLPw(pkg.packageName); 16558 // Enable the child packages 16559 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16560 for (int i = 0; i < childCount; i++) { 16561 PackageParser.Package childPkg = pkg.childPackages.get(i); 16562 mSettings.enableSystemPackageLPw(childPkg.packageName); 16563 } 16564 } 16565 16566 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16567 PackageParser.Package newPkg) { 16568 // Disable the parent package (parent always replaced) 16569 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16570 // Disable the child packages 16571 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16572 for (int i = 0; i < childCount; i++) { 16573 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16574 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16575 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16576 } 16577 return disabled; 16578 } 16579 16580 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16581 String installerPackageName) { 16582 // Enable the parent package 16583 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16584 // Enable the child packages 16585 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16586 for (int i = 0; i < childCount; i++) { 16587 PackageParser.Package childPkg = pkg.childPackages.get(i); 16588 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16589 } 16590 } 16591 16592 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16593 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16594 // Update the parent package setting 16595 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16596 res, user, installReason); 16597 // Update the child packages setting 16598 final int childCount = (newPackage.childPackages != null) 16599 ? newPackage.childPackages.size() : 0; 16600 for (int i = 0; i < childCount; i++) { 16601 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16602 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16603 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16604 childRes.origUsers, childRes, user, installReason); 16605 } 16606 } 16607 16608 private void updateSettingsInternalLI(PackageParser.Package pkg, 16609 String installerPackageName, int[] allUsers, int[] installedForUsers, 16610 PackageInstalledInfo res, UserHandle user, int installReason) { 16611 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16612 16613 String pkgName = pkg.packageName; 16614 synchronized (mPackages) { 16615 //write settings. the installStatus will be incomplete at this stage. 16616 //note that the new package setting would have already been 16617 //added to mPackages. It hasn't been persisted yet. 16618 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16619 // TODO: Remove this write? It's also written at the end of this method 16620 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16621 mSettings.writeLPr(); 16622 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16623 } 16624 16625 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath); 16626 synchronized (mPackages) { 16627// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions 16628 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 16629 mPermissionCallback); 16630 // For system-bundled packages, we assume that installing an upgraded version 16631 // of the package implies that the user actually wants to run that new code, 16632 // so we enable the package. 16633 PackageSetting ps = mSettings.mPackages.get(pkgName); 16634 final int userId = user.getIdentifier(); 16635 if (ps != null) { 16636 if (isSystemApp(pkg)) { 16637 if (DEBUG_INSTALL) { 16638 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16639 } 16640 // Enable system package for requested users 16641 if (res.origUsers != null) { 16642 for (int origUserId : res.origUsers) { 16643 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16644 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16645 origUserId, installerPackageName); 16646 } 16647 } 16648 } 16649 // Also convey the prior install/uninstall state 16650 if (allUsers != null && installedForUsers != null) { 16651 for (int currentUserId : allUsers) { 16652 final boolean installed = ArrayUtils.contains( 16653 installedForUsers, currentUserId); 16654 if (DEBUG_INSTALL) { 16655 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16656 } 16657 ps.setInstalled(installed, currentUserId); 16658 } 16659 // these install state changes will be persisted in the 16660 // upcoming call to mSettings.writeLPr(). 16661 } 16662 } 16663 // It's implied that when a user requests installation, they want the app to be 16664 // installed and enabled. 16665 if (userId != UserHandle.USER_ALL) { 16666 ps.setInstalled(true, userId); 16667 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16668 } 16669 16670 // When replacing an existing package, preserve the original install reason for all 16671 // users that had the package installed before. 16672 final Set<Integer> previousUserIds = new ArraySet<>(); 16673 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16674 final int installReasonCount = res.removedInfo.installReasons.size(); 16675 for (int i = 0; i < installReasonCount; i++) { 16676 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16677 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16678 ps.setInstallReason(previousInstallReason, previousUserId); 16679 previousUserIds.add(previousUserId); 16680 } 16681 } 16682 16683 // Set install reason for users that are having the package newly installed. 16684 if (userId == UserHandle.USER_ALL) { 16685 for (int currentUserId : sUserManager.getUserIds()) { 16686 if (!previousUserIds.contains(currentUserId)) { 16687 ps.setInstallReason(installReason, currentUserId); 16688 } 16689 } 16690 } else if (!previousUserIds.contains(userId)) { 16691 ps.setInstallReason(installReason, userId); 16692 } 16693 mSettings.writeKernelMappingLPr(ps); 16694 } 16695 res.name = pkgName; 16696 res.uid = pkg.applicationInfo.uid; 16697 res.pkg = pkg; 16698 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16699 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16700 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16701 //to update install status 16702 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16703 mSettings.writeLPr(); 16704 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16705 } 16706 16707 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16708 } 16709 16710 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16711 try { 16712 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16713 installPackageLI(args, res); 16714 } finally { 16715 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16716 } 16717 } 16718 16719 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16720 final int installFlags = args.installFlags; 16721 final String installerPackageName = args.installerPackageName; 16722 final String volumeUuid = args.volumeUuid; 16723 final File tmpPackageFile = new File(args.getCodePath()); 16724 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16725 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16726 || (args.volumeUuid != null)); 16727 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16728 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16729 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16730 final boolean virtualPreload = 16731 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 16732 boolean replace = false; 16733 @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16734 if (args.move != null) { 16735 // moving a complete application; perform an initial scan on the new install location 16736 scanFlags |= SCAN_INITIAL; 16737 } 16738 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16739 scanFlags |= SCAN_DONT_KILL_APP; 16740 } 16741 if (instantApp) { 16742 scanFlags |= SCAN_AS_INSTANT_APP; 16743 } 16744 if (fullApp) { 16745 scanFlags |= SCAN_AS_FULL_APP; 16746 } 16747 if (virtualPreload) { 16748 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 16749 } 16750 16751 // Result object to be returned 16752 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16753 res.installerPackageName = installerPackageName; 16754 16755 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16756 16757 // Sanity check 16758 if (instantApp && (forwardLocked || onExternal)) { 16759 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16760 + " external=" + onExternal); 16761 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16762 return; 16763 } 16764 16765 // Retrieve PackageSettings and parse package 16766 @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16767 | PackageParser.PARSE_ENFORCE_CODE 16768 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16769 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16770 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16771 PackageParser pp = new PackageParser(); 16772 pp.setSeparateProcesses(mSeparateProcesses); 16773 pp.setDisplayMetrics(mMetrics); 16774 pp.setCallback(mPackageParserCallback); 16775 16776 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16777 final PackageParser.Package pkg; 16778 try { 16779 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16780 DexMetadataHelper.validatePackageDexMetadata(pkg); 16781 } catch (PackageParserException e) { 16782 res.setError("Failed parse during installPackageLI", e); 16783 return; 16784 } finally { 16785 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16786 } 16787 16788 // Instant apps have several additional install-time checks. 16789 if (instantApp) { 16790 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 16791 Slog.w(TAG, 16792 "Instant app package " + pkg.packageName + " does not target at least O"); 16793 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16794 "Instant app package must target at least O"); 16795 return; 16796 } 16797 if (pkg.applicationInfo.targetSandboxVersion != 2) { 16798 Slog.w(TAG, "Instant app package " + pkg.packageName 16799 + " does not target targetSandboxVersion 2"); 16800 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16801 "Instant app package must use targetSandboxVersion 2"); 16802 return; 16803 } 16804 if (pkg.mSharedUserId != null) { 16805 Slog.w(TAG, "Instant app package " + pkg.packageName 16806 + " may not declare sharedUserId."); 16807 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16808 "Instant app package may not declare a sharedUserId"); 16809 return; 16810 } 16811 } 16812 16813 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16814 // Static shared libraries have synthetic package names 16815 renameStaticSharedLibraryPackage(pkg); 16816 16817 // No static shared libs on external storage 16818 if (onExternal) { 16819 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16820 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16821 "Packages declaring static-shared libs cannot be updated"); 16822 return; 16823 } 16824 } 16825 16826 // If we are installing a clustered package add results for the children 16827 if (pkg.childPackages != null) { 16828 synchronized (mPackages) { 16829 final int childCount = pkg.childPackages.size(); 16830 for (int i = 0; i < childCount; i++) { 16831 PackageParser.Package childPkg = pkg.childPackages.get(i); 16832 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16833 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16834 childRes.pkg = childPkg; 16835 childRes.name = childPkg.packageName; 16836 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16837 if (childPs != null) { 16838 childRes.origUsers = childPs.queryInstalledUsers( 16839 sUserManager.getUserIds(), true); 16840 } 16841 if ((mPackages.containsKey(childPkg.packageName))) { 16842 childRes.removedInfo = new PackageRemovedInfo(this); 16843 childRes.removedInfo.removedPackage = childPkg.packageName; 16844 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16845 } 16846 if (res.addedChildPackages == null) { 16847 res.addedChildPackages = new ArrayMap<>(); 16848 } 16849 res.addedChildPackages.put(childPkg.packageName, childRes); 16850 } 16851 } 16852 } 16853 16854 // If package doesn't declare API override, mark that we have an install 16855 // time CPU ABI override. 16856 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16857 pkg.cpuAbiOverride = args.abiOverride; 16858 } 16859 16860 String pkgName = res.name = pkg.packageName; 16861 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16862 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16863 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16864 return; 16865 } 16866 } 16867 16868 try { 16869 // either use what we've been given or parse directly from the APK 16870 if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) { 16871 pkg.setSigningDetails(args.signingDetails); 16872 } else { 16873 PackageParser.collectCertificates(pkg, false /* skipVerify */); 16874 } 16875 } catch (PackageParserException e) { 16876 res.setError("Failed collect during installPackageLI", e); 16877 return; 16878 } 16879 16880 if (instantApp && pkg.mSigningDetails.signatureSchemeVersion 16881 < SignatureSchemeVersion.SIGNING_BLOCK_V2) { 16882 Slog.w(TAG, "Instant app package " + pkg.packageName 16883 + " is not signed with at least APK Signature Scheme v2"); 16884 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16885 "Instant app package must be signed with APK Signature Scheme v2 or greater"); 16886 return; 16887 } 16888 16889 // Get rid of all references to package scan path via parser. 16890 pp = null; 16891 String oldCodePath = null; 16892 boolean systemApp = false; 16893 synchronized (mPackages) { 16894 // Check if installing already existing package 16895 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16896 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16897 if (pkg.mOriginalPackages != null 16898 && pkg.mOriginalPackages.contains(oldName) 16899 && mPackages.containsKey(oldName)) { 16900 // This package is derived from an original package, 16901 // and this device has been updating from that original 16902 // name. We must continue using the original name, so 16903 // rename the new package here. 16904 pkg.setPackageName(oldName); 16905 pkgName = pkg.packageName; 16906 replace = true; 16907 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16908 + oldName + " pkgName=" + pkgName); 16909 } else if (mPackages.containsKey(pkgName)) { 16910 // This package, under its official name, already exists 16911 // on the device; we should replace it. 16912 replace = true; 16913 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16914 } 16915 16916 // Child packages are installed through the parent package 16917 if (pkg.parentPackage != null) { 16918 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16919 "Package " + pkg.packageName + " is child of package " 16920 + pkg.parentPackage.parentPackage + ". Child packages " 16921 + "can be updated only through the parent package."); 16922 return; 16923 } 16924 16925 if (replace) { 16926 // Prevent apps opting out from runtime permissions 16927 PackageParser.Package oldPackage = mPackages.get(pkgName); 16928 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16929 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16930 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16931 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16932 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16933 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16934 + " doesn't support runtime permissions but the old" 16935 + " target SDK " + oldTargetSdk + " does."); 16936 return; 16937 } 16938 // Prevent persistent apps from being updated 16939 if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) { 16940 res.setError(PackageManager.INSTALL_FAILED_INVALID_APK, 16941 "Package " + oldPackage.packageName + " is a persistent app. " 16942 + "Persistent apps are not updateable."); 16943 return; 16944 } 16945 // Prevent apps from downgrading their targetSandbox. 16946 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16947 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16948 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16949 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16950 "Package " + pkg.packageName + " new target sandbox " 16951 + newTargetSandbox + " is incompatible with the previous value of" 16952 + oldTargetSandbox + "."); 16953 return; 16954 } 16955 16956 // Prevent installing of child packages 16957 if (oldPackage.parentPackage != null) { 16958 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16959 "Package " + pkg.packageName + " is child of package " 16960 + oldPackage.parentPackage + ". Child packages " 16961 + "can be updated only through the parent package."); 16962 return; 16963 } 16964 } 16965 } 16966 16967 PackageSetting ps = mSettings.mPackages.get(pkgName); 16968 if (ps != null) { 16969 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16970 16971 // Static shared libs have same package with different versions where 16972 // we internally use a synthetic package name to allow multiple versions 16973 // of the same package, therefore we need to compare signatures against 16974 // the package setting for the latest library version. 16975 PackageSetting signatureCheckPs = ps; 16976 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16977 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16978 if (libraryEntry != null) { 16979 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16980 } 16981 } 16982 16983 // Quick sanity check that we're signed correctly if updating; 16984 // we'll check this again later when scanning, but we want to 16985 // bail early here before tripping over redefined permissions. 16986 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16987 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 16988 if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 16989 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16990 + pkg.packageName + " upgrade keys do not match the " 16991 + "previously installed version"); 16992 return; 16993 } 16994 } else { 16995 try { 16996 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 16997 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 16998 // We don't care about disabledPkgSetting on install for now. 16999 final boolean compatMatch = verifySignatures( 17000 signatureCheckPs, null, pkg.mSigningDetails, compareCompat, 17001 compareRecover); 17002 // The new KeySets will be re-added later in the scanning process. 17003 if (compatMatch) { 17004 synchronized (mPackages) { 17005 ksms.removeAppKeySetDataLPw(pkg.packageName); 17006 } 17007 } 17008 } catch (PackageManagerException e) { 17009 res.setError(e.error, e.getMessage()); 17010 return; 17011 } 17012 } 17013 17014 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 17015 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 17016 systemApp = (ps.pkg.applicationInfo.flags & 17017 ApplicationInfo.FLAG_SYSTEM) != 0; 17018 } 17019 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17020 } 17021 17022 int N = pkg.permissions.size(); 17023 for (int i = N-1; i >= 0; i--) { 17024 final PackageParser.Permission perm = pkg.permissions.get(i); 17025 final BasePermission bp = 17026 (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name); 17027 17028 // Don't allow anyone but the system to define ephemeral permissions. 17029 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 17030 && !systemApp) { 17031 Slog.w(TAG, "Non-System package " + pkg.packageName 17032 + " attempting to delcare ephemeral permission " 17033 + perm.info.name + "; Removing ephemeral."); 17034 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 17035 } 17036 17037 // Check whether the newly-scanned package wants to define an already-defined perm 17038 if (bp != null) { 17039 // If the defining package is signed with our cert, it's okay. This 17040 // also includes the "updating the same package" case, of course. 17041 // "updating same package" could also involve key-rotation. 17042 final boolean sigsOk; 17043 final String sourcePackageName = bp.getSourcePackageName(); 17044 final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting(); 17045 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 17046 if (sourcePackageName.equals(pkg.packageName) 17047 && (ksms.shouldCheckUpgradeKeySetLocked( 17048 sourcePackageSetting, scanFlags))) { 17049 sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg); 17050 } else { 17051 sigsOk = compareSignatures( 17052 sourcePackageSetting.signatures.mSigningDetails.signatures, 17053 pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH; 17054 } 17055 if (!sigsOk) { 17056 // If the owning package is the system itself, we log but allow 17057 // install to proceed; we fail the install on all other permission 17058 // redefinitions. 17059 if (!sourcePackageName.equals("android")) { 17060 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 17061 + pkg.packageName + " attempting to redeclare permission " 17062 + perm.info.name + " already owned by " + sourcePackageName); 17063 res.origPermission = perm.info.name; 17064 res.origPackage = sourcePackageName; 17065 return; 17066 } else { 17067 Slog.w(TAG, "Package " + pkg.packageName 17068 + " attempting to redeclare system permission " 17069 + perm.info.name + "; ignoring new declaration"); 17070 pkg.permissions.remove(i); 17071 } 17072 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 17073 // Prevent apps to change protection level to dangerous from any other 17074 // type as this would allow a privilege escalation where an app adds a 17075 // normal/signature permission in other app's group and later redefines 17076 // it as dangerous leading to the group auto-grant. 17077 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 17078 == PermissionInfo.PROTECTION_DANGEROUS) { 17079 if (bp != null && !bp.isRuntime()) { 17080 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 17081 + "non-runtime permission " + perm.info.name 17082 + " to runtime; keeping old protection level"); 17083 perm.info.protectionLevel = bp.getProtectionLevel(); 17084 } 17085 } 17086 } 17087 } 17088 } 17089 } 17090 17091 if (systemApp) { 17092 if (onExternal) { 17093 // Abort update; system app can't be replaced with app on sdcard 17094 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17095 "Cannot install updates to system apps on sdcard"); 17096 return; 17097 } else if (instantApp) { 17098 // Abort update; system app can't be replaced with an instant app 17099 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 17100 "Cannot update a system app with an instant app"); 17101 return; 17102 } 17103 } 17104 17105 if (args.move != null) { 17106 // We did an in-place move, so dex is ready to roll 17107 scanFlags |= SCAN_NO_DEX; 17108 scanFlags |= SCAN_MOVE; 17109 17110 synchronized (mPackages) { 17111 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17112 if (ps == null) { 17113 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17114 "Missing settings for moved package " + pkgName); 17115 } 17116 17117 // We moved the entire application as-is, so bring over the 17118 // previously derived ABI information. 17119 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 17120 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 17121 } 17122 17123 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 17124 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 17125 scanFlags |= SCAN_NO_DEX; 17126 17127 try { 17128 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 17129 args.abiOverride : pkg.cpuAbiOverride); 17130 final boolean extractNativeLibs = !pkg.isLibrary(); 17131 derivePackageAbi(pkg, abiOverride, extractNativeLibs); 17132 } catch (PackageManagerException pme) { 17133 Slog.e(TAG, "Error deriving application ABI", pme); 17134 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 17135 return; 17136 } 17137 17138 // Shared libraries for the package need to be updated. 17139 synchronized (mPackages) { 17140 try { 17141 updateSharedLibrariesLPr(pkg, null); 17142 } catch (PackageManagerException e) { 17143 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17144 } 17145 } 17146 } 17147 17148 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 17149 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17150 return; 17151 } 17152 17153 if (PackageManagerServiceUtils.isApkVerityEnabled()) { 17154 String apkPath = null; 17155 synchronized (mPackages) { 17156 // Note that if the attacker managed to skip verify setup, for example by tampering 17157 // with the package settings, upon reboot we will do full apk verification when 17158 // verity is not detected. 17159 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17160 if (ps != null && ps.isPrivileged()) { 17161 apkPath = pkg.baseCodePath; 17162 } 17163 } 17164 17165 if (apkPath != null) { 17166 final VerityUtils.SetupResult result = 17167 VerityUtils.generateApkVeritySetupData(apkPath); 17168 if (result.isOk()) { 17169 if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath); 17170 FileDescriptor fd = result.getUnownedFileDescriptor(); 17171 try { 17172 mInstaller.installApkVerity(apkPath, fd); 17173 } catch (InstallerException e) { 17174 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17175 "Failed to set up verity: " + e); 17176 return; 17177 } finally { 17178 IoUtils.closeQuietly(fd); 17179 } 17180 } else if (result.isFailed()) { 17181 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity"); 17182 return; 17183 } else { 17184 // Do nothing if verity is skipped. Will fall back to full apk verification on 17185 // reboot. 17186 } 17187 } 17188 } 17189 17190 if (!instantApp) { 17191 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17192 } else { 17193 if (DEBUG_DOMAIN_VERIFICATION) { 17194 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName); 17195 } 17196 } 17197 17198 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17199 "installPackageLI")) { 17200 if (replace) { 17201 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17202 // Static libs have a synthetic package name containing the version 17203 // and cannot be updated as an update would get a new package name, 17204 // unless this is the exact same version code which is useful for 17205 // development. 17206 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17207 if (existingPkg != null && 17208 existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) { 17209 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17210 + "static-shared libs cannot be updated"); 17211 return; 17212 } 17213 } 17214 replacePackageLIF(pkg, parseFlags, scanFlags, args.user, 17215 installerPackageName, res, args.installReason); 17216 } else { 17217 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17218 args.user, installerPackageName, volumeUuid, res, args.installReason); 17219 } 17220 } 17221 17222 // Prepare the application profiles for the new code paths. 17223 // This needs to be done before invoking dexopt so that any install-time profile 17224 // can be used for optimizations. 17225 mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier())); 17226 17227 // Check whether we need to dexopt the app. 17228 // 17229 // NOTE: it is IMPORTANT to call dexopt: 17230 // - after doRename which will sync the package data from PackageParser.Package and its 17231 // corresponding ApplicationInfo. 17232 // - after installNewPackageLIF or replacePackageLIF which will update result with the 17233 // uid of the application (pkg.applicationInfo.uid). 17234 // This update happens in place! 17235 // 17236 // We only need to dexopt if the package meets ALL of the following conditions: 17237 // 1) it is not forward locked. 17238 // 2) it is not on on an external ASEC container. 17239 // 3) it is not an instant app or if it is then dexopt is enabled via gservices. 17240 // 17241 // Note that we do not dexopt instant apps by default. dexopt can take some time to 17242 // complete, so we skip this step during installation. Instead, we'll take extra time 17243 // the first time the instant app starts. It's preferred to do it this way to provide 17244 // continuous progress to the useur instead of mysteriously blocking somewhere in the 17245 // middle of running an instant app. The default behaviour can be overridden 17246 // via gservices. 17247 final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED) 17248 && !forwardLocked 17249 && !pkg.applicationInfo.isExternalAsec() 17250 && (!instantApp || Global.getInt(mContext.getContentResolver(), 17251 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0); 17252 17253 if (performDexopt) { 17254 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17255 // Do not run PackageDexOptimizer through the local performDexOpt 17256 // method because `pkg` may not be in `mPackages` yet. 17257 // 17258 // Also, don't fail application installs if the dexopt step fails. 17259 DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName, 17260 REASON_INSTALL, 17261 DexoptOptions.DEXOPT_BOOT_COMPLETE); 17262 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17263 null /* instructionSets */, 17264 getOrCreateCompilerPackageStats(pkg), 17265 mDexManager.getPackageUseInfoOrDefault(pkg.packageName), 17266 dexoptOptions); 17267 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17268 } 17269 17270 // Notify BackgroundDexOptService that the package has been changed. 17271 // If this is an update of a package which used to fail to compile, 17272 // BackgroundDexOptService will remove it from its blacklist. 17273 // TODO: Layering violation 17274 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17275 17276 synchronized (mPackages) { 17277 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17278 if (ps != null) { 17279 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17280 ps.setUpdateAvailable(false /*updateAvailable*/); 17281 } 17282 17283 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17284 for (int i = 0; i < childCount; i++) { 17285 PackageParser.Package childPkg = pkg.childPackages.get(i); 17286 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17287 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17288 if (childPs != null) { 17289 childRes.newUsers = childPs.queryInstalledUsers( 17290 sUserManager.getUserIds(), true); 17291 } 17292 } 17293 17294 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17295 updateSequenceNumberLP(ps, res.newUsers); 17296 updateInstantAppInstallerLocked(pkgName); 17297 } 17298 } 17299 } 17300 17301 private void startIntentFilterVerifications(int userId, boolean replacing, 17302 PackageParser.Package pkg) { 17303 if (mIntentFilterVerifierComponent == null) { 17304 Slog.w(TAG, "No IntentFilter verification will not be done as " 17305 + "there is no IntentFilterVerifier available!"); 17306 return; 17307 } 17308 17309 final int verifierUid = getPackageUid( 17310 mIntentFilterVerifierComponent.getPackageName(), 17311 MATCH_DEBUG_TRIAGED_MISSING, 17312 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17313 17314 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17315 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17316 mHandler.sendMessage(msg); 17317 17318 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17319 for (int i = 0; i < childCount; i++) { 17320 PackageParser.Package childPkg = pkg.childPackages.get(i); 17321 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17322 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17323 mHandler.sendMessage(msg); 17324 } 17325 } 17326 17327 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17328 PackageParser.Package pkg) { 17329 int size = pkg.activities.size(); 17330 if (size == 0) { 17331 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17332 "No activity, so no need to verify any IntentFilter!"); 17333 return; 17334 } 17335 17336 final boolean hasDomainURLs = hasDomainURLs(pkg); 17337 if (!hasDomainURLs) { 17338 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17339 "No domain URLs, so no need to verify any IntentFilter!"); 17340 return; 17341 } 17342 17343 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17344 + " if any IntentFilter from the " + size 17345 + " Activities needs verification ..."); 17346 17347 int count = 0; 17348 final String packageName = pkg.packageName; 17349 17350 synchronized (mPackages) { 17351 // If this is a new install and we see that we've already run verification for this 17352 // package, we have nothing to do: it means the state was restored from backup. 17353 if (!replacing) { 17354 IntentFilterVerificationInfo ivi = 17355 mSettings.getIntentFilterVerificationLPr(packageName); 17356 if (ivi != null) { 17357 if (DEBUG_DOMAIN_VERIFICATION) { 17358 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17359 + ivi.getStatusString()); 17360 } 17361 return; 17362 } 17363 } 17364 17365 // If any filters need to be verified, then all need to be. 17366 boolean needToVerify = false; 17367 for (PackageParser.Activity a : pkg.activities) { 17368 for (ActivityIntentInfo filter : a.intents) { 17369 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17370 if (DEBUG_DOMAIN_VERIFICATION) { 17371 Slog.d(TAG, 17372 "Intent filter needs verification, so processing all filters"); 17373 } 17374 needToVerify = true; 17375 break; 17376 } 17377 } 17378 } 17379 17380 if (needToVerify) { 17381 final int verificationId = mIntentFilterVerificationToken++; 17382 for (PackageParser.Activity a : pkg.activities) { 17383 for (ActivityIntentInfo filter : a.intents) { 17384 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17385 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17386 "Verification needed for IntentFilter:" + filter.toString()); 17387 mIntentFilterVerifier.addOneIntentFilterVerification( 17388 verifierUid, userId, verificationId, filter, packageName); 17389 count++; 17390 } 17391 } 17392 } 17393 } 17394 } 17395 17396 if (count > 0) { 17397 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17398 + " IntentFilter verification" + (count > 1 ? "s" : "") 17399 + " for userId:" + userId); 17400 mIntentFilterVerifier.startVerifications(userId); 17401 } else { 17402 if (DEBUG_DOMAIN_VERIFICATION) { 17403 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17404 } 17405 } 17406 } 17407 17408 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17409 final ComponentName cn = filter.activity.getComponentName(); 17410 final String packageName = cn.getPackageName(); 17411 17412 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17413 packageName); 17414 if (ivi == null) { 17415 return true; 17416 } 17417 int status = ivi.getStatus(); 17418 switch (status) { 17419 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17420 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17421 return true; 17422 17423 default: 17424 // Nothing to do 17425 return false; 17426 } 17427 } 17428 17429 private static boolean isMultiArch(ApplicationInfo info) { 17430 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17431 } 17432 17433 private static boolean isExternal(PackageParser.Package pkg) { 17434 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17435 } 17436 17437 private static boolean isExternal(PackageSetting ps) { 17438 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17439 } 17440 17441 private static boolean isSystemApp(PackageParser.Package pkg) { 17442 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17443 } 17444 17445 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17446 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17447 } 17448 17449 private static boolean isOemApp(PackageParser.Package pkg) { 17450 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 17451 } 17452 17453 private static boolean isVendorApp(PackageParser.Package pkg) { 17454 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 17455 } 17456 17457 private static boolean isProductApp(PackageParser.Package pkg) { 17458 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 17459 } 17460 17461 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17462 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17463 } 17464 17465 private static boolean isSystemApp(PackageSetting ps) { 17466 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17467 } 17468 17469 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17470 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17471 } 17472 17473 private int packageFlagsToInstallFlags(PackageSetting ps) { 17474 int installFlags = 0; 17475 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17476 // This existing package was an external ASEC install when we have 17477 // the external flag without a UUID 17478 installFlags |= PackageManager.INSTALL_EXTERNAL; 17479 } 17480 if (ps.isForwardLocked()) { 17481 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17482 } 17483 return installFlags; 17484 } 17485 17486 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17487 if (isExternal(pkg)) { 17488 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17489 return mSettings.getExternalVersion(); 17490 } else { 17491 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17492 } 17493 } else { 17494 return mSettings.getInternalVersion(); 17495 } 17496 } 17497 17498 private void deleteTempPackageFiles() { 17499 final FilenameFilter filter = new FilenameFilter() { 17500 public boolean accept(File dir, String name) { 17501 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17502 } 17503 }; 17504 for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) { 17505 file.delete(); 17506 } 17507 } 17508 17509 @Override 17510 public void deletePackageAsUser(String packageName, int versionCode, 17511 IPackageDeleteObserver observer, int userId, int flags) { 17512 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17513 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17514 } 17515 17516 @Override 17517 public void deletePackageVersioned(VersionedPackage versionedPackage, 17518 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17519 final int callingUid = Binder.getCallingUid(); 17520 mContext.enforceCallingOrSelfPermission( 17521 android.Manifest.permission.DELETE_PACKAGES, null); 17522 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 17523 Preconditions.checkNotNull(versionedPackage); 17524 Preconditions.checkNotNull(observer); 17525 Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(), 17526 PackageManager.VERSION_CODE_HIGHEST, 17527 Long.MAX_VALUE, "versionCode must be >= -1"); 17528 17529 final String packageName = versionedPackage.getPackageName(); 17530 final long versionCode = versionedPackage.getLongVersionCode(); 17531 final String internalPackageName; 17532 synchronized (mPackages) { 17533 // Normalize package name to handle renamed packages and static libs 17534 internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode); 17535 } 17536 17537 final int uid = Binder.getCallingUid(); 17538 if (!isOrphaned(internalPackageName) 17539 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17540 try { 17541 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17542 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17543 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17544 observer.onUserActionRequired(intent); 17545 } catch (RemoteException re) { 17546 } 17547 return; 17548 } 17549 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17550 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17551 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17552 mContext.enforceCallingOrSelfPermission( 17553 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17554 "deletePackage for user " + userId); 17555 } 17556 17557 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17558 try { 17559 observer.onPackageDeleted(packageName, 17560 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17561 } catch (RemoteException re) { 17562 } 17563 return; 17564 } 17565 17566 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17567 try { 17568 observer.onPackageDeleted(packageName, 17569 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17570 } catch (RemoteException re) { 17571 } 17572 return; 17573 } 17574 17575 if (DEBUG_REMOVE) { 17576 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17577 + " deleteAllUsers: " + deleteAllUsers + " version=" 17578 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17579 ? "VERSION_CODE_HIGHEST" : versionCode)); 17580 } 17581 // Queue up an async operation since the package deletion may take a little while. 17582 mHandler.post(new Runnable() { 17583 public void run() { 17584 mHandler.removeCallbacks(this); 17585 int returnCode; 17586 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 17587 boolean doDeletePackage = true; 17588 if (ps != null) { 17589 final boolean targetIsInstantApp = 17590 ps.getInstantApp(UserHandle.getUserId(callingUid)); 17591 doDeletePackage = !targetIsInstantApp 17592 || canViewInstantApps; 17593 } 17594 if (doDeletePackage) { 17595 if (!deleteAllUsers) { 17596 returnCode = deletePackageX(internalPackageName, versionCode, 17597 userId, deleteFlags); 17598 } else { 17599 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17600 internalPackageName, users); 17601 // If nobody is blocking uninstall, proceed with delete for all users 17602 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17603 returnCode = deletePackageX(internalPackageName, versionCode, 17604 userId, deleteFlags); 17605 } else { 17606 // Otherwise uninstall individually for users with blockUninstalls=false 17607 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17608 for (int userId : users) { 17609 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17610 returnCode = deletePackageX(internalPackageName, versionCode, 17611 userId, userFlags); 17612 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17613 Slog.w(TAG, "Package delete failed for user " + userId 17614 + ", returnCode " + returnCode); 17615 } 17616 } 17617 } 17618 // The app has only been marked uninstalled for certain users. 17619 // We still need to report that delete was blocked 17620 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17621 } 17622 } 17623 } else { 17624 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17625 } 17626 try { 17627 observer.onPackageDeleted(packageName, returnCode, null); 17628 } catch (RemoteException e) { 17629 Log.i(TAG, "Observer no longer exists."); 17630 } //end catch 17631 } //end run 17632 }); 17633 } 17634 17635 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17636 if (pkg.staticSharedLibName != null) { 17637 return pkg.manifestPackageName; 17638 } 17639 return pkg.packageName; 17640 } 17641 17642 private String resolveInternalPackageNameLPr(String packageName, long versionCode) { 17643 // Handle renamed packages 17644 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17645 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17646 17647 // Is this a static library? 17648 LongSparseArray<SharedLibraryEntry> versionedLib = 17649 mStaticLibsByDeclaringPackage.get(packageName); 17650 if (versionedLib == null || versionedLib.size() <= 0) { 17651 return packageName; 17652 } 17653 17654 // Figure out which lib versions the caller can see 17655 LongSparseLongArray versionsCallerCanSee = null; 17656 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17657 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17658 && callingAppId != Process.ROOT_UID) { 17659 versionsCallerCanSee = new LongSparseLongArray(); 17660 String libName = versionedLib.valueAt(0).info.getName(); 17661 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17662 if (uidPackages != null) { 17663 for (String uidPackage : uidPackages) { 17664 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17665 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17666 if (libIdx >= 0) { 17667 final long libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17668 versionsCallerCanSee.append(libVersion, libVersion); 17669 } 17670 } 17671 } 17672 } 17673 17674 // Caller can see nothing - done 17675 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17676 return packageName; 17677 } 17678 17679 // Find the version the caller can see and the app version code 17680 SharedLibraryEntry highestVersion = null; 17681 final int versionCount = versionedLib.size(); 17682 for (int i = 0; i < versionCount; i++) { 17683 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17684 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17685 libEntry.info.getLongVersion()) < 0) { 17686 continue; 17687 } 17688 final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode(); 17689 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17690 if (libVersionCode == versionCode) { 17691 return libEntry.apk; 17692 } 17693 } else if (highestVersion == null) { 17694 highestVersion = libEntry; 17695 } else if (libVersionCode > highestVersion.info 17696 .getDeclaringPackage().getLongVersionCode()) { 17697 highestVersion = libEntry; 17698 } 17699 } 17700 17701 if (highestVersion != null) { 17702 return highestVersion.apk; 17703 } 17704 17705 return packageName; 17706 } 17707 17708 boolean isCallerVerifier(int callingUid) { 17709 final int callingUserId = UserHandle.getUserId(callingUid); 17710 return mRequiredVerifierPackage != null && 17711 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 17712 } 17713 17714 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17715 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17716 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17717 return true; 17718 } 17719 final int callingUserId = UserHandle.getUserId(callingUid); 17720 // If the caller installed the pkgName, then allow it to silently uninstall. 17721 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17722 return true; 17723 } 17724 17725 // Allow package verifier to silently uninstall. 17726 if (mRequiredVerifierPackage != null && 17727 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17728 return true; 17729 } 17730 17731 // Allow package uninstaller to silently uninstall. 17732 if (mRequiredUninstallerPackage != null && 17733 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17734 return true; 17735 } 17736 17737 // Allow storage manager to silently uninstall. 17738 if (mStorageManagerPackage != null && 17739 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17740 return true; 17741 } 17742 17743 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 17744 // uninstall for device owner provisioning. 17745 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 17746 == PERMISSION_GRANTED) { 17747 return true; 17748 } 17749 17750 return false; 17751 } 17752 17753 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17754 int[] result = EMPTY_INT_ARRAY; 17755 for (int userId : userIds) { 17756 if (getBlockUninstallForUser(packageName, userId)) { 17757 result = ArrayUtils.appendInt(result, userId); 17758 } 17759 } 17760 return result; 17761 } 17762 17763 @Override 17764 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17765 final int callingUid = Binder.getCallingUid(); 17766 if (getInstantAppPackageName(callingUid) != null 17767 && !isCallerSameApp(packageName, callingUid)) { 17768 return false; 17769 } 17770 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17771 } 17772 17773 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17774 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17775 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17776 try { 17777 if (dpm != null) { 17778 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17779 /* callingUserOnly =*/ false); 17780 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17781 : deviceOwnerComponentName.getPackageName(); 17782 // Does the package contains the device owner? 17783 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17784 // this check is probably not needed, since DO should be registered as a device 17785 // admin on some user too. (Original bug for this: b/17657954) 17786 if (packageName.equals(deviceOwnerPackageName)) { 17787 return true; 17788 } 17789 // Does it contain a device admin for any user? 17790 int[] users; 17791 if (userId == UserHandle.USER_ALL) { 17792 users = sUserManager.getUserIds(); 17793 } else { 17794 users = new int[]{userId}; 17795 } 17796 for (int i = 0; i < users.length; ++i) { 17797 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17798 return true; 17799 } 17800 } 17801 } 17802 } catch (RemoteException e) { 17803 } 17804 return false; 17805 } 17806 17807 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17808 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17809 } 17810 17811 /** 17812 * This method is an internal method that could be get invoked either 17813 * to delete an installed package or to clean up a failed installation. 17814 * After deleting an installed package, a broadcast is sent to notify any 17815 * listeners that the package has been removed. For cleaning up a failed 17816 * installation, the broadcast is not necessary since the package's 17817 * installation wouldn't have sent the initial broadcast either 17818 * The key steps in deleting a package are 17819 * deleting the package information in internal structures like mPackages, 17820 * deleting the packages base directories through installd 17821 * updating mSettings to reflect current status 17822 * persisting settings for later use 17823 * sending a broadcast if necessary 17824 */ 17825 int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) { 17826 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17827 final boolean res; 17828 17829 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17830 ? UserHandle.USER_ALL : userId; 17831 17832 if (isPackageDeviceAdmin(packageName, removeUser)) { 17833 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17834 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17835 } 17836 17837 PackageSetting uninstalledPs = null; 17838 PackageParser.Package pkg = null; 17839 17840 // for the uninstall-updates case and restricted profiles, remember the per- 17841 // user handle installed state 17842 int[] allUsers; 17843 synchronized (mPackages) { 17844 uninstalledPs = mSettings.mPackages.get(packageName); 17845 if (uninstalledPs == null) { 17846 Slog.w(TAG, "Not removing non-existent package " + packageName); 17847 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17848 } 17849 17850 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17851 && uninstalledPs.versionCode != versionCode) { 17852 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17853 + uninstalledPs.versionCode + " != " + versionCode); 17854 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17855 } 17856 17857 // Static shared libs can be declared by any package, so let us not 17858 // allow removing a package if it provides a lib others depend on. 17859 pkg = mPackages.get(packageName); 17860 17861 allUsers = sUserManager.getUserIds(); 17862 17863 if (pkg != null && pkg.staticSharedLibName != null) { 17864 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17865 pkg.staticSharedLibVersion); 17866 if (libEntry != null) { 17867 for (int currUserId : allUsers) { 17868 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 17869 continue; 17870 } 17871 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17872 libEntry.info, 0, currUserId); 17873 if (!ArrayUtils.isEmpty(libClientPackages)) { 17874 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17875 + " hosting lib " + libEntry.info.getName() + " version " 17876 + libEntry.info.getLongVersion() + " used by " + libClientPackages 17877 + " for user " + currUserId); 17878 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17879 } 17880 } 17881 } 17882 } 17883 17884 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17885 } 17886 17887 final int freezeUser; 17888 if (isUpdatedSystemApp(uninstalledPs) 17889 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17890 // We're downgrading a system app, which will apply to all users, so 17891 // freeze them all during the downgrade 17892 freezeUser = UserHandle.USER_ALL; 17893 } else { 17894 freezeUser = removeUser; 17895 } 17896 17897 synchronized (mInstallLock) { 17898 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17899 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17900 deleteFlags, "deletePackageX")) { 17901 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17902 deleteFlags | PackageManager.DELETE_CHATTY, info, true, null); 17903 } 17904 synchronized (mPackages) { 17905 if (res) { 17906 if (pkg != null) { 17907 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17908 } 17909 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 17910 updateInstantAppInstallerLocked(packageName); 17911 } 17912 } 17913 } 17914 17915 if (res) { 17916 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17917 info.sendPackageRemovedBroadcasts(killApp); 17918 info.sendSystemPackageUpdatedBroadcasts(); 17919 info.sendSystemPackageAppearedBroadcasts(); 17920 } 17921 // Force a gc here. 17922 Runtime.getRuntime().gc(); 17923 // Delete the resources here after sending the broadcast to let 17924 // other processes clean up before deleting resources. 17925 if (info.args != null) { 17926 synchronized (mInstallLock) { 17927 info.args.doPostDeleteLI(true); 17928 } 17929 } 17930 17931 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17932 } 17933 17934 static class PackageRemovedInfo { 17935 final PackageSender packageSender; 17936 String removedPackage; 17937 String installerPackageName; 17938 int uid = -1; 17939 int removedAppId = -1; 17940 int[] origUsers; 17941 int[] removedUsers = null; 17942 int[] broadcastUsers = null; 17943 int[] instantUserIds = null; 17944 SparseArray<Integer> installReasons; 17945 boolean isRemovedPackageSystemUpdate = false; 17946 boolean isUpdate; 17947 boolean dataRemoved; 17948 boolean removedForAllUsers; 17949 boolean isStaticSharedLib; 17950 // Clean up resources deleted packages. 17951 InstallArgs args = null; 17952 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17953 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17954 17955 PackageRemovedInfo(PackageSender packageSender) { 17956 this.packageSender = packageSender; 17957 } 17958 17959 void sendPackageRemovedBroadcasts(boolean killApp) { 17960 sendPackageRemovedBroadcastInternal(killApp); 17961 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17962 for (int i = 0; i < childCount; i++) { 17963 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17964 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17965 } 17966 } 17967 17968 void sendSystemPackageUpdatedBroadcasts() { 17969 if (isRemovedPackageSystemUpdate) { 17970 sendSystemPackageUpdatedBroadcastsInternal(); 17971 final int childCount = (removedChildPackages != null) 17972 ? removedChildPackages.size() : 0; 17973 for (int i = 0; i < childCount; i++) { 17974 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17975 if (childInfo.isRemovedPackageSystemUpdate) { 17976 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17977 } 17978 } 17979 } 17980 } 17981 17982 void sendSystemPackageAppearedBroadcasts() { 17983 final int packageCount = (appearedChildPackages != null) 17984 ? appearedChildPackages.size() : 0; 17985 for (int i = 0; i < packageCount; i++) { 17986 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17987 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 17988 true /*sendBootCompleted*/, false /*startReceiver*/, 17989 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null); 17990 } 17991 } 17992 17993 private void sendSystemPackageUpdatedBroadcastsInternal() { 17994 Bundle extras = new Bundle(2); 17995 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17996 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17997 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17998 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 17999 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18000 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 18001 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 18002 null, null, 0, removedPackage, null, null, null); 18003 if (installerPackageName != null) { 18004 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18005 removedPackage, extras, 0 /*flags*/, 18006 installerPackageName, null, null, null); 18007 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18008 removedPackage, extras, 0 /*flags*/, 18009 installerPackageName, null, null, null); 18010 } 18011 } 18012 18013 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 18014 // Don't send static shared library removal broadcasts as these 18015 // libs are visible only the the apps that depend on them an one 18016 // cannot remove the library if it has a dependency. 18017 if (isStaticSharedLib) { 18018 return; 18019 } 18020 Bundle extras = new Bundle(2); 18021 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18022 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 18023 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 18024 if (isUpdate || isRemovedPackageSystemUpdate) { 18025 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18026 } 18027 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 18028 if (removedPackage != null) { 18029 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18030 removedPackage, extras, 0, null /*targetPackage*/, null, 18031 broadcastUsers, instantUserIds); 18032 if (installerPackageName != null) { 18033 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18034 removedPackage, extras, 0 /*flags*/, 18035 installerPackageName, null, broadcastUsers, instantUserIds); 18036 } 18037 if (dataRemoved && !isRemovedPackageSystemUpdate) { 18038 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 18039 removedPackage, extras, 18040 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18041 null, null, broadcastUsers, instantUserIds); 18042 packageSender.notifyPackageRemoved(removedPackage); 18043 } 18044 } 18045 if (removedAppId >= 0) { 18046 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 18047 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18048 null, null, broadcastUsers, instantUserIds); 18049 } 18050 } 18051 18052 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 18053 removedUsers = userIds; 18054 if (removedUsers == null) { 18055 broadcastUsers = null; 18056 return; 18057 } 18058 18059 broadcastUsers = EMPTY_INT_ARRAY; 18060 instantUserIds = EMPTY_INT_ARRAY; 18061 for (int i = userIds.length - 1; i >= 0; --i) { 18062 final int userId = userIds[i]; 18063 if (deletedPackageSetting.getInstantApp(userId)) { 18064 instantUserIds = ArrayUtils.appendInt(instantUserIds, userId); 18065 } else { 18066 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 18067 } 18068 } 18069 } 18070 } 18071 18072 /* 18073 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 18074 * flag is not set, the data directory is removed as well. 18075 * make sure this flag is set for partially installed apps. If not its meaningless to 18076 * delete a partially installed application. 18077 */ 18078 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 18079 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 18080 String packageName = ps.name; 18081 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 18082 // Retrieve object to delete permissions for shared user later on 18083 final PackageParser.Package deletedPkg; 18084 final PackageSetting deletedPs; 18085 // reader 18086 synchronized (mPackages) { 18087 deletedPkg = mPackages.get(packageName); 18088 deletedPs = mSettings.mPackages.get(packageName); 18089 if (outInfo != null) { 18090 outInfo.removedPackage = packageName; 18091 outInfo.installerPackageName = ps.installerPackageName; 18092 outInfo.isStaticSharedLib = deletedPkg != null 18093 && deletedPkg.staticSharedLibName != null; 18094 outInfo.populateUsers(deletedPs == null ? null 18095 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 18096 } 18097 } 18098 18099 removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0); 18100 18101 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 18102 final PackageParser.Package resolvedPkg; 18103 if (deletedPkg != null) { 18104 resolvedPkg = deletedPkg; 18105 } else { 18106 // We don't have a parsed package when it lives on an ejected 18107 // adopted storage device, so fake something together 18108 resolvedPkg = new PackageParser.Package(ps.name); 18109 resolvedPkg.setVolumeUuid(ps.volumeUuid); 18110 } 18111 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 18112 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18113 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 18114 if (outInfo != null) { 18115 outInfo.dataRemoved = true; 18116 } 18117 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 18118 } 18119 18120 int removedAppId = -1; 18121 18122 // writer 18123 synchronized (mPackages) { 18124 boolean installedStateChanged = false; 18125 if (deletedPs != null) { 18126 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 18127 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 18128 clearDefaultBrowserIfNeeded(packageName); 18129 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 18130 removedAppId = mSettings.removePackageLPw(packageName); 18131 if (outInfo != null) { 18132 outInfo.removedAppId = removedAppId; 18133 } 18134 mPermissionManager.updatePermissions( 18135 deletedPs.name, null, false, mPackages.values(), mPermissionCallback); 18136 if (deletedPs.sharedUser != null) { 18137 // Remove permissions associated with package. Since runtime 18138 // permissions are per user we have to kill the removed package 18139 // or packages running under the shared user of the removed 18140 // package if revoking the permissions requested only by the removed 18141 // package is successful and this causes a change in gids. 18142 for (int userId : UserManagerService.getInstance().getUserIds()) { 18143 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 18144 userId); 18145 if (userIdToKill == UserHandle.USER_ALL 18146 || userIdToKill >= UserHandle.USER_SYSTEM) { 18147 // If gids changed for this user, kill all affected packages. 18148 mHandler.post(new Runnable() { 18149 @Override 18150 public void run() { 18151 // This has to happen with no lock held. 18152 killApplication(deletedPs.name, deletedPs.appId, 18153 KILL_APP_REASON_GIDS_CHANGED); 18154 } 18155 }); 18156 break; 18157 } 18158 } 18159 } 18160 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 18161 } 18162 // make sure to preserve per-user disabled state if this removal was just 18163 // a downgrade of a system app to the factory package 18164 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 18165 if (DEBUG_REMOVE) { 18166 Slog.d(TAG, "Propagating install state across downgrade"); 18167 } 18168 for (int userId : allUserHandles) { 18169 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18170 if (DEBUG_REMOVE) { 18171 Slog.d(TAG, " user " + userId + " => " + installed); 18172 } 18173 if (installed != ps.getInstalled(userId)) { 18174 installedStateChanged = true; 18175 } 18176 ps.setInstalled(installed, userId); 18177 } 18178 } 18179 } 18180 // can downgrade to reader 18181 if (writeSettings) { 18182 // Save settings now 18183 mSettings.writeLPr(); 18184 } 18185 if (installedStateChanged) { 18186 mSettings.writeKernelMappingLPr(ps); 18187 } 18188 } 18189 if (removedAppId != -1) { 18190 // A user ID was deleted here. Go through all users and remove it 18191 // from KeyStore. 18192 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 18193 } 18194 } 18195 18196 static boolean locationIsPrivileged(String path) { 18197 try { 18198 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 18199 final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 18200 final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 18201 return path.startsWith(privilegedAppDir.getCanonicalPath()) 18202 || path.startsWith(privilegedVendorAppDir.getCanonicalPath()) 18203 || path.startsWith(privilegedProductAppDir.getCanonicalPath()); 18204 } catch (IOException e) { 18205 Slog.e(TAG, "Unable to access code path " + path); 18206 } 18207 return false; 18208 } 18209 18210 static boolean locationIsOem(String path) { 18211 try { 18212 return path.startsWith(Environment.getOemDirectory().getCanonicalPath()); 18213 } catch (IOException e) { 18214 Slog.e(TAG, "Unable to access code path " + path); 18215 } 18216 return false; 18217 } 18218 18219 static boolean locationIsVendor(String path) { 18220 try { 18221 return path.startsWith(Environment.getVendorDirectory().getCanonicalPath()); 18222 } catch (IOException e) { 18223 Slog.e(TAG, "Unable to access code path " + path); 18224 } 18225 return false; 18226 } 18227 18228 static boolean locationIsProduct(String path) { 18229 try { 18230 return path.startsWith(Environment.getProductDirectory().getCanonicalPath()); 18231 } catch (IOException e) { 18232 Slog.e(TAG, "Unable to access code path " + path); 18233 } 18234 return false; 18235 } 18236 18237 /* 18238 * Tries to delete system package. 18239 */ 18240 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 18241 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 18242 boolean writeSettings) { 18243 if (deletedPs.parentPackageName != null) { 18244 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 18245 return false; 18246 } 18247 18248 final boolean applyUserRestrictions 18249 = (allUserHandles != null) && (outInfo.origUsers != null); 18250 final PackageSetting disabledPs; 18251 // Confirm if the system package has been updated 18252 // An updated system app can be deleted. This will also have to restore 18253 // the system pkg from system partition 18254 // reader 18255 synchronized (mPackages) { 18256 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 18257 } 18258 18259 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 18260 + " disabledPs=" + disabledPs); 18261 18262 if (disabledPs == null) { 18263 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 18264 return false; 18265 } else if (DEBUG_REMOVE) { 18266 Slog.d(TAG, "Deleting system pkg from data partition"); 18267 } 18268 18269 if (DEBUG_REMOVE) { 18270 if (applyUserRestrictions) { 18271 Slog.d(TAG, "Remembering install states:"); 18272 for (int userId : allUserHandles) { 18273 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 18274 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 18275 } 18276 } 18277 } 18278 18279 // Delete the updated package 18280 outInfo.isRemovedPackageSystemUpdate = true; 18281 if (outInfo.removedChildPackages != null) { 18282 final int childCount = (deletedPs.childPackageNames != null) 18283 ? deletedPs.childPackageNames.size() : 0; 18284 for (int i = 0; i < childCount; i++) { 18285 String childPackageName = deletedPs.childPackageNames.get(i); 18286 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 18287 .contains(childPackageName)) { 18288 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18289 childPackageName); 18290 if (childInfo != null) { 18291 childInfo.isRemovedPackageSystemUpdate = true; 18292 } 18293 } 18294 } 18295 } 18296 18297 if (disabledPs.versionCode < deletedPs.versionCode) { 18298 // Delete data for downgrades 18299 flags &= ~PackageManager.DELETE_KEEP_DATA; 18300 } else { 18301 // Preserve data by setting flag 18302 flags |= PackageManager.DELETE_KEEP_DATA; 18303 } 18304 18305 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 18306 outInfo, writeSettings, disabledPs.pkg); 18307 if (!ret) { 18308 return false; 18309 } 18310 18311 // writer 18312 synchronized (mPackages) { 18313 // NOTE: The system package always needs to be enabled; even if it's for 18314 // a compressed stub. If we don't, installing the system package fails 18315 // during scan [scanning checks the disabled packages]. We will reverse 18316 // this later, after we've "installed" the stub. 18317 // Reinstate the old system package 18318 enableSystemPackageLPw(disabledPs.pkg); 18319 // Remove any native libraries from the upgraded package. 18320 removeNativeBinariesLI(deletedPs); 18321 } 18322 18323 // Install the system package 18324 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18325 try { 18326 installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles, 18327 outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings); 18328 } catch (PackageManagerException e) { 18329 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18330 + e.getMessage()); 18331 return false; 18332 } finally { 18333 if (disabledPs.pkg.isStub) { 18334 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/); 18335 } 18336 } 18337 return true; 18338 } 18339 18340 /** 18341 * Installs a package that's already on the system partition. 18342 */ 18343 private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString, 18344 boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 18345 @Nullable PermissionsState origPermissionState, boolean writeSettings) 18346 throws PackageManagerException { 18347 @ParseFlags int parseFlags = 18348 mDefParseFlags 18349 | PackageParser.PARSE_MUST_BE_APK 18350 | PackageParser.PARSE_IS_SYSTEM_DIR; 18351 @ScanFlags int scanFlags = SCAN_AS_SYSTEM; 18352 if (isPrivileged || locationIsPrivileged(codePathString)) { 18353 scanFlags |= SCAN_AS_PRIVILEGED; 18354 } 18355 if (locationIsOem(codePathString)) { 18356 scanFlags |= SCAN_AS_OEM; 18357 } 18358 if (locationIsVendor(codePathString)) { 18359 scanFlags |= SCAN_AS_VENDOR; 18360 } 18361 if (locationIsProduct(codePathString)) { 18362 scanFlags |= SCAN_AS_PRODUCT; 18363 } 18364 18365 final File codePath = new File(codePathString); 18366 final PackageParser.Package pkg = 18367 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null); 18368 18369 try { 18370 // update shared libraries for the newly re-installed system package 18371 updateSharedLibrariesLPr(pkg, null); 18372 } catch (PackageManagerException e) { 18373 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18374 } 18375 18376 prepareAppDataAfterInstallLIF(pkg); 18377 18378 // writer 18379 synchronized (mPackages) { 18380 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 18381 18382 // Propagate the permissions state as we do not want to drop on the floor 18383 // runtime permissions. The update permissions method below will take 18384 // care of removing obsolete permissions and grant install permissions. 18385 if (origPermissionState != null) { 18386 ps.getPermissionsState().copyFrom(origPermissionState); 18387 } 18388 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 18389 mPermissionCallback); 18390 18391 final boolean applyUserRestrictions 18392 = (allUserHandles != null) && (origUserHandles != null); 18393 if (applyUserRestrictions) { 18394 boolean installedStateChanged = false; 18395 if (DEBUG_REMOVE) { 18396 Slog.d(TAG, "Propagating install state across reinstall"); 18397 } 18398 for (int userId : allUserHandles) { 18399 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 18400 if (DEBUG_REMOVE) { 18401 Slog.d(TAG, " user " + userId + " => " + installed); 18402 } 18403 if (installed != ps.getInstalled(userId)) { 18404 installedStateChanged = true; 18405 } 18406 ps.setInstalled(installed, userId); 18407 18408 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18409 } 18410 // Regardless of writeSettings we need to ensure that this restriction 18411 // state propagation is persisted 18412 mSettings.writeAllUsersPackageRestrictionsLPr(); 18413 if (installedStateChanged) { 18414 mSettings.writeKernelMappingLPr(ps); 18415 } 18416 } 18417 // can downgrade to reader here 18418 if (writeSettings) { 18419 mSettings.writeLPr(); 18420 } 18421 } 18422 return pkg; 18423 } 18424 18425 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18426 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18427 PackageRemovedInfo outInfo, boolean writeSettings, 18428 PackageParser.Package replacingPackage) { 18429 synchronized (mPackages) { 18430 if (outInfo != null) { 18431 outInfo.uid = ps.appId; 18432 } 18433 18434 if (outInfo != null && outInfo.removedChildPackages != null) { 18435 final int childCount = (ps.childPackageNames != null) 18436 ? ps.childPackageNames.size() : 0; 18437 for (int i = 0; i < childCount; i++) { 18438 String childPackageName = ps.childPackageNames.get(i); 18439 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18440 if (childPs == null) { 18441 return false; 18442 } 18443 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18444 childPackageName); 18445 if (childInfo != null) { 18446 childInfo.uid = childPs.appId; 18447 } 18448 } 18449 } 18450 } 18451 18452 // Delete package data from internal structures and also remove data if flag is set 18453 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18454 18455 // Delete the child packages data 18456 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18457 for (int i = 0; i < childCount; i++) { 18458 PackageSetting childPs; 18459 synchronized (mPackages) { 18460 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18461 } 18462 if (childPs != null) { 18463 PackageRemovedInfo childOutInfo = (outInfo != null 18464 && outInfo.removedChildPackages != null) 18465 ? outInfo.removedChildPackages.get(childPs.name) : null; 18466 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18467 && (replacingPackage != null 18468 && !replacingPackage.hasChildPackage(childPs.name)) 18469 ? flags & ~DELETE_KEEP_DATA : flags; 18470 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18471 deleteFlags, writeSettings); 18472 } 18473 } 18474 18475 // Delete application code and resources only for parent packages 18476 if (ps.parentPackageName == null) { 18477 if (deleteCodeAndResources && (outInfo != null)) { 18478 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18479 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18480 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18481 } 18482 } 18483 18484 return true; 18485 } 18486 18487 @Override 18488 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18489 int userId) { 18490 mContext.enforceCallingOrSelfPermission( 18491 android.Manifest.permission.DELETE_PACKAGES, null); 18492 synchronized (mPackages) { 18493 // Cannot block uninstall of static shared libs as they are 18494 // considered a part of the using app (emulating static linking). 18495 // Also static libs are installed always on internal storage. 18496 PackageParser.Package pkg = mPackages.get(packageName); 18497 if (pkg != null && pkg.staticSharedLibName != null) { 18498 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18499 + " providing static shared library: " + pkg.staticSharedLibName); 18500 return false; 18501 } 18502 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 18503 mSettings.writePackageRestrictionsLPr(userId); 18504 } 18505 return true; 18506 } 18507 18508 @Override 18509 public boolean getBlockUninstallForUser(String packageName, int userId) { 18510 synchronized (mPackages) { 18511 final PackageSetting ps = mSettings.mPackages.get(packageName); 18512 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 18513 return false; 18514 } 18515 return mSettings.getBlockUninstallLPr(userId, packageName); 18516 } 18517 } 18518 18519 @Override 18520 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18521 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 18522 synchronized (mPackages) { 18523 PackageSetting ps = mSettings.mPackages.get(packageName); 18524 if (ps == null) { 18525 Log.w(TAG, "Package doesn't exist: " + packageName); 18526 return false; 18527 } 18528 if (systemUserApp) { 18529 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18530 } else { 18531 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18532 } 18533 mSettings.writeLPr(); 18534 } 18535 return true; 18536 } 18537 18538 /* 18539 * This method handles package deletion in general 18540 */ 18541 private boolean deletePackageLIF(String packageName, UserHandle user, 18542 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18543 PackageRemovedInfo outInfo, boolean writeSettings, 18544 PackageParser.Package replacingPackage) { 18545 if (packageName == null) { 18546 Slog.w(TAG, "Attempt to delete null packageName."); 18547 return false; 18548 } 18549 18550 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18551 18552 PackageSetting ps; 18553 synchronized (mPackages) { 18554 ps = mSettings.mPackages.get(packageName); 18555 if (ps == null) { 18556 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18557 return false; 18558 } 18559 18560 if (ps.parentPackageName != null && (!isSystemApp(ps) 18561 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18562 if (DEBUG_REMOVE) { 18563 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18564 + ((user == null) ? UserHandle.USER_ALL : user)); 18565 } 18566 final int removedUserId = (user != null) ? user.getIdentifier() 18567 : UserHandle.USER_ALL; 18568 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18569 return false; 18570 } 18571 markPackageUninstalledForUserLPw(ps, user); 18572 scheduleWritePackageRestrictionsLocked(user); 18573 return true; 18574 } 18575 } 18576 18577 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18578 && user.getIdentifier() != UserHandle.USER_ALL)) { 18579 // The caller is asking that the package only be deleted for a single 18580 // user. To do this, we just mark its uninstalled state and delete 18581 // its data. If this is a system app, we only allow this to happen if 18582 // they have set the special DELETE_SYSTEM_APP which requests different 18583 // semantics than normal for uninstalling system apps. 18584 markPackageUninstalledForUserLPw(ps, user); 18585 18586 if (!isSystemApp(ps)) { 18587 // Do not uninstall the APK if an app should be cached 18588 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18589 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18590 // Other user still have this package installed, so all 18591 // we need to do is clear this user's data and save that 18592 // it is uninstalled. 18593 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18594 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18595 return false; 18596 } 18597 scheduleWritePackageRestrictionsLocked(user); 18598 return true; 18599 } else { 18600 // We need to set it back to 'installed' so the uninstall 18601 // broadcasts will be sent correctly. 18602 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18603 ps.setInstalled(true, user.getIdentifier()); 18604 mSettings.writeKernelMappingLPr(ps); 18605 } 18606 } else { 18607 // This is a system app, so we assume that the 18608 // other users still have this package installed, so all 18609 // we need to do is clear this user's data and save that 18610 // it is uninstalled. 18611 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18612 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18613 return false; 18614 } 18615 scheduleWritePackageRestrictionsLocked(user); 18616 return true; 18617 } 18618 } 18619 18620 // If we are deleting a composite package for all users, keep track 18621 // of result for each child. 18622 if (ps.childPackageNames != null && outInfo != null) { 18623 synchronized (mPackages) { 18624 final int childCount = ps.childPackageNames.size(); 18625 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18626 for (int i = 0; i < childCount; i++) { 18627 String childPackageName = ps.childPackageNames.get(i); 18628 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18629 childInfo.removedPackage = childPackageName; 18630 childInfo.installerPackageName = ps.installerPackageName; 18631 outInfo.removedChildPackages.put(childPackageName, childInfo); 18632 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18633 if (childPs != null) { 18634 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18635 } 18636 } 18637 } 18638 } 18639 18640 boolean ret = false; 18641 if (isSystemApp(ps)) { 18642 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18643 // When an updated system application is deleted we delete the existing resources 18644 // as well and fall back to existing code in system partition 18645 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18646 } else { 18647 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18648 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18649 outInfo, writeSettings, replacingPackage); 18650 } 18651 18652 // Take a note whether we deleted the package for all users 18653 if (outInfo != null) { 18654 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18655 if (outInfo.removedChildPackages != null) { 18656 synchronized (mPackages) { 18657 final int childCount = outInfo.removedChildPackages.size(); 18658 for (int i = 0; i < childCount; i++) { 18659 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18660 if (childInfo != null) { 18661 childInfo.removedForAllUsers = mPackages.get( 18662 childInfo.removedPackage) == null; 18663 } 18664 } 18665 } 18666 } 18667 // If we uninstalled an update to a system app there may be some 18668 // child packages that appeared as they are declared in the system 18669 // app but were not declared in the update. 18670 if (isSystemApp(ps)) { 18671 synchronized (mPackages) { 18672 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18673 final int childCount = (updatedPs.childPackageNames != null) 18674 ? updatedPs.childPackageNames.size() : 0; 18675 for (int i = 0; i < childCount; i++) { 18676 String childPackageName = updatedPs.childPackageNames.get(i); 18677 if (outInfo.removedChildPackages == null 18678 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18679 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18680 if (childPs == null) { 18681 continue; 18682 } 18683 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18684 installRes.name = childPackageName; 18685 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18686 installRes.pkg = mPackages.get(childPackageName); 18687 installRes.uid = childPs.pkg.applicationInfo.uid; 18688 if (outInfo.appearedChildPackages == null) { 18689 outInfo.appearedChildPackages = new ArrayMap<>(); 18690 } 18691 outInfo.appearedChildPackages.put(childPackageName, installRes); 18692 } 18693 } 18694 } 18695 } 18696 } 18697 18698 return ret; 18699 } 18700 18701 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18702 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18703 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18704 for (int nextUserId : userIds) { 18705 if (DEBUG_REMOVE) { 18706 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18707 } 18708 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18709 false /*installed*/, 18710 true /*stopped*/, 18711 true /*notLaunched*/, 18712 false /*hidden*/, 18713 false /*suspended*/, 18714 false /*instantApp*/, 18715 false /*virtualPreload*/, 18716 null /*lastDisableAppCaller*/, 18717 null /*enabledComponents*/, 18718 null /*disabledComponents*/, 18719 ps.readUserState(nextUserId).domainVerificationStatus, 18720 0, PackageManager.INSTALL_REASON_UNKNOWN, 18721 null /*harmfulAppWarning*/); 18722 } 18723 mSettings.writeKernelMappingLPr(ps); 18724 } 18725 18726 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18727 PackageRemovedInfo outInfo) { 18728 final PackageParser.Package pkg; 18729 synchronized (mPackages) { 18730 pkg = mPackages.get(ps.name); 18731 } 18732 18733 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18734 : new int[] {userId}; 18735 for (int nextUserId : userIds) { 18736 if (DEBUG_REMOVE) { 18737 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18738 + nextUserId); 18739 } 18740 18741 destroyAppDataLIF(pkg, userId, 18742 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18743 destroyAppProfilesLIF(pkg, userId); 18744 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18745 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18746 schedulePackageCleaning(ps.name, nextUserId, false); 18747 synchronized (mPackages) { 18748 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18749 scheduleWritePackageRestrictionsLocked(nextUserId); 18750 } 18751 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18752 } 18753 } 18754 18755 if (outInfo != null) { 18756 outInfo.removedPackage = ps.name; 18757 outInfo.installerPackageName = ps.installerPackageName; 18758 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18759 outInfo.removedAppId = ps.appId; 18760 outInfo.removedUsers = userIds; 18761 outInfo.broadcastUsers = userIds; 18762 } 18763 18764 return true; 18765 } 18766 18767 private final class ClearStorageConnection implements ServiceConnection { 18768 IMediaContainerService mContainerService; 18769 18770 @Override 18771 public void onServiceConnected(ComponentName name, IBinder service) { 18772 synchronized (this) { 18773 mContainerService = IMediaContainerService.Stub 18774 .asInterface(Binder.allowBlocking(service)); 18775 notifyAll(); 18776 } 18777 } 18778 18779 @Override 18780 public void onServiceDisconnected(ComponentName name) { 18781 } 18782 } 18783 18784 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18785 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18786 18787 final boolean mounted; 18788 if (Environment.isExternalStorageEmulated()) { 18789 mounted = true; 18790 } else { 18791 final String status = Environment.getExternalStorageState(); 18792 18793 mounted = status.equals(Environment.MEDIA_MOUNTED) 18794 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18795 } 18796 18797 if (!mounted) { 18798 return; 18799 } 18800 18801 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18802 int[] users; 18803 if (userId == UserHandle.USER_ALL) { 18804 users = sUserManager.getUserIds(); 18805 } else { 18806 users = new int[] { userId }; 18807 } 18808 final ClearStorageConnection conn = new ClearStorageConnection(); 18809 if (mContext.bindServiceAsUser( 18810 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18811 try { 18812 for (int curUser : users) { 18813 long timeout = SystemClock.uptimeMillis() + 5000; 18814 synchronized (conn) { 18815 long now; 18816 while (conn.mContainerService == null && 18817 (now = SystemClock.uptimeMillis()) < timeout) { 18818 try { 18819 conn.wait(timeout - now); 18820 } catch (InterruptedException e) { 18821 } 18822 } 18823 } 18824 if (conn.mContainerService == null) { 18825 return; 18826 } 18827 18828 final UserEnvironment userEnv = new UserEnvironment(curUser); 18829 clearDirectory(conn.mContainerService, 18830 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18831 if (allData) { 18832 clearDirectory(conn.mContainerService, 18833 userEnv.buildExternalStorageAppDataDirs(packageName)); 18834 clearDirectory(conn.mContainerService, 18835 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18836 } 18837 } 18838 } finally { 18839 mContext.unbindService(conn); 18840 } 18841 } 18842 } 18843 18844 @Override 18845 public void clearApplicationProfileData(String packageName) { 18846 enforceSystemOrRoot("Only the system can clear all profile data"); 18847 18848 final PackageParser.Package pkg; 18849 synchronized (mPackages) { 18850 pkg = mPackages.get(packageName); 18851 } 18852 18853 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18854 synchronized (mInstallLock) { 18855 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18856 } 18857 } 18858 } 18859 18860 @Override 18861 public void clearApplicationUserData(final String packageName, 18862 final IPackageDataObserver observer, final int userId) { 18863 mContext.enforceCallingOrSelfPermission( 18864 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18865 18866 final int callingUid = Binder.getCallingUid(); 18867 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18868 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18869 18870 final PackageSetting ps = mSettings.getPackageLPr(packageName); 18871 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 18872 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18873 throw new SecurityException("Cannot clear data for a protected package: " 18874 + packageName); 18875 } 18876 // Queue up an async operation since the package deletion may take a little while. 18877 mHandler.post(new Runnable() { 18878 public void run() { 18879 mHandler.removeCallbacks(this); 18880 final boolean succeeded; 18881 if (!filterApp) { 18882 try (PackageFreezer freezer = freezePackage(packageName, 18883 "clearApplicationUserData")) { 18884 synchronized (mInstallLock) { 18885 succeeded = clearApplicationUserDataLIF(packageName, userId); 18886 } 18887 clearExternalStorageDataSync(packageName, userId, true); 18888 synchronized (mPackages) { 18889 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18890 packageName, userId); 18891 } 18892 } 18893 if (succeeded) { 18894 // invoke DeviceStorageMonitor's update method to clear any notifications 18895 DeviceStorageMonitorInternal dsm = LocalServices 18896 .getService(DeviceStorageMonitorInternal.class); 18897 if (dsm != null) { 18898 dsm.checkMemory(); 18899 } 18900 } 18901 } else { 18902 succeeded = false; 18903 } 18904 if (observer != null) { 18905 try { 18906 observer.onRemoveCompleted(packageName, succeeded); 18907 } catch (RemoteException e) { 18908 Log.i(TAG, "Observer no longer exists."); 18909 } 18910 } //end if observer 18911 } //end run 18912 }); 18913 } 18914 18915 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18916 if (packageName == null) { 18917 Slog.w(TAG, "Attempt to delete null packageName."); 18918 return false; 18919 } 18920 18921 // Try finding details about the requested package 18922 PackageParser.Package pkg; 18923 synchronized (mPackages) { 18924 pkg = mPackages.get(packageName); 18925 if (pkg == null) { 18926 final PackageSetting ps = mSettings.mPackages.get(packageName); 18927 if (ps != null) { 18928 pkg = ps.pkg; 18929 } 18930 } 18931 18932 if (pkg == null) { 18933 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18934 return false; 18935 } 18936 18937 PackageSetting ps = (PackageSetting) pkg.mExtras; 18938 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18939 } 18940 18941 clearAppDataLIF(pkg, userId, 18942 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18943 18944 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18945 removeKeystoreDataIfNeeded(userId, appId); 18946 18947 UserManagerInternal umInternal = getUserManagerInternal(); 18948 final int flags; 18949 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18950 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18951 } else if (umInternal.isUserRunning(userId)) { 18952 flags = StorageManager.FLAG_STORAGE_DE; 18953 } else { 18954 flags = 0; 18955 } 18956 prepareAppDataContentsLIF(pkg, userId, flags); 18957 18958 return true; 18959 } 18960 18961 /** 18962 * Reverts user permission state changes (permissions and flags) in 18963 * all packages for a given user. 18964 * 18965 * @param userId The device user for which to do a reset. 18966 */ 18967 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18968 final int packageCount = mPackages.size(); 18969 for (int i = 0; i < packageCount; i++) { 18970 PackageParser.Package pkg = mPackages.valueAt(i); 18971 PackageSetting ps = (PackageSetting) pkg.mExtras; 18972 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18973 } 18974 } 18975 18976 private void resetNetworkPolicies(int userId) { 18977 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18978 } 18979 18980 /** 18981 * Reverts user permission state changes (permissions and flags). 18982 * 18983 * @param ps The package for which to reset. 18984 * @param userId The device user for which to do a reset. 18985 */ 18986 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18987 final PackageSetting ps, final int userId) { 18988 if (ps.pkg == null) { 18989 return; 18990 } 18991 18992 // These are flags that can change base on user actions. 18993 final int userSettableMask = FLAG_PERMISSION_USER_SET 18994 | FLAG_PERMISSION_USER_FIXED 18995 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18996 | FLAG_PERMISSION_REVIEW_REQUIRED; 18997 18998 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18999 | FLAG_PERMISSION_POLICY_FIXED; 19000 19001 boolean writeInstallPermissions = false; 19002 boolean writeRuntimePermissions = false; 19003 19004 final int permissionCount = ps.pkg.requestedPermissions.size(); 19005 for (int i = 0; i < permissionCount; i++) { 19006 final String permName = ps.pkg.requestedPermissions.get(i); 19007 final BasePermission bp = 19008 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 19009 if (bp == null) { 19010 continue; 19011 } 19012 19013 // If shared user we just reset the state to which only this app contributed. 19014 if (ps.sharedUser != null) { 19015 boolean used = false; 19016 final int packageCount = ps.sharedUser.packages.size(); 19017 for (int j = 0; j < packageCount; j++) { 19018 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 19019 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 19020 && pkg.pkg.requestedPermissions.contains(permName)) { 19021 used = true; 19022 break; 19023 } 19024 } 19025 if (used) { 19026 continue; 19027 } 19028 } 19029 19030 final PermissionsState permissionsState = ps.getPermissionsState(); 19031 19032 final int oldFlags = permissionsState.getPermissionFlags(permName, userId); 19033 19034 // Always clear the user settable flags. 19035 final boolean hasInstallState = 19036 permissionsState.getInstallPermissionState(permName) != null; 19037 // If permission review is enabled and this is a legacy app, mark the 19038 // permission as requiring a review as this is the initial state. 19039 int flags = 0; 19040 if (mSettings.mPermissions.mPermissionReviewRequired 19041 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 19042 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 19043 } 19044 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 19045 if (hasInstallState) { 19046 writeInstallPermissions = true; 19047 } else { 19048 writeRuntimePermissions = true; 19049 } 19050 } 19051 19052 // Below is only runtime permission handling. 19053 if (!bp.isRuntime()) { 19054 continue; 19055 } 19056 19057 // Never clobber system or policy. 19058 if ((oldFlags & policyOrSystemFlags) != 0) { 19059 continue; 19060 } 19061 19062 // If this permission was granted by default, make sure it is. 19063 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 19064 if (permissionsState.grantRuntimePermission(bp, userId) 19065 != PERMISSION_OPERATION_FAILURE) { 19066 writeRuntimePermissions = true; 19067 } 19068 // If permission review is enabled the permissions for a legacy apps 19069 // are represented as constantly granted runtime ones, so don't revoke. 19070 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 19071 // Otherwise, reset the permission. 19072 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 19073 switch (revokeResult) { 19074 case PERMISSION_OPERATION_SUCCESS: 19075 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 19076 writeRuntimePermissions = true; 19077 final int appId = ps.appId; 19078 mHandler.post(new Runnable() { 19079 @Override 19080 public void run() { 19081 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 19082 } 19083 }); 19084 } break; 19085 } 19086 } 19087 } 19088 19089 // Synchronously write as we are taking permissions away. 19090 if (writeRuntimePermissions) { 19091 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 19092 } 19093 19094 // Synchronously write as we are taking permissions away. 19095 if (writeInstallPermissions) { 19096 mSettings.writeLPr(); 19097 } 19098 } 19099 19100 /** 19101 * Remove entries from the keystore daemon. Will only remove it if the 19102 * {@code appId} is valid. 19103 */ 19104 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 19105 if (appId < 0) { 19106 return; 19107 } 19108 19109 final KeyStore keyStore = KeyStore.getInstance(); 19110 if (keyStore != null) { 19111 if (userId == UserHandle.USER_ALL) { 19112 for (final int individual : sUserManager.getUserIds()) { 19113 keyStore.clearUid(UserHandle.getUid(individual, appId)); 19114 } 19115 } else { 19116 keyStore.clearUid(UserHandle.getUid(userId, appId)); 19117 } 19118 } else { 19119 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 19120 } 19121 } 19122 19123 @Override 19124 public void deleteApplicationCacheFiles(final String packageName, 19125 final IPackageDataObserver observer) { 19126 final int userId = UserHandle.getCallingUserId(); 19127 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 19128 } 19129 19130 @Override 19131 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 19132 final IPackageDataObserver observer) { 19133 final int callingUid = Binder.getCallingUid(); 19134 mContext.enforceCallingOrSelfPermission( 19135 android.Manifest.permission.DELETE_CACHE_FILES, null); 19136 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19137 /* requireFullPermission= */ true, /* checkShell= */ false, 19138 "delete application cache files"); 19139 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 19140 android.Manifest.permission.ACCESS_INSTANT_APPS); 19141 19142 final PackageParser.Package pkg; 19143 synchronized (mPackages) { 19144 pkg = mPackages.get(packageName); 19145 } 19146 19147 // Queue up an async operation since the package deletion may take a little while. 19148 mHandler.post(new Runnable() { 19149 public void run() { 19150 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 19151 boolean doClearData = true; 19152 if (ps != null) { 19153 final boolean targetIsInstantApp = 19154 ps.getInstantApp(UserHandle.getUserId(callingUid)); 19155 doClearData = !targetIsInstantApp 19156 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 19157 } 19158 if (doClearData) { 19159 synchronized (mInstallLock) { 19160 final int flags = StorageManager.FLAG_STORAGE_DE 19161 | StorageManager.FLAG_STORAGE_CE; 19162 // We're only clearing cache files, so we don't care if the 19163 // app is unfrozen and still able to run 19164 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 19165 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19166 } 19167 clearExternalStorageDataSync(packageName, userId, false); 19168 } 19169 if (observer != null) { 19170 try { 19171 observer.onRemoveCompleted(packageName, true); 19172 } catch (RemoteException e) { 19173 Log.i(TAG, "Observer no longer exists."); 19174 } 19175 } 19176 } 19177 }); 19178 } 19179 19180 @Override 19181 public void getPackageSizeInfo(final String packageName, int userHandle, 19182 final IPackageStatsObserver observer) { 19183 throw new UnsupportedOperationException( 19184 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 19185 } 19186 19187 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 19188 final PackageSetting ps; 19189 synchronized (mPackages) { 19190 ps = mSettings.mPackages.get(packageName); 19191 if (ps == null) { 19192 Slog.w(TAG, "Failed to find settings for " + packageName); 19193 return false; 19194 } 19195 } 19196 19197 final String[] packageNames = { packageName }; 19198 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 19199 final String[] codePaths = { ps.codePathString }; 19200 19201 try { 19202 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 19203 ps.appId, ceDataInodes, codePaths, stats); 19204 19205 // For now, ignore code size of packages on system partition 19206 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 19207 stats.codeSize = 0; 19208 } 19209 19210 // External clients expect these to be tracked separately 19211 stats.dataSize -= stats.cacheSize; 19212 19213 } catch (InstallerException e) { 19214 Slog.w(TAG, String.valueOf(e)); 19215 return false; 19216 } 19217 19218 return true; 19219 } 19220 19221 private int getUidTargetSdkVersionLockedLPr(int uid) { 19222 Object obj = mSettings.getUserIdLPr(uid); 19223 if (obj instanceof SharedUserSetting) { 19224 final SharedUserSetting sus = (SharedUserSetting) obj; 19225 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 19226 final Iterator<PackageSetting> it = sus.packages.iterator(); 19227 while (it.hasNext()) { 19228 final PackageSetting ps = it.next(); 19229 if (ps.pkg != null) { 19230 int v = ps.pkg.applicationInfo.targetSdkVersion; 19231 if (v < vers) vers = v; 19232 } 19233 } 19234 return vers; 19235 } else if (obj instanceof PackageSetting) { 19236 final PackageSetting ps = (PackageSetting) obj; 19237 if (ps.pkg != null) { 19238 return ps.pkg.applicationInfo.targetSdkVersion; 19239 } 19240 } 19241 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19242 } 19243 19244 private int getPackageTargetSdkVersionLockedLPr(String packageName) { 19245 final PackageParser.Package p = mPackages.get(packageName); 19246 if (p != null) { 19247 return p.applicationInfo.targetSdkVersion; 19248 } 19249 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19250 } 19251 19252 @Override 19253 public void addPreferredActivity(IntentFilter filter, int match, 19254 ComponentName[] set, ComponentName activity, int userId) { 19255 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19256 "Adding preferred"); 19257 } 19258 19259 private void addPreferredActivityInternal(IntentFilter filter, int match, 19260 ComponentName[] set, ComponentName activity, boolean always, int userId, 19261 String opname) { 19262 // writer 19263 int callingUid = Binder.getCallingUid(); 19264 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19265 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 19266 if (filter.countActions() == 0) { 19267 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19268 return; 19269 } 19270 synchronized (mPackages) { 19271 if (mContext.checkCallingOrSelfPermission( 19272 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19273 != PackageManager.PERMISSION_GRANTED) { 19274 if (getUidTargetSdkVersionLockedLPr(callingUid) 19275 < Build.VERSION_CODES.FROYO) { 19276 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 19277 + callingUid); 19278 return; 19279 } 19280 mContext.enforceCallingOrSelfPermission( 19281 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19282 } 19283 19284 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 19285 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 19286 + userId + ":"); 19287 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19288 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 19289 scheduleWritePackageRestrictionsLocked(userId); 19290 postPreferredActivityChangedBroadcast(userId); 19291 } 19292 } 19293 19294 private void postPreferredActivityChangedBroadcast(int userId) { 19295 mHandler.post(() -> { 19296 final IActivityManager am = ActivityManager.getService(); 19297 if (am == null) { 19298 return; 19299 } 19300 19301 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 19302 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 19303 try { 19304 am.broadcastIntent(null, intent, null, null, 19305 0, null, null, null, android.app.AppOpsManager.OP_NONE, 19306 null, false, false, userId); 19307 } catch (RemoteException e) { 19308 } 19309 }); 19310 } 19311 19312 @Override 19313 public void replacePreferredActivity(IntentFilter filter, int match, 19314 ComponentName[] set, ComponentName activity, int userId) { 19315 if (filter.countActions() != 1) { 19316 throw new IllegalArgumentException( 19317 "replacePreferredActivity expects filter to have only 1 action."); 19318 } 19319 if (filter.countDataAuthorities() != 0 19320 || filter.countDataPaths() != 0 19321 || filter.countDataSchemes() > 1 19322 || filter.countDataTypes() != 0) { 19323 throw new IllegalArgumentException( 19324 "replacePreferredActivity expects filter to have no data authorities, " + 19325 "paths, or types; and at most one scheme."); 19326 } 19327 19328 final int callingUid = Binder.getCallingUid(); 19329 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19330 true /* requireFullPermission */, false /* checkShell */, 19331 "replace preferred activity"); 19332 synchronized (mPackages) { 19333 if (mContext.checkCallingOrSelfPermission( 19334 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19335 != PackageManager.PERMISSION_GRANTED) { 19336 if (getUidTargetSdkVersionLockedLPr(callingUid) 19337 < Build.VERSION_CODES.FROYO) { 19338 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 19339 + Binder.getCallingUid()); 19340 return; 19341 } 19342 mContext.enforceCallingOrSelfPermission( 19343 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19344 } 19345 19346 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19347 if (pir != null) { 19348 // Get all of the existing entries that exactly match this filter. 19349 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 19350 if (existing != null && existing.size() == 1) { 19351 PreferredActivity cur = existing.get(0); 19352 if (DEBUG_PREFERRED) { 19353 Slog.i(TAG, "Checking replace of preferred:"); 19354 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19355 if (!cur.mPref.mAlways) { 19356 Slog.i(TAG, " -- CUR; not mAlways!"); 19357 } else { 19358 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19359 Slog.i(TAG, " -- CUR: mSet=" 19360 + Arrays.toString(cur.mPref.mSetComponents)); 19361 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19362 Slog.i(TAG, " -- NEW: mMatch=" 19363 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19364 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19365 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19366 } 19367 } 19368 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19369 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19370 && cur.mPref.sameSet(set)) { 19371 // Setting the preferred activity to what it happens to be already 19372 if (DEBUG_PREFERRED) { 19373 Slog.i(TAG, "Replacing with same preferred activity " 19374 + cur.mPref.mShortComponent + " for user " 19375 + userId + ":"); 19376 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19377 } 19378 return; 19379 } 19380 } 19381 19382 if (existing != null) { 19383 if (DEBUG_PREFERRED) { 19384 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19385 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19386 } 19387 for (int i = 0; i < existing.size(); i++) { 19388 PreferredActivity pa = existing.get(i); 19389 if (DEBUG_PREFERRED) { 19390 Slog.i(TAG, "Removing existing preferred activity " 19391 + pa.mPref.mComponent + ":"); 19392 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19393 } 19394 pir.removeFilter(pa); 19395 } 19396 } 19397 } 19398 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19399 "Replacing preferred"); 19400 } 19401 } 19402 19403 @Override 19404 public void clearPackagePreferredActivities(String packageName) { 19405 final int callingUid = Binder.getCallingUid(); 19406 if (getInstantAppPackageName(callingUid) != null) { 19407 return; 19408 } 19409 // writer 19410 synchronized (mPackages) { 19411 PackageParser.Package pkg = mPackages.get(packageName); 19412 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 19413 if (mContext.checkCallingOrSelfPermission( 19414 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19415 != PackageManager.PERMISSION_GRANTED) { 19416 if (getUidTargetSdkVersionLockedLPr(callingUid) 19417 < Build.VERSION_CODES.FROYO) { 19418 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19419 + callingUid); 19420 return; 19421 } 19422 mContext.enforceCallingOrSelfPermission( 19423 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19424 } 19425 } 19426 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19427 if (ps != null 19428 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 19429 return; 19430 } 19431 int user = UserHandle.getCallingUserId(); 19432 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19433 scheduleWritePackageRestrictionsLocked(user); 19434 } 19435 } 19436 } 19437 19438 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19439 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19440 ArrayList<PreferredActivity> removed = null; 19441 boolean changed = false; 19442 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19443 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19444 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19445 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19446 continue; 19447 } 19448 Iterator<PreferredActivity> it = pir.filterIterator(); 19449 while (it.hasNext()) { 19450 PreferredActivity pa = it.next(); 19451 // Mark entry for removal only if it matches the package name 19452 // and the entry is of type "always". 19453 if (packageName == null || 19454 (pa.mPref.mComponent.getPackageName().equals(packageName) 19455 && pa.mPref.mAlways)) { 19456 if (removed == null) { 19457 removed = new ArrayList<PreferredActivity>(); 19458 } 19459 removed.add(pa); 19460 } 19461 } 19462 if (removed != null) { 19463 for (int j=0; j<removed.size(); j++) { 19464 PreferredActivity pa = removed.get(j); 19465 pir.removeFilter(pa); 19466 } 19467 changed = true; 19468 } 19469 } 19470 if (changed) { 19471 postPreferredActivityChangedBroadcast(userId); 19472 } 19473 return changed; 19474 } 19475 19476 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19477 private void clearIntentFilterVerificationsLPw(int userId) { 19478 final int packageCount = mPackages.size(); 19479 for (int i = 0; i < packageCount; i++) { 19480 PackageParser.Package pkg = mPackages.valueAt(i); 19481 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19482 } 19483 } 19484 19485 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19486 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19487 if (userId == UserHandle.USER_ALL) { 19488 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19489 sUserManager.getUserIds())) { 19490 for (int oneUserId : sUserManager.getUserIds()) { 19491 scheduleWritePackageRestrictionsLocked(oneUserId); 19492 } 19493 } 19494 } else { 19495 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19496 scheduleWritePackageRestrictionsLocked(userId); 19497 } 19498 } 19499 } 19500 19501 /** Clears state for all users, and touches intent filter verification policy */ 19502 void clearDefaultBrowserIfNeeded(String packageName) { 19503 for (int oneUserId : sUserManager.getUserIds()) { 19504 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19505 } 19506 } 19507 19508 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19509 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19510 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19511 if (packageName.equals(defaultBrowserPackageName)) { 19512 setDefaultBrowserPackageName(null, userId); 19513 } 19514 } 19515 } 19516 19517 @Override 19518 public void resetApplicationPreferences(int userId) { 19519 mContext.enforceCallingOrSelfPermission( 19520 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19521 final long identity = Binder.clearCallingIdentity(); 19522 // writer 19523 try { 19524 synchronized (mPackages) { 19525 clearPackagePreferredActivitiesLPw(null, userId); 19526 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19527 // TODO: We have to reset the default SMS and Phone. This requires 19528 // significant refactoring to keep all default apps in the package 19529 // manager (cleaner but more work) or have the services provide 19530 // callbacks to the package manager to request a default app reset. 19531 applyFactoryDefaultBrowserLPw(userId); 19532 clearIntentFilterVerificationsLPw(userId); 19533 primeDomainVerificationsLPw(userId); 19534 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19535 scheduleWritePackageRestrictionsLocked(userId); 19536 } 19537 resetNetworkPolicies(userId); 19538 } finally { 19539 Binder.restoreCallingIdentity(identity); 19540 } 19541 } 19542 19543 @Override 19544 public int getPreferredActivities(List<IntentFilter> outFilters, 19545 List<ComponentName> outActivities, String packageName) { 19546 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19547 return 0; 19548 } 19549 int num = 0; 19550 final int userId = UserHandle.getCallingUserId(); 19551 // reader 19552 synchronized (mPackages) { 19553 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19554 if (pir != null) { 19555 final Iterator<PreferredActivity> it = pir.filterIterator(); 19556 while (it.hasNext()) { 19557 final PreferredActivity pa = it.next(); 19558 if (packageName == null 19559 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19560 && pa.mPref.mAlways)) { 19561 if (outFilters != null) { 19562 outFilters.add(new IntentFilter(pa)); 19563 } 19564 if (outActivities != null) { 19565 outActivities.add(pa.mPref.mComponent); 19566 } 19567 } 19568 } 19569 } 19570 } 19571 19572 return num; 19573 } 19574 19575 @Override 19576 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19577 int userId) { 19578 int callingUid = Binder.getCallingUid(); 19579 if (callingUid != Process.SYSTEM_UID) { 19580 throw new SecurityException( 19581 "addPersistentPreferredActivity can only be run by the system"); 19582 } 19583 if (filter.countActions() == 0) { 19584 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19585 return; 19586 } 19587 synchronized (mPackages) { 19588 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19589 ":"); 19590 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19591 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19592 new PersistentPreferredActivity(filter, activity)); 19593 scheduleWritePackageRestrictionsLocked(userId); 19594 postPreferredActivityChangedBroadcast(userId); 19595 } 19596 } 19597 19598 @Override 19599 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19600 int callingUid = Binder.getCallingUid(); 19601 if (callingUid != Process.SYSTEM_UID) { 19602 throw new SecurityException( 19603 "clearPackagePersistentPreferredActivities can only be run by the system"); 19604 } 19605 ArrayList<PersistentPreferredActivity> removed = null; 19606 boolean changed = false; 19607 synchronized (mPackages) { 19608 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19609 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19610 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19611 .valueAt(i); 19612 if (userId != thisUserId) { 19613 continue; 19614 } 19615 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19616 while (it.hasNext()) { 19617 PersistentPreferredActivity ppa = it.next(); 19618 // Mark entry for removal only if it matches the package name. 19619 if (ppa.mComponent.getPackageName().equals(packageName)) { 19620 if (removed == null) { 19621 removed = new ArrayList<PersistentPreferredActivity>(); 19622 } 19623 removed.add(ppa); 19624 } 19625 } 19626 if (removed != null) { 19627 for (int j=0; j<removed.size(); j++) { 19628 PersistentPreferredActivity ppa = removed.get(j); 19629 ppir.removeFilter(ppa); 19630 } 19631 changed = true; 19632 } 19633 } 19634 19635 if (changed) { 19636 scheduleWritePackageRestrictionsLocked(userId); 19637 postPreferredActivityChangedBroadcast(userId); 19638 } 19639 } 19640 } 19641 19642 /** 19643 * Common machinery for picking apart a restored XML blob and passing 19644 * it to a caller-supplied functor to be applied to the running system. 19645 */ 19646 private void restoreFromXml(XmlPullParser parser, int userId, 19647 String expectedStartTag, BlobXmlRestorer functor) 19648 throws IOException, XmlPullParserException { 19649 int type; 19650 while ((type = parser.next()) != XmlPullParser.START_TAG 19651 && type != XmlPullParser.END_DOCUMENT) { 19652 } 19653 if (type != XmlPullParser.START_TAG) { 19654 // oops didn't find a start tag?! 19655 if (DEBUG_BACKUP) { 19656 Slog.e(TAG, "Didn't find start tag during restore"); 19657 } 19658 return; 19659 } 19660Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19661 // this is supposed to be TAG_PREFERRED_BACKUP 19662 if (!expectedStartTag.equals(parser.getName())) { 19663 if (DEBUG_BACKUP) { 19664 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19665 } 19666 return; 19667 } 19668 19669 // skip interfering stuff, then we're aligned with the backing implementation 19670 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19671Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19672 functor.apply(parser, userId); 19673 } 19674 19675 private interface BlobXmlRestorer { 19676 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19677 } 19678 19679 /** 19680 * Non-Binder method, support for the backup/restore mechanism: write the 19681 * full set of preferred activities in its canonical XML format. Returns the 19682 * XML output as a byte array, or null if there is none. 19683 */ 19684 @Override 19685 public byte[] getPreferredActivityBackup(int userId) { 19686 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19687 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19688 } 19689 19690 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19691 try { 19692 final XmlSerializer serializer = new FastXmlSerializer(); 19693 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19694 serializer.startDocument(null, true); 19695 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19696 19697 synchronized (mPackages) { 19698 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19699 } 19700 19701 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19702 serializer.endDocument(); 19703 serializer.flush(); 19704 } catch (Exception e) { 19705 if (DEBUG_BACKUP) { 19706 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19707 } 19708 return null; 19709 } 19710 19711 return dataStream.toByteArray(); 19712 } 19713 19714 @Override 19715 public void restorePreferredActivities(byte[] backup, int userId) { 19716 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19717 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19718 } 19719 19720 try { 19721 final XmlPullParser parser = Xml.newPullParser(); 19722 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19723 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19724 new BlobXmlRestorer() { 19725 @Override 19726 public void apply(XmlPullParser parser, int userId) 19727 throws XmlPullParserException, IOException { 19728 synchronized (mPackages) { 19729 mSettings.readPreferredActivitiesLPw(parser, userId); 19730 } 19731 } 19732 } ); 19733 } catch (Exception e) { 19734 if (DEBUG_BACKUP) { 19735 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19736 } 19737 } 19738 } 19739 19740 /** 19741 * Non-Binder method, support for the backup/restore mechanism: write the 19742 * default browser (etc) settings in its canonical XML format. Returns the default 19743 * browser XML representation as a byte array, or null if there is none. 19744 */ 19745 @Override 19746 public byte[] getDefaultAppsBackup(int userId) { 19747 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19748 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19749 } 19750 19751 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19752 try { 19753 final XmlSerializer serializer = new FastXmlSerializer(); 19754 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19755 serializer.startDocument(null, true); 19756 serializer.startTag(null, TAG_DEFAULT_APPS); 19757 19758 synchronized (mPackages) { 19759 mSettings.writeDefaultAppsLPr(serializer, userId); 19760 } 19761 19762 serializer.endTag(null, TAG_DEFAULT_APPS); 19763 serializer.endDocument(); 19764 serializer.flush(); 19765 } catch (Exception e) { 19766 if (DEBUG_BACKUP) { 19767 Slog.e(TAG, "Unable to write default apps for backup", e); 19768 } 19769 return null; 19770 } 19771 19772 return dataStream.toByteArray(); 19773 } 19774 19775 @Override 19776 public void restoreDefaultApps(byte[] backup, int userId) { 19777 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19778 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19779 } 19780 19781 try { 19782 final XmlPullParser parser = Xml.newPullParser(); 19783 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19784 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19785 new BlobXmlRestorer() { 19786 @Override 19787 public void apply(XmlPullParser parser, int userId) 19788 throws XmlPullParserException, IOException { 19789 synchronized (mPackages) { 19790 mSettings.readDefaultAppsLPw(parser, userId); 19791 } 19792 } 19793 } ); 19794 } catch (Exception e) { 19795 if (DEBUG_BACKUP) { 19796 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19797 } 19798 } 19799 } 19800 19801 @Override 19802 public byte[] getIntentFilterVerificationBackup(int userId) { 19803 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19804 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19805 } 19806 19807 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19808 try { 19809 final XmlSerializer serializer = new FastXmlSerializer(); 19810 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19811 serializer.startDocument(null, true); 19812 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19813 19814 synchronized (mPackages) { 19815 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19816 } 19817 19818 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19819 serializer.endDocument(); 19820 serializer.flush(); 19821 } catch (Exception e) { 19822 if (DEBUG_BACKUP) { 19823 Slog.e(TAG, "Unable to write default apps for backup", e); 19824 } 19825 return null; 19826 } 19827 19828 return dataStream.toByteArray(); 19829 } 19830 19831 @Override 19832 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19833 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19834 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19835 } 19836 19837 try { 19838 final XmlPullParser parser = Xml.newPullParser(); 19839 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19840 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19841 new BlobXmlRestorer() { 19842 @Override 19843 public void apply(XmlPullParser parser, int userId) 19844 throws XmlPullParserException, IOException { 19845 synchronized (mPackages) { 19846 mSettings.readAllDomainVerificationsLPr(parser, userId); 19847 mSettings.writeLPr(); 19848 } 19849 } 19850 } ); 19851 } catch (Exception e) { 19852 if (DEBUG_BACKUP) { 19853 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19854 } 19855 } 19856 } 19857 19858 @Override 19859 public byte[] getPermissionGrantBackup(int userId) { 19860 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19861 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19862 } 19863 19864 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19865 try { 19866 final XmlSerializer serializer = new FastXmlSerializer(); 19867 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19868 serializer.startDocument(null, true); 19869 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19870 19871 synchronized (mPackages) { 19872 serializeRuntimePermissionGrantsLPr(serializer, userId); 19873 } 19874 19875 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19876 serializer.endDocument(); 19877 serializer.flush(); 19878 } catch (Exception e) { 19879 if (DEBUG_BACKUP) { 19880 Slog.e(TAG, "Unable to write default apps for backup", e); 19881 } 19882 return null; 19883 } 19884 19885 return dataStream.toByteArray(); 19886 } 19887 19888 @Override 19889 public void restorePermissionGrants(byte[] backup, int userId) { 19890 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19891 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19892 } 19893 19894 try { 19895 final XmlPullParser parser = Xml.newPullParser(); 19896 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19897 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19898 new BlobXmlRestorer() { 19899 @Override 19900 public void apply(XmlPullParser parser, int userId) 19901 throws XmlPullParserException, IOException { 19902 synchronized (mPackages) { 19903 processRestoredPermissionGrantsLPr(parser, userId); 19904 } 19905 } 19906 } ); 19907 } catch (Exception e) { 19908 if (DEBUG_BACKUP) { 19909 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19910 } 19911 } 19912 } 19913 19914 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19915 throws IOException { 19916 serializer.startTag(null, TAG_ALL_GRANTS); 19917 19918 final int N = mSettings.mPackages.size(); 19919 for (int i = 0; i < N; i++) { 19920 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19921 boolean pkgGrantsKnown = false; 19922 19923 PermissionsState packagePerms = ps.getPermissionsState(); 19924 19925 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19926 final int grantFlags = state.getFlags(); 19927 // only look at grants that are not system/policy fixed 19928 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19929 final boolean isGranted = state.isGranted(); 19930 // And only back up the user-twiddled state bits 19931 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19932 final String packageName = mSettings.mPackages.keyAt(i); 19933 if (!pkgGrantsKnown) { 19934 serializer.startTag(null, TAG_GRANT); 19935 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19936 pkgGrantsKnown = true; 19937 } 19938 19939 final boolean userSet = 19940 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19941 final boolean userFixed = 19942 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19943 final boolean revoke = 19944 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19945 19946 serializer.startTag(null, TAG_PERMISSION); 19947 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19948 if (isGranted) { 19949 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19950 } 19951 if (userSet) { 19952 serializer.attribute(null, ATTR_USER_SET, "true"); 19953 } 19954 if (userFixed) { 19955 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19956 } 19957 if (revoke) { 19958 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19959 } 19960 serializer.endTag(null, TAG_PERMISSION); 19961 } 19962 } 19963 } 19964 19965 if (pkgGrantsKnown) { 19966 serializer.endTag(null, TAG_GRANT); 19967 } 19968 } 19969 19970 serializer.endTag(null, TAG_ALL_GRANTS); 19971 } 19972 19973 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19974 throws XmlPullParserException, IOException { 19975 String pkgName = null; 19976 int outerDepth = parser.getDepth(); 19977 int type; 19978 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19979 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19980 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19981 continue; 19982 } 19983 19984 final String tagName = parser.getName(); 19985 if (tagName.equals(TAG_GRANT)) { 19986 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19987 if (DEBUG_BACKUP) { 19988 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19989 } 19990 } else if (tagName.equals(TAG_PERMISSION)) { 19991 19992 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19993 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19994 19995 int newFlagSet = 0; 19996 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19997 newFlagSet |= FLAG_PERMISSION_USER_SET; 19998 } 19999 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 20000 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 20001 } 20002 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 20003 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 20004 } 20005 if (DEBUG_BACKUP) { 20006 Slog.v(TAG, " + Restoring grant:" 20007 + " pkg=" + pkgName 20008 + " perm=" + permName 20009 + " granted=" + isGranted 20010 + " bits=0x" + Integer.toHexString(newFlagSet)); 20011 } 20012 final PackageSetting ps = mSettings.mPackages.get(pkgName); 20013 if (ps != null) { 20014 // Already installed so we apply the grant immediately 20015 if (DEBUG_BACKUP) { 20016 Slog.v(TAG, " + already installed; applying"); 20017 } 20018 PermissionsState perms = ps.getPermissionsState(); 20019 BasePermission bp = 20020 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 20021 if (bp != null) { 20022 if (isGranted) { 20023 perms.grantRuntimePermission(bp, userId); 20024 } 20025 if (newFlagSet != 0) { 20026 perms.updatePermissionFlags( 20027 bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 20028 } 20029 } 20030 } else { 20031 // Need to wait for post-restore install to apply the grant 20032 if (DEBUG_BACKUP) { 20033 Slog.v(TAG, " - not yet installed; saving for later"); 20034 } 20035 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 20036 isGranted, newFlagSet, userId); 20037 } 20038 } else { 20039 PackageManagerService.reportSettingsProblem(Log.WARN, 20040 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 20041 XmlUtils.skipCurrentTag(parser); 20042 } 20043 } 20044 20045 scheduleWriteSettingsLocked(); 20046 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 20047 } 20048 20049 @Override 20050 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 20051 int sourceUserId, int targetUserId, int flags) { 20052 mContext.enforceCallingOrSelfPermission( 20053 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20054 int callingUid = Binder.getCallingUid(); 20055 enforceOwnerRights(ownerPackage, callingUid); 20056 PackageManagerServiceUtils.enforceShellRestriction( 20057 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20058 if (intentFilter.countActions() == 0) { 20059 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 20060 return; 20061 } 20062 synchronized (mPackages) { 20063 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 20064 ownerPackage, targetUserId, flags); 20065 CrossProfileIntentResolver resolver = 20066 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20067 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 20068 // We have all those whose filter is equal. Now checking if the rest is equal as well. 20069 if (existing != null) { 20070 int size = existing.size(); 20071 for (int i = 0; i < size; i++) { 20072 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 20073 return; 20074 } 20075 } 20076 } 20077 resolver.addFilter(newFilter); 20078 scheduleWritePackageRestrictionsLocked(sourceUserId); 20079 } 20080 } 20081 20082 @Override 20083 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 20084 mContext.enforceCallingOrSelfPermission( 20085 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20086 final int callingUid = Binder.getCallingUid(); 20087 enforceOwnerRights(ownerPackage, callingUid); 20088 PackageManagerServiceUtils.enforceShellRestriction( 20089 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20090 synchronized (mPackages) { 20091 CrossProfileIntentResolver resolver = 20092 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20093 ArraySet<CrossProfileIntentFilter> set = 20094 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 20095 for (CrossProfileIntentFilter filter : set) { 20096 if (filter.getOwnerPackage().equals(ownerPackage)) { 20097 resolver.removeFilter(filter); 20098 } 20099 } 20100 scheduleWritePackageRestrictionsLocked(sourceUserId); 20101 } 20102 } 20103 20104 // Enforcing that callingUid is owning pkg on userId 20105 private void enforceOwnerRights(String pkg, int callingUid) { 20106 // The system owns everything. 20107 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 20108 return; 20109 } 20110 final int callingUserId = UserHandle.getUserId(callingUid); 20111 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 20112 if (pi == null) { 20113 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 20114 + callingUserId); 20115 } 20116 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 20117 throw new SecurityException("Calling uid " + callingUid 20118 + " does not own package " + pkg); 20119 } 20120 } 20121 20122 @Override 20123 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 20124 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20125 return null; 20126 } 20127 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 20128 } 20129 20130 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 20131 UserManagerService ums = UserManagerService.getInstance(); 20132 if (ums != null) { 20133 final UserInfo parent = ums.getProfileParent(userId); 20134 final int launcherUid = (parent != null) ? parent.id : userId; 20135 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 20136 if (launcherComponent != null) { 20137 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 20138 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 20139 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 20140 .setPackage(launcherComponent.getPackageName()); 20141 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 20142 } 20143 } 20144 } 20145 20146 /** 20147 * Report the 'Home' activity which is currently set as "always use this one". If non is set 20148 * then reports the most likely home activity or null if there are more than one. 20149 */ 20150 private ComponentName getDefaultHomeActivity(int userId) { 20151 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 20152 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 20153 if (cn != null) { 20154 return cn; 20155 } 20156 20157 // Find the launcher with the highest priority and return that component if there are no 20158 // other home activity with the same priority. 20159 int lastPriority = Integer.MIN_VALUE; 20160 ComponentName lastComponent = null; 20161 final int size = allHomeCandidates.size(); 20162 for (int i = 0; i < size; i++) { 20163 final ResolveInfo ri = allHomeCandidates.get(i); 20164 if (ri.priority > lastPriority) { 20165 lastComponent = ri.activityInfo.getComponentName(); 20166 lastPriority = ri.priority; 20167 } else if (ri.priority == lastPriority) { 20168 // Two components found with same priority. 20169 lastComponent = null; 20170 } 20171 } 20172 return lastComponent; 20173 } 20174 20175 private Intent getHomeIntent() { 20176 Intent intent = new Intent(Intent.ACTION_MAIN); 20177 intent.addCategory(Intent.CATEGORY_HOME); 20178 intent.addCategory(Intent.CATEGORY_DEFAULT); 20179 return intent; 20180 } 20181 20182 private IntentFilter getHomeFilter() { 20183 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 20184 filter.addCategory(Intent.CATEGORY_HOME); 20185 filter.addCategory(Intent.CATEGORY_DEFAULT); 20186 return filter; 20187 } 20188 20189 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20190 int userId) { 20191 Intent intent = getHomeIntent(); 20192 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 20193 PackageManager.GET_META_DATA, userId); 20194 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 20195 true, false, false, userId); 20196 20197 allHomeCandidates.clear(); 20198 if (list != null) { 20199 for (ResolveInfo ri : list) { 20200 allHomeCandidates.add(ri); 20201 } 20202 } 20203 return (preferred == null || preferred.activityInfo == null) 20204 ? null 20205 : new ComponentName(preferred.activityInfo.packageName, 20206 preferred.activityInfo.name); 20207 } 20208 20209 @Override 20210 public void setHomeActivity(ComponentName comp, int userId) { 20211 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20212 return; 20213 } 20214 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 20215 getHomeActivitiesAsUser(homeActivities, userId); 20216 20217 boolean found = false; 20218 20219 final int size = homeActivities.size(); 20220 final ComponentName[] set = new ComponentName[size]; 20221 for (int i = 0; i < size; i++) { 20222 final ResolveInfo candidate = homeActivities.get(i); 20223 final ActivityInfo info = candidate.activityInfo; 20224 final ComponentName activityName = new ComponentName(info.packageName, info.name); 20225 set[i] = activityName; 20226 if (!found && activityName.equals(comp)) { 20227 found = true; 20228 } 20229 } 20230 if (!found) { 20231 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 20232 + userId); 20233 } 20234 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 20235 set, comp, userId); 20236 } 20237 20238 private @Nullable String getSetupWizardPackageName() { 20239 final Intent intent = new Intent(Intent.ACTION_MAIN); 20240 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 20241 20242 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20243 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20244 | MATCH_DISABLED_COMPONENTS, 20245 UserHandle.myUserId()); 20246 if (matches.size() == 1) { 20247 return matches.get(0).getComponentInfo().packageName; 20248 } else { 20249 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 20250 + ": matches=" + matches); 20251 return null; 20252 } 20253 } 20254 20255 private @Nullable String getStorageManagerPackageName() { 20256 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 20257 20258 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20259 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20260 | MATCH_DISABLED_COMPONENTS, 20261 UserHandle.myUserId()); 20262 if (matches.size() == 1) { 20263 return matches.get(0).getComponentInfo().packageName; 20264 } else { 20265 Slog.e(TAG, "There should probably be exactly one storage manager; found " 20266 + matches.size() + ": matches=" + matches); 20267 return null; 20268 } 20269 } 20270 20271 @Override 20272 public void setApplicationEnabledSetting(String appPackageName, 20273 int newState, int flags, int userId, String callingPackage) { 20274 if (!sUserManager.exists(userId)) return; 20275 if (callingPackage == null) { 20276 callingPackage = Integer.toString(Binder.getCallingUid()); 20277 } 20278 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 20279 } 20280 20281 @Override 20282 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 20283 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 20284 synchronized (mPackages) { 20285 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 20286 if (pkgSetting != null) { 20287 pkgSetting.setUpdateAvailable(updateAvailable); 20288 } 20289 } 20290 } 20291 20292 @Override 20293 public void setComponentEnabledSetting(ComponentName componentName, 20294 int newState, int flags, int userId) { 20295 if (!sUserManager.exists(userId)) return; 20296 setEnabledSetting(componentName.getPackageName(), 20297 componentName.getClassName(), newState, flags, userId, null); 20298 } 20299 20300 private void setEnabledSetting(final String packageName, String className, int newState, 20301 final int flags, int userId, String callingPackage) { 20302 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 20303 || newState == COMPONENT_ENABLED_STATE_ENABLED 20304 || newState == COMPONENT_ENABLED_STATE_DISABLED 20305 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20306 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 20307 throw new IllegalArgumentException("Invalid new component state: " 20308 + newState); 20309 } 20310 PackageSetting pkgSetting; 20311 final int callingUid = Binder.getCallingUid(); 20312 final int permission; 20313 if (callingUid == Process.SYSTEM_UID) { 20314 permission = PackageManager.PERMISSION_GRANTED; 20315 } else { 20316 permission = mContext.checkCallingOrSelfPermission( 20317 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20318 } 20319 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20320 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 20321 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20322 boolean sendNow = false; 20323 boolean isApp = (className == null); 20324 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 20325 String componentName = isApp ? packageName : className; 20326 int packageUid = -1; 20327 ArrayList<String> components; 20328 20329 // reader 20330 synchronized (mPackages) { 20331 pkgSetting = mSettings.mPackages.get(packageName); 20332 if (pkgSetting == null) { 20333 if (!isCallerInstantApp) { 20334 if (className == null) { 20335 throw new IllegalArgumentException("Unknown package: " + packageName); 20336 } 20337 throw new IllegalArgumentException( 20338 "Unknown component: " + packageName + "/" + className); 20339 } else { 20340 // throw SecurityException to prevent leaking package information 20341 throw new SecurityException( 20342 "Attempt to change component state; " 20343 + "pid=" + Binder.getCallingPid() 20344 + ", uid=" + callingUid 20345 + (className == null 20346 ? ", package=" + packageName 20347 : ", component=" + packageName + "/" + className)); 20348 } 20349 } 20350 } 20351 20352 // Limit who can change which apps 20353 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 20354 // Don't allow apps that don't have permission to modify other apps 20355 if (!allowedByPermission 20356 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 20357 throw new SecurityException( 20358 "Attempt to change component state; " 20359 + "pid=" + Binder.getCallingPid() 20360 + ", uid=" + callingUid 20361 + (className == null 20362 ? ", package=" + packageName 20363 : ", component=" + packageName + "/" + className)); 20364 } 20365 // Don't allow changing protected packages. 20366 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 20367 throw new SecurityException("Cannot disable a protected package: " + packageName); 20368 } 20369 } 20370 20371 synchronized (mPackages) { 20372 if (callingUid == Process.SHELL_UID 20373 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 20374 // Shell can only change whole packages between ENABLED and DISABLED_USER states 20375 // unless it is a test package. 20376 int oldState = pkgSetting.getEnabled(userId); 20377 if (className == null 20378 && 20379 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 20380 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 20381 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 20382 && 20383 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20384 || newState == COMPONENT_ENABLED_STATE_DEFAULT 20385 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 20386 // ok 20387 } else { 20388 throw new SecurityException( 20389 "Shell cannot change component state for " + packageName + "/" 20390 + className + " to " + newState); 20391 } 20392 } 20393 } 20394 if (className == null) { 20395 // We're dealing with an application/package level state change 20396 synchronized (mPackages) { 20397 if (pkgSetting.getEnabled(userId) == newState) { 20398 // Nothing to do 20399 return; 20400 } 20401 } 20402 // If we're enabling a system stub, there's a little more work to do. 20403 // Prior to enabling the package, we need to decompress the APK(s) to the 20404 // data partition and then replace the version on the system partition. 20405 final PackageParser.Package deletedPkg = pkgSetting.pkg; 20406 final boolean isSystemStub = deletedPkg.isStub 20407 && deletedPkg.isSystem(); 20408 if (isSystemStub 20409 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20410 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 20411 final File codePath = decompressPackage(deletedPkg); 20412 if (codePath == null) { 20413 Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name); 20414 return; 20415 } 20416 // TODO remove direct parsing of the package object during internal cleanup 20417 // of scan package 20418 // We need to call parse directly here for no other reason than we need 20419 // the new package in order to disable the old one [we use the information 20420 // for some internal optimization to optionally create a new package setting 20421 // object on replace]. However, we can't get the package from the scan 20422 // because the scan modifies live structures and we need to remove the 20423 // old [system] package from the system before a scan can be attempted. 20424 // Once scan is indempotent we can remove this parse and use the package 20425 // object we scanned, prior to adding it to package settings. 20426 final PackageParser pp = new PackageParser(); 20427 pp.setSeparateProcesses(mSeparateProcesses); 20428 pp.setDisplayMetrics(mMetrics); 20429 pp.setCallback(mPackageParserCallback); 20430 final PackageParser.Package tmpPkg; 20431 try { 20432 final @ParseFlags int parseFlags = mDefParseFlags 20433 | PackageParser.PARSE_MUST_BE_APK 20434 | PackageParser.PARSE_IS_SYSTEM_DIR; 20435 tmpPkg = pp.parsePackage(codePath, parseFlags); 20436 } catch (PackageParserException e) { 20437 Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e); 20438 return; 20439 } 20440 synchronized (mInstallLock) { 20441 // Disable the stub and remove any package entries 20442 removePackageLI(deletedPkg, true); 20443 synchronized (mPackages) { 20444 disableSystemPackageLPw(deletedPkg, tmpPkg); 20445 } 20446 final PackageParser.Package pkg; 20447 try (PackageFreezer freezer = 20448 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20449 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 20450 | PackageParser.PARSE_ENFORCE_CODE; 20451 pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 20452 0 /*currentTime*/, null /*user*/); 20453 prepareAppDataAfterInstallLIF(pkg); 20454 synchronized (mPackages) { 20455 try { 20456 updateSharedLibrariesLPr(pkg, null); 20457 } catch (PackageManagerException e) { 20458 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 20459 } 20460 mPermissionManager.updatePermissions( 20461 pkg.packageName, pkg, true, mPackages.values(), 20462 mPermissionCallback); 20463 mSettings.writeLPr(); 20464 } 20465 } catch (PackageManagerException e) { 20466 // Whoops! Something went wrong; try to roll back to the stub 20467 Slog.w(TAG, "Failed to install compressed system package:" 20468 + pkgSetting.name, e); 20469 // Remove the failed install 20470 removeCodePathLI(codePath); 20471 20472 // Install the system package 20473 try (PackageFreezer freezer = 20474 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20475 synchronized (mPackages) { 20476 // NOTE: The system package always needs to be enabled; even 20477 // if it's for a compressed stub. If we don't, installing the 20478 // system package fails during scan [scanning checks the disabled 20479 // packages]. We will reverse this later, after we've "installed" 20480 // the stub. 20481 // This leaves us in a fragile state; the stub should never be 20482 // enabled, so, cross your fingers and hope nothing goes wrong 20483 // until we can disable the package later. 20484 enableSystemPackageLPw(deletedPkg); 20485 } 20486 installPackageFromSystemLIF(deletedPkg.codePath, 20487 false /*isPrivileged*/, null /*allUserHandles*/, 20488 null /*origUserHandles*/, null /*origPermissionsState*/, 20489 true /*writeSettings*/); 20490 } catch (PackageManagerException pme) { 20491 Slog.w(TAG, "Failed to restore system package:" 20492 + deletedPkg.packageName, pme); 20493 } finally { 20494 synchronized (mPackages) { 20495 mSettings.disableSystemPackageLPw( 20496 deletedPkg.packageName, true /*replaced*/); 20497 mSettings.writeLPr(); 20498 } 20499 } 20500 return; 20501 } 20502 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE 20503 | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20504 mDexManager.notifyPackageUpdated(pkg.packageName, 20505 pkg.baseCodePath, pkg.splitCodePaths); 20506 } 20507 } 20508 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20509 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20510 // Don't care about who enables an app. 20511 callingPackage = null; 20512 } 20513 synchronized (mPackages) { 20514 pkgSetting.setEnabled(newState, userId, callingPackage); 20515 } 20516 } else { 20517 synchronized (mPackages) { 20518 // We're dealing with a component level state change 20519 // First, verify that this is a valid class name. 20520 PackageParser.Package pkg = pkgSetting.pkg; 20521 if (pkg == null || !pkg.hasComponentClassName(className)) { 20522 if (pkg != null && 20523 pkg.applicationInfo.targetSdkVersion >= 20524 Build.VERSION_CODES.JELLY_BEAN) { 20525 throw new IllegalArgumentException("Component class " + className 20526 + " does not exist in " + packageName); 20527 } else { 20528 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20529 + className + " does not exist in " + packageName); 20530 } 20531 } 20532 switch (newState) { 20533 case COMPONENT_ENABLED_STATE_ENABLED: 20534 if (!pkgSetting.enableComponentLPw(className, userId)) { 20535 return; 20536 } 20537 break; 20538 case COMPONENT_ENABLED_STATE_DISABLED: 20539 if (!pkgSetting.disableComponentLPw(className, userId)) { 20540 return; 20541 } 20542 break; 20543 case COMPONENT_ENABLED_STATE_DEFAULT: 20544 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20545 return; 20546 } 20547 break; 20548 default: 20549 Slog.e(TAG, "Invalid new component state: " + newState); 20550 return; 20551 } 20552 } 20553 } 20554 synchronized (mPackages) { 20555 scheduleWritePackageRestrictionsLocked(userId); 20556 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 20557 final long callingId = Binder.clearCallingIdentity(); 20558 try { 20559 updateInstantAppInstallerLocked(packageName); 20560 } finally { 20561 Binder.restoreCallingIdentity(callingId); 20562 } 20563 components = mPendingBroadcasts.get(userId, packageName); 20564 final boolean newPackage = components == null; 20565 if (newPackage) { 20566 components = new ArrayList<String>(); 20567 } 20568 if (!components.contains(componentName)) { 20569 components.add(componentName); 20570 } 20571 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20572 sendNow = true; 20573 // Purge entry from pending broadcast list if another one exists already 20574 // since we are sending one right away. 20575 mPendingBroadcasts.remove(userId, packageName); 20576 } else { 20577 if (newPackage) { 20578 mPendingBroadcasts.put(userId, packageName, components); 20579 } 20580 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20581 // Schedule a message 20582 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20583 } 20584 } 20585 } 20586 20587 long callingId = Binder.clearCallingIdentity(); 20588 try { 20589 if (sendNow) { 20590 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20591 sendPackageChangedBroadcast(packageName, 20592 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20593 } 20594 } finally { 20595 Binder.restoreCallingIdentity(callingId); 20596 } 20597 } 20598 20599 @Override 20600 public void flushPackageRestrictionsAsUser(int userId) { 20601 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20602 return; 20603 } 20604 if (!sUserManager.exists(userId)) { 20605 return; 20606 } 20607 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20608 false /* checkShell */, "flushPackageRestrictions"); 20609 synchronized (mPackages) { 20610 mSettings.writePackageRestrictionsLPr(userId); 20611 mDirtyUsers.remove(userId); 20612 if (mDirtyUsers.isEmpty()) { 20613 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20614 } 20615 } 20616 } 20617 20618 private void sendPackageChangedBroadcast(String packageName, 20619 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20620 if (DEBUG_INSTALL) 20621 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20622 + componentNames); 20623 Bundle extras = new Bundle(4); 20624 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20625 String nameList[] = new String[componentNames.size()]; 20626 componentNames.toArray(nameList); 20627 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20628 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20629 extras.putInt(Intent.EXTRA_UID, packageUid); 20630 // If this is not reporting a change of the overall package, then only send it 20631 // to registered receivers. We don't want to launch a swath of apps for every 20632 // little component state change. 20633 final int flags = !componentNames.contains(packageName) 20634 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20635 final int userId = UserHandle.getUserId(packageUid); 20636 final boolean isInstantApp = isInstantApp(packageName, userId); 20637 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 20638 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 20639 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20640 userIds, instantUserIds); 20641 } 20642 20643 @Override 20644 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20645 if (!sUserManager.exists(userId)) return; 20646 final int callingUid = Binder.getCallingUid(); 20647 if (getInstantAppPackageName(callingUid) != null) { 20648 return; 20649 } 20650 final int permission = mContext.checkCallingOrSelfPermission( 20651 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20652 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20653 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20654 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20655 // writer 20656 synchronized (mPackages) { 20657 final PackageSetting ps = mSettings.mPackages.get(packageName); 20658 if (!filterAppAccessLPr(ps, callingUid, userId) 20659 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20660 allowedByPermission, callingUid, userId)) { 20661 scheduleWritePackageRestrictionsLocked(userId); 20662 } 20663 } 20664 } 20665 20666 @Override 20667 public String getInstallerPackageName(String packageName) { 20668 final int callingUid = Binder.getCallingUid(); 20669 if (getInstantAppPackageName(callingUid) != null) { 20670 return null; 20671 } 20672 // reader 20673 synchronized (mPackages) { 20674 final PackageSetting ps = mSettings.mPackages.get(packageName); 20675 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20676 return null; 20677 } 20678 return mSettings.getInstallerPackageNameLPr(packageName); 20679 } 20680 } 20681 20682 public boolean isOrphaned(String packageName) { 20683 // reader 20684 synchronized (mPackages) { 20685 return mSettings.isOrphaned(packageName); 20686 } 20687 } 20688 20689 @Override 20690 public int getApplicationEnabledSetting(String packageName, int userId) { 20691 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20692 int callingUid = Binder.getCallingUid(); 20693 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20694 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20695 // reader 20696 synchronized (mPackages) { 20697 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 20698 return COMPONENT_ENABLED_STATE_DISABLED; 20699 } 20700 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20701 } 20702 } 20703 20704 @Override 20705 public int getComponentEnabledSetting(ComponentName component, int userId) { 20706 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20707 int callingUid = Binder.getCallingUid(); 20708 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20709 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 20710 synchronized (mPackages) { 20711 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 20712 component, TYPE_UNKNOWN, userId)) { 20713 return COMPONENT_ENABLED_STATE_DISABLED; 20714 } 20715 return mSettings.getComponentEnabledSettingLPr(component, userId); 20716 } 20717 } 20718 20719 @Override 20720 public void enterSafeMode() { 20721 enforceSystemOrRoot("Only the system can request entering safe mode"); 20722 20723 if (!mSystemReady) { 20724 mSafeMode = true; 20725 } 20726 } 20727 20728 @Override 20729 public void systemReady() { 20730 enforceSystemOrRoot("Only the system can claim the system is ready"); 20731 20732 mSystemReady = true; 20733 final ContentResolver resolver = mContext.getContentResolver(); 20734 ContentObserver co = new ContentObserver(mHandler) { 20735 @Override 20736 public void onChange(boolean selfChange) { 20737 mEphemeralAppsDisabled = 20738 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20739 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20740 } 20741 }; 20742 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20743 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20744 false, co, UserHandle.USER_SYSTEM); 20745 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20746 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20747 co.onChange(true); 20748 20749 // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to 20750 // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once 20751 // it is done. 20752 ContentObserver privAppOobObserver = new ContentObserver(mHandler) { 20753 @Override 20754 public void onChange(boolean selfChange) { 20755 int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0); 20756 SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, 20757 oobEnabled == 1 ? "true" : "false"); 20758 } 20759 }; 20760 mContext.getContentResolver().registerContentObserver( 20761 Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver, 20762 UserHandle.USER_SYSTEM); 20763 // At boot, restore the value from the setting, which persists across reboot. 20764 privAppOobObserver.onChange(true); 20765 20766 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20767 // disabled after already being started. 20768 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20769 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20770 20771 // Read the compatibilty setting when the system is ready. 20772 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20773 mContext.getContentResolver(), 20774 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20775 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20776 if (DEBUG_SETTINGS) { 20777 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20778 } 20779 20780 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20781 20782 synchronized (mPackages) { 20783 // Verify that all of the preferred activity components actually 20784 // exist. It is possible for applications to be updated and at 20785 // that point remove a previously declared activity component that 20786 // had been set as a preferred activity. We try to clean this up 20787 // the next time we encounter that preferred activity, but it is 20788 // possible for the user flow to never be able to return to that 20789 // situation so here we do a sanity check to make sure we haven't 20790 // left any junk around. 20791 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20792 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20793 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20794 removed.clear(); 20795 for (PreferredActivity pa : pir.filterSet()) { 20796 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20797 removed.add(pa); 20798 } 20799 } 20800 if (removed.size() > 0) { 20801 for (int r=0; r<removed.size(); r++) { 20802 PreferredActivity pa = removed.get(r); 20803 Slog.w(TAG, "Removing dangling preferred activity: " 20804 + pa.mPref.mComponent); 20805 pir.removeFilter(pa); 20806 } 20807 mSettings.writePackageRestrictionsLPr( 20808 mSettings.mPreferredActivities.keyAt(i)); 20809 } 20810 } 20811 20812 for (int userId : UserManagerService.getInstance().getUserIds()) { 20813 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20814 grantPermissionsUserIds = ArrayUtils.appendInt( 20815 grantPermissionsUserIds, userId); 20816 } 20817 } 20818 } 20819 sUserManager.systemReady(); 20820 // If we upgraded grant all default permissions before kicking off. 20821 for (int userId : grantPermissionsUserIds) { 20822 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20823 } 20824 20825 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20826 // If we did not grant default permissions, we preload from this the 20827 // default permission exceptions lazily to ensure we don't hit the 20828 // disk on a new user creation. 20829 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20830 } 20831 20832 // Now that we've scanned all packages, and granted any default 20833 // permissions, ensure permissions are updated. Beware of dragons if you 20834 // try optimizing this. 20835 synchronized (mPackages) { 20836 mPermissionManager.updateAllPermissions( 20837 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 20838 mPermissionCallback); 20839 } 20840 20841 // Kick off any messages waiting for system ready 20842 if (mPostSystemReadyMessages != null) { 20843 for (Message msg : mPostSystemReadyMessages) { 20844 msg.sendToTarget(); 20845 } 20846 mPostSystemReadyMessages = null; 20847 } 20848 20849 // Watch for external volumes that come and go over time 20850 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20851 storage.registerListener(mStorageListener); 20852 20853 mInstallerService.systemReady(); 20854 mPackageDexOptimizer.systemReady(); 20855 20856 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20857 StorageManagerInternal.class); 20858 StorageManagerInternal.addExternalStoragePolicy( 20859 new StorageManagerInternal.ExternalStorageMountPolicy() { 20860 @Override 20861 public int getMountMode(int uid, String packageName) { 20862 if (Process.isIsolated(uid)) { 20863 return Zygote.MOUNT_EXTERNAL_NONE; 20864 } 20865 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20866 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20867 } 20868 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20869 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20870 } 20871 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20872 return Zygote.MOUNT_EXTERNAL_READ; 20873 } 20874 return Zygote.MOUNT_EXTERNAL_WRITE; 20875 } 20876 20877 @Override 20878 public boolean hasExternalStorage(int uid, String packageName) { 20879 return true; 20880 } 20881 }); 20882 20883 // Now that we're mostly running, clean up stale users and apps 20884 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20885 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20886 20887 mPermissionManager.systemReady(); 20888 } 20889 20890 public void waitForAppDataPrepared() { 20891 if (mPrepareAppDataFuture == null) { 20892 return; 20893 } 20894 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20895 mPrepareAppDataFuture = null; 20896 } 20897 20898 @Override 20899 public boolean isSafeMode() { 20900 // allow instant applications 20901 return mSafeMode; 20902 } 20903 20904 @Override 20905 public boolean hasSystemUidErrors() { 20906 // allow instant applications 20907 return mHasSystemUidErrors; 20908 } 20909 20910 static String arrayToString(int[] array) { 20911 StringBuffer buf = new StringBuffer(128); 20912 buf.append('['); 20913 if (array != null) { 20914 for (int i=0; i<array.length; i++) { 20915 if (i > 0) buf.append(", "); 20916 buf.append(array[i]); 20917 } 20918 } 20919 buf.append(']'); 20920 return buf.toString(); 20921 } 20922 20923 @Override 20924 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20925 FileDescriptor err, String[] args, ShellCallback callback, 20926 ResultReceiver resultReceiver) { 20927 (new PackageManagerShellCommand(this)).exec( 20928 this, in, out, err, args, callback, resultReceiver); 20929 } 20930 20931 @Override 20932 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20933 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20934 20935 DumpState dumpState = new DumpState(); 20936 boolean fullPreferred = false; 20937 boolean checkin = false; 20938 20939 String packageName = null; 20940 ArraySet<String> permissionNames = null; 20941 20942 int opti = 0; 20943 while (opti < args.length) { 20944 String opt = args[opti]; 20945 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20946 break; 20947 } 20948 opti++; 20949 20950 if ("-a".equals(opt)) { 20951 // Right now we only know how to print all. 20952 } else if ("-h".equals(opt)) { 20953 pw.println("Package manager dump options:"); 20954 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20955 pw.println(" --checkin: dump for a checkin"); 20956 pw.println(" -f: print details of intent filters"); 20957 pw.println(" -h: print this help"); 20958 pw.println(" cmd may be one of:"); 20959 pw.println(" l[ibraries]: list known shared libraries"); 20960 pw.println(" f[eatures]: list device features"); 20961 pw.println(" k[eysets]: print known keysets"); 20962 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20963 pw.println(" perm[issions]: dump permissions"); 20964 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20965 pw.println(" pref[erred]: print preferred package settings"); 20966 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20967 pw.println(" prov[iders]: dump content providers"); 20968 pw.println(" p[ackages]: dump installed packages"); 20969 pw.println(" s[hared-users]: dump shared user IDs"); 20970 pw.println(" m[essages]: print collected runtime messages"); 20971 pw.println(" v[erifiers]: print package verifier info"); 20972 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20973 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20974 pw.println(" version: print database version info"); 20975 pw.println(" write: write current settings now"); 20976 pw.println(" installs: details about install sessions"); 20977 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20978 pw.println(" dexopt: dump dexopt state"); 20979 pw.println(" compiler-stats: dump compiler statistics"); 20980 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20981 pw.println(" service-permissions: dump permissions required by services"); 20982 pw.println(" <package.name>: info about given package"); 20983 return; 20984 } else if ("--checkin".equals(opt)) { 20985 checkin = true; 20986 } else if ("-f".equals(opt)) { 20987 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20988 } else if ("--proto".equals(opt)) { 20989 dumpProto(fd); 20990 return; 20991 } else { 20992 pw.println("Unknown argument: " + opt + "; use -h for help"); 20993 } 20994 } 20995 20996 // Is the caller requesting to dump a particular piece of data? 20997 if (opti < args.length) { 20998 String cmd = args[opti]; 20999 opti++; 21000 // Is this a package name? 21001 if ("android".equals(cmd) || cmd.contains(".")) { 21002 packageName = cmd; 21003 // When dumping a single package, we always dump all of its 21004 // filter information since the amount of data will be reasonable. 21005 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21006 } else if ("check-permission".equals(cmd)) { 21007 if (opti >= args.length) { 21008 pw.println("Error: check-permission missing permission argument"); 21009 return; 21010 } 21011 String perm = args[opti]; 21012 opti++; 21013 if (opti >= args.length) { 21014 pw.println("Error: check-permission missing package argument"); 21015 return; 21016 } 21017 21018 String pkg = args[opti]; 21019 opti++; 21020 int user = UserHandle.getUserId(Binder.getCallingUid()); 21021 if (opti < args.length) { 21022 try { 21023 user = Integer.parseInt(args[opti]); 21024 } catch (NumberFormatException e) { 21025 pw.println("Error: check-permission user argument is not a number: " 21026 + args[opti]); 21027 return; 21028 } 21029 } 21030 21031 // Normalize package name to handle renamed packages and static libs 21032 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 21033 21034 pw.println(checkPermission(perm, pkg, user)); 21035 return; 21036 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 21037 dumpState.setDump(DumpState.DUMP_LIBS); 21038 } else if ("f".equals(cmd) || "features".equals(cmd)) { 21039 dumpState.setDump(DumpState.DUMP_FEATURES); 21040 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 21041 if (opti >= args.length) { 21042 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 21043 | DumpState.DUMP_SERVICE_RESOLVERS 21044 | DumpState.DUMP_RECEIVER_RESOLVERS 21045 | DumpState.DUMP_CONTENT_RESOLVERS); 21046 } else { 21047 while (opti < args.length) { 21048 String name = args[opti]; 21049 if ("a".equals(name) || "activity".equals(name)) { 21050 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 21051 } else if ("s".equals(name) || "service".equals(name)) { 21052 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 21053 } else if ("r".equals(name) || "receiver".equals(name)) { 21054 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 21055 } else if ("c".equals(name) || "content".equals(name)) { 21056 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 21057 } else { 21058 pw.println("Error: unknown resolver table type: " + name); 21059 return; 21060 } 21061 opti++; 21062 } 21063 } 21064 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 21065 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 21066 } else if ("permission".equals(cmd)) { 21067 if (opti >= args.length) { 21068 pw.println("Error: permission requires permission name"); 21069 return; 21070 } 21071 permissionNames = new ArraySet<>(); 21072 while (opti < args.length) { 21073 permissionNames.add(args[opti]); 21074 opti++; 21075 } 21076 dumpState.setDump(DumpState.DUMP_PERMISSIONS 21077 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 21078 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 21079 dumpState.setDump(DumpState.DUMP_PREFERRED); 21080 } else if ("preferred-xml".equals(cmd)) { 21081 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 21082 if (opti < args.length && "--full".equals(args[opti])) { 21083 fullPreferred = true; 21084 opti++; 21085 } 21086 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 21087 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 21088 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 21089 dumpState.setDump(DumpState.DUMP_PACKAGES); 21090 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 21091 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 21092 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 21093 dumpState.setDump(DumpState.DUMP_PROVIDERS); 21094 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 21095 dumpState.setDump(DumpState.DUMP_MESSAGES); 21096 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 21097 dumpState.setDump(DumpState.DUMP_VERIFIERS); 21098 } else if ("i".equals(cmd) || "ifv".equals(cmd) 21099 || "intent-filter-verifiers".equals(cmd)) { 21100 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 21101 } else if ("version".equals(cmd)) { 21102 dumpState.setDump(DumpState.DUMP_VERSION); 21103 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 21104 dumpState.setDump(DumpState.DUMP_KEYSETS); 21105 } else if ("installs".equals(cmd)) { 21106 dumpState.setDump(DumpState.DUMP_INSTALLS); 21107 } else if ("frozen".equals(cmd)) { 21108 dumpState.setDump(DumpState.DUMP_FROZEN); 21109 } else if ("volumes".equals(cmd)) { 21110 dumpState.setDump(DumpState.DUMP_VOLUMES); 21111 } else if ("dexopt".equals(cmd)) { 21112 dumpState.setDump(DumpState.DUMP_DEXOPT); 21113 } else if ("compiler-stats".equals(cmd)) { 21114 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 21115 } else if ("changes".equals(cmd)) { 21116 dumpState.setDump(DumpState.DUMP_CHANGES); 21117 } else if ("service-permissions".equals(cmd)) { 21118 dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS); 21119 } else if ("write".equals(cmd)) { 21120 synchronized (mPackages) { 21121 mSettings.writeLPr(); 21122 pw.println("Settings written."); 21123 return; 21124 } 21125 } 21126 } 21127 21128 if (checkin) { 21129 pw.println("vers,1"); 21130 } 21131 21132 // reader 21133 synchronized (mPackages) { 21134 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 21135 if (!checkin) { 21136 if (dumpState.onTitlePrinted()) 21137 pw.println(); 21138 pw.println("Database versions:"); 21139 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 21140 } 21141 } 21142 21143 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 21144 if (!checkin) { 21145 if (dumpState.onTitlePrinted()) 21146 pw.println(); 21147 pw.println("Verifiers:"); 21148 pw.print(" Required: "); 21149 pw.print(mRequiredVerifierPackage); 21150 pw.print(" (uid="); 21151 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21152 UserHandle.USER_SYSTEM)); 21153 pw.println(")"); 21154 } else if (mRequiredVerifierPackage != null) { 21155 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 21156 pw.print(","); 21157 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21158 UserHandle.USER_SYSTEM)); 21159 } 21160 } 21161 21162 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 21163 packageName == null) { 21164 if (mIntentFilterVerifierComponent != null) { 21165 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21166 if (!checkin) { 21167 if (dumpState.onTitlePrinted()) 21168 pw.println(); 21169 pw.println("Intent Filter Verifier:"); 21170 pw.print(" Using: "); 21171 pw.print(verifierPackageName); 21172 pw.print(" (uid="); 21173 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21174 UserHandle.USER_SYSTEM)); 21175 pw.println(")"); 21176 } else if (verifierPackageName != null) { 21177 pw.print("ifv,"); pw.print(verifierPackageName); 21178 pw.print(","); 21179 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21180 UserHandle.USER_SYSTEM)); 21181 } 21182 } else { 21183 pw.println(); 21184 pw.println("No Intent Filter Verifier available!"); 21185 } 21186 } 21187 21188 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 21189 boolean printedHeader = false; 21190 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 21191 while (it.hasNext()) { 21192 String libName = it.next(); 21193 LongSparseArray<SharedLibraryEntry> versionedLib 21194 = mSharedLibraries.get(libName); 21195 if (versionedLib == null) { 21196 continue; 21197 } 21198 final int versionCount = versionedLib.size(); 21199 for (int i = 0; i < versionCount; i++) { 21200 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 21201 if (!checkin) { 21202 if (!printedHeader) { 21203 if (dumpState.onTitlePrinted()) 21204 pw.println(); 21205 pw.println("Libraries:"); 21206 printedHeader = true; 21207 } 21208 pw.print(" "); 21209 } else { 21210 pw.print("lib,"); 21211 } 21212 pw.print(libEntry.info.getName()); 21213 if (libEntry.info.isStatic()) { 21214 pw.print(" version=" + libEntry.info.getLongVersion()); 21215 } 21216 if (!checkin) { 21217 pw.print(" -> "); 21218 } 21219 if (libEntry.path != null) { 21220 pw.print(" (jar) "); 21221 pw.print(libEntry.path); 21222 } else { 21223 pw.print(" (apk) "); 21224 pw.print(libEntry.apk); 21225 } 21226 pw.println(); 21227 } 21228 } 21229 } 21230 21231 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 21232 if (dumpState.onTitlePrinted()) 21233 pw.println(); 21234 if (!checkin) { 21235 pw.println("Features:"); 21236 } 21237 21238 synchronized (mAvailableFeatures) { 21239 for (FeatureInfo feat : mAvailableFeatures.values()) { 21240 if (checkin) { 21241 pw.print("feat,"); 21242 pw.print(feat.name); 21243 pw.print(","); 21244 pw.println(feat.version); 21245 } else { 21246 pw.print(" "); 21247 pw.print(feat.name); 21248 if (feat.version > 0) { 21249 pw.print(" version="); 21250 pw.print(feat.version); 21251 } 21252 pw.println(); 21253 } 21254 } 21255 } 21256 } 21257 21258 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 21259 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 21260 : "Activity Resolver Table:", " ", packageName, 21261 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21262 dumpState.setTitlePrinted(true); 21263 } 21264 } 21265 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 21266 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 21267 : "Receiver Resolver Table:", " ", packageName, 21268 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21269 dumpState.setTitlePrinted(true); 21270 } 21271 } 21272 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 21273 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 21274 : "Service Resolver Table:", " ", packageName, 21275 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21276 dumpState.setTitlePrinted(true); 21277 } 21278 } 21279 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 21280 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 21281 : "Provider Resolver Table:", " ", packageName, 21282 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21283 dumpState.setTitlePrinted(true); 21284 } 21285 } 21286 21287 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 21288 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21289 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21290 int user = mSettings.mPreferredActivities.keyAt(i); 21291 if (pir.dump(pw, 21292 dumpState.getTitlePrinted() 21293 ? "\nPreferred Activities User " + user + ":" 21294 : "Preferred Activities User " + user + ":", " ", 21295 packageName, true, false)) { 21296 dumpState.setTitlePrinted(true); 21297 } 21298 } 21299 } 21300 21301 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 21302 pw.flush(); 21303 FileOutputStream fout = new FileOutputStream(fd); 21304 BufferedOutputStream str = new BufferedOutputStream(fout); 21305 XmlSerializer serializer = new FastXmlSerializer(); 21306 try { 21307 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 21308 serializer.startDocument(null, true); 21309 serializer.setFeature( 21310 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 21311 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 21312 serializer.endDocument(); 21313 serializer.flush(); 21314 } catch (IllegalArgumentException e) { 21315 pw.println("Failed writing: " + e); 21316 } catch (IllegalStateException e) { 21317 pw.println("Failed writing: " + e); 21318 } catch (IOException e) { 21319 pw.println("Failed writing: " + e); 21320 } 21321 } 21322 21323 if (!checkin 21324 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 21325 && packageName == null) { 21326 pw.println(); 21327 int count = mSettings.mPackages.size(); 21328 if (count == 0) { 21329 pw.println("No applications!"); 21330 pw.println(); 21331 } else { 21332 final String prefix = " "; 21333 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 21334 if (allPackageSettings.size() == 0) { 21335 pw.println("No domain preferred apps!"); 21336 pw.println(); 21337 } else { 21338 pw.println("App verification status:"); 21339 pw.println(); 21340 count = 0; 21341 for (PackageSetting ps : allPackageSettings) { 21342 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 21343 if (ivi == null || ivi.getPackageName() == null) continue; 21344 pw.println(prefix + "Package: " + ivi.getPackageName()); 21345 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 21346 pw.println(prefix + "Status: " + ivi.getStatusString()); 21347 pw.println(); 21348 count++; 21349 } 21350 if (count == 0) { 21351 pw.println(prefix + "No app verification established."); 21352 pw.println(); 21353 } 21354 for (int userId : sUserManager.getUserIds()) { 21355 pw.println("App linkages for user " + userId + ":"); 21356 pw.println(); 21357 count = 0; 21358 for (PackageSetting ps : allPackageSettings) { 21359 final long status = ps.getDomainVerificationStatusForUser(userId); 21360 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 21361 && !DEBUG_DOMAIN_VERIFICATION) { 21362 continue; 21363 } 21364 pw.println(prefix + "Package: " + ps.name); 21365 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 21366 String statusStr = IntentFilterVerificationInfo. 21367 getStatusStringFromValue(status); 21368 pw.println(prefix + "Status: " + statusStr); 21369 pw.println(); 21370 count++; 21371 } 21372 if (count == 0) { 21373 pw.println(prefix + "No configured app linkages."); 21374 pw.println(); 21375 } 21376 } 21377 } 21378 } 21379 } 21380 21381 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 21382 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 21383 } 21384 21385 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 21386 boolean printedSomething = false; 21387 for (PackageParser.Provider p : mProviders.mProviders.values()) { 21388 if (packageName != null && !packageName.equals(p.info.packageName)) { 21389 continue; 21390 } 21391 if (!printedSomething) { 21392 if (dumpState.onTitlePrinted()) 21393 pw.println(); 21394 pw.println("Registered ContentProviders:"); 21395 printedSomething = true; 21396 } 21397 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 21398 pw.print(" "); pw.println(p.toString()); 21399 } 21400 printedSomething = false; 21401 for (Map.Entry<String, PackageParser.Provider> entry : 21402 mProvidersByAuthority.entrySet()) { 21403 PackageParser.Provider p = entry.getValue(); 21404 if (packageName != null && !packageName.equals(p.info.packageName)) { 21405 continue; 21406 } 21407 if (!printedSomething) { 21408 if (dumpState.onTitlePrinted()) 21409 pw.println(); 21410 pw.println("ContentProvider Authorities:"); 21411 printedSomething = true; 21412 } 21413 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 21414 pw.print(" "); pw.println(p.toString()); 21415 if (p.info != null && p.info.applicationInfo != null) { 21416 final String appInfo = p.info.applicationInfo.toString(); 21417 pw.print(" applicationInfo="); pw.println(appInfo); 21418 } 21419 } 21420 } 21421 21422 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 21423 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 21424 } 21425 21426 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 21427 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 21428 } 21429 21430 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 21431 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 21432 } 21433 21434 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 21435 if (dumpState.onTitlePrinted()) pw.println(); 21436 pw.println("Package Changes:"); 21437 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 21438 final int K = mChangedPackages.size(); 21439 for (int i = 0; i < K; i++) { 21440 final SparseArray<String> changes = mChangedPackages.valueAt(i); 21441 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 21442 final int N = changes.size(); 21443 if (N == 0) { 21444 pw.print(" "); pw.println("No packages changed"); 21445 } else { 21446 for (int j = 0; j < N; j++) { 21447 final String pkgName = changes.valueAt(j); 21448 final int sequenceNumber = changes.keyAt(j); 21449 pw.print(" "); 21450 pw.print("seq="); 21451 pw.print(sequenceNumber); 21452 pw.print(", package="); 21453 pw.println(pkgName); 21454 } 21455 } 21456 } 21457 } 21458 21459 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 21460 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 21461 } 21462 21463 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21464 // XXX should handle packageName != null by dumping only install data that 21465 // the given package is involved with. 21466 if (dumpState.onTitlePrinted()) pw.println(); 21467 21468 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21469 ipw.println(); 21470 ipw.println("Frozen packages:"); 21471 ipw.increaseIndent(); 21472 if (mFrozenPackages.size() == 0) { 21473 ipw.println("(none)"); 21474 } else { 21475 for (int i = 0; i < mFrozenPackages.size(); i++) { 21476 ipw.println(mFrozenPackages.valueAt(i)); 21477 } 21478 } 21479 ipw.decreaseIndent(); 21480 } 21481 21482 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 21483 if (dumpState.onTitlePrinted()) pw.println(); 21484 21485 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21486 ipw.println(); 21487 ipw.println("Loaded volumes:"); 21488 ipw.increaseIndent(); 21489 if (mLoadedVolumes.size() == 0) { 21490 ipw.println("(none)"); 21491 } else { 21492 for (int i = 0; i < mLoadedVolumes.size(); i++) { 21493 ipw.println(mLoadedVolumes.valueAt(i)); 21494 } 21495 } 21496 ipw.decreaseIndent(); 21497 } 21498 21499 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS) 21500 && packageName == null) { 21501 if (dumpState.onTitlePrinted()) pw.println(); 21502 pw.println("Service permissions:"); 21503 21504 final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator(); 21505 while (filterIterator.hasNext()) { 21506 final ServiceIntentInfo info = filterIterator.next(); 21507 final ServiceInfo serviceInfo = info.service.info; 21508 final String permission = serviceInfo.permission; 21509 if (permission != null) { 21510 pw.print(" "); 21511 pw.print(serviceInfo.getComponentName().flattenToShortString()); 21512 pw.print(": "); 21513 pw.println(permission); 21514 } 21515 } 21516 } 21517 21518 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21519 if (dumpState.onTitlePrinted()) pw.println(); 21520 dumpDexoptStateLPr(pw, packageName); 21521 } 21522 21523 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21524 if (dumpState.onTitlePrinted()) pw.println(); 21525 dumpCompilerStatsLPr(pw, packageName); 21526 } 21527 21528 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21529 if (dumpState.onTitlePrinted()) pw.println(); 21530 mSettings.dumpReadMessagesLPr(pw, dumpState); 21531 21532 pw.println(); 21533 pw.println("Package warning messages:"); 21534 dumpCriticalInfo(pw, null); 21535 } 21536 21537 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21538 dumpCriticalInfo(pw, "msg,"); 21539 } 21540 } 21541 21542 // PackageInstaller should be called outside of mPackages lock 21543 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21544 // XXX should handle packageName != null by dumping only install data that 21545 // the given package is involved with. 21546 if (dumpState.onTitlePrinted()) pw.println(); 21547 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21548 } 21549 } 21550 21551 private void dumpProto(FileDescriptor fd) { 21552 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21553 21554 synchronized (mPackages) { 21555 final long requiredVerifierPackageToken = 21556 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21557 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21558 proto.write( 21559 PackageServiceDumpProto.PackageShortProto.UID, 21560 getPackageUid( 21561 mRequiredVerifierPackage, 21562 MATCH_DEBUG_TRIAGED_MISSING, 21563 UserHandle.USER_SYSTEM)); 21564 proto.end(requiredVerifierPackageToken); 21565 21566 if (mIntentFilterVerifierComponent != null) { 21567 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21568 final long verifierPackageToken = 21569 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21570 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21571 proto.write( 21572 PackageServiceDumpProto.PackageShortProto.UID, 21573 getPackageUid( 21574 verifierPackageName, 21575 MATCH_DEBUG_TRIAGED_MISSING, 21576 UserHandle.USER_SYSTEM)); 21577 proto.end(verifierPackageToken); 21578 } 21579 21580 dumpSharedLibrariesProto(proto); 21581 dumpFeaturesProto(proto); 21582 mSettings.dumpPackagesProto(proto); 21583 mSettings.dumpSharedUsersProto(proto); 21584 dumpCriticalInfo(proto); 21585 } 21586 proto.flush(); 21587 } 21588 21589 private void dumpFeaturesProto(ProtoOutputStream proto) { 21590 synchronized (mAvailableFeatures) { 21591 final int count = mAvailableFeatures.size(); 21592 for (int i = 0; i < count; i++) { 21593 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES); 21594 } 21595 } 21596 } 21597 21598 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21599 final int count = mSharedLibraries.size(); 21600 for (int i = 0; i < count; i++) { 21601 final String libName = mSharedLibraries.keyAt(i); 21602 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21603 if (versionedLib == null) { 21604 continue; 21605 } 21606 final int versionCount = versionedLib.size(); 21607 for (int j = 0; j < versionCount; j++) { 21608 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21609 final long sharedLibraryToken = 21610 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21611 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21612 final boolean isJar = (libEntry.path != null); 21613 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21614 if (isJar) { 21615 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21616 } else { 21617 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21618 } 21619 proto.end(sharedLibraryToken); 21620 } 21621 } 21622 } 21623 21624 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21625 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21626 ipw.println(); 21627 ipw.println("Dexopt state:"); 21628 ipw.increaseIndent(); 21629 Collection<PackageParser.Package> packages = null; 21630 if (packageName != null) { 21631 PackageParser.Package targetPackage = mPackages.get(packageName); 21632 if (targetPackage != null) { 21633 packages = Collections.singletonList(targetPackage); 21634 } else { 21635 ipw.println("Unable to find package: " + packageName); 21636 return; 21637 } 21638 } else { 21639 packages = mPackages.values(); 21640 } 21641 21642 for (PackageParser.Package pkg : packages) { 21643 ipw.println("[" + pkg.packageName + "]"); 21644 ipw.increaseIndent(); 21645 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 21646 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 21647 ipw.decreaseIndent(); 21648 } 21649 } 21650 21651 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21652 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21653 ipw.println(); 21654 ipw.println("Compiler stats:"); 21655 ipw.increaseIndent(); 21656 Collection<PackageParser.Package> packages = null; 21657 if (packageName != null) { 21658 PackageParser.Package targetPackage = mPackages.get(packageName); 21659 if (targetPackage != null) { 21660 packages = Collections.singletonList(targetPackage); 21661 } else { 21662 ipw.println("Unable to find package: " + packageName); 21663 return; 21664 } 21665 } else { 21666 packages = mPackages.values(); 21667 } 21668 21669 for (PackageParser.Package pkg : packages) { 21670 ipw.println("[" + pkg.packageName + "]"); 21671 ipw.increaseIndent(); 21672 21673 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21674 if (stats == null) { 21675 ipw.println("(No recorded stats)"); 21676 } else { 21677 stats.dump(ipw); 21678 } 21679 ipw.decreaseIndent(); 21680 } 21681 } 21682 21683 private String dumpDomainString(String packageName) { 21684 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21685 .getList(); 21686 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21687 21688 ArraySet<String> result = new ArraySet<>(); 21689 if (iviList.size() > 0) { 21690 for (IntentFilterVerificationInfo ivi : iviList) { 21691 for (String host : ivi.getDomains()) { 21692 result.add(host); 21693 } 21694 } 21695 } 21696 if (filters != null && filters.size() > 0) { 21697 for (IntentFilter filter : filters) { 21698 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21699 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21700 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21701 result.addAll(filter.getHostsList()); 21702 } 21703 } 21704 } 21705 21706 StringBuilder sb = new StringBuilder(result.size() * 16); 21707 for (String domain : result) { 21708 if (sb.length() > 0) sb.append(" "); 21709 sb.append(domain); 21710 } 21711 return sb.toString(); 21712 } 21713 21714 // ------- apps on sdcard specific code ------- 21715 static final boolean DEBUG_SD_INSTALL = false; 21716 21717 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21718 21719 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21720 21721 private boolean mMediaMounted = false; 21722 21723 static String getEncryptKey() { 21724 try { 21725 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21726 SD_ENCRYPTION_KEYSTORE_NAME); 21727 if (sdEncKey == null) { 21728 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21729 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21730 if (sdEncKey == null) { 21731 Slog.e(TAG, "Failed to create encryption keys"); 21732 return null; 21733 } 21734 } 21735 return sdEncKey; 21736 } catch (NoSuchAlgorithmException nsae) { 21737 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21738 return null; 21739 } catch (IOException ioe) { 21740 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21741 return null; 21742 } 21743 } 21744 21745 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21746 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21747 final int size = infos.size(); 21748 final String[] packageNames = new String[size]; 21749 final int[] packageUids = new int[size]; 21750 for (int i = 0; i < size; i++) { 21751 final ApplicationInfo info = infos.get(i); 21752 packageNames[i] = info.packageName; 21753 packageUids[i] = info.uid; 21754 } 21755 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21756 finishedReceiver); 21757 } 21758 21759 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21760 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21761 sendResourcesChangedBroadcast(mediaStatus, replacing, 21762 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21763 } 21764 21765 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21766 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21767 int size = pkgList.length; 21768 if (size > 0) { 21769 // Send broadcasts here 21770 Bundle extras = new Bundle(); 21771 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21772 if (uidArr != null) { 21773 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21774 } 21775 if (replacing) { 21776 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21777 } 21778 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21779 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21780 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null); 21781 } 21782 } 21783 21784 private void loadPrivatePackages(final VolumeInfo vol) { 21785 mHandler.post(new Runnable() { 21786 @Override 21787 public void run() { 21788 loadPrivatePackagesInner(vol); 21789 } 21790 }); 21791 } 21792 21793 private void loadPrivatePackagesInner(VolumeInfo vol) { 21794 final String volumeUuid = vol.fsUuid; 21795 if (TextUtils.isEmpty(volumeUuid)) { 21796 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21797 return; 21798 } 21799 21800 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21801 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21802 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21803 21804 final VersionInfo ver; 21805 final List<PackageSetting> packages; 21806 synchronized (mPackages) { 21807 ver = mSettings.findOrCreateVersion(volumeUuid); 21808 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21809 } 21810 21811 for (PackageSetting ps : packages) { 21812 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21813 synchronized (mInstallLock) { 21814 final PackageParser.Package pkg; 21815 try { 21816 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21817 loaded.add(pkg.applicationInfo); 21818 21819 } catch (PackageManagerException e) { 21820 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21821 } 21822 21823 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21824 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21825 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21826 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21827 } 21828 } 21829 } 21830 21831 // Reconcile app data for all started/unlocked users 21832 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21833 final UserManager um = mContext.getSystemService(UserManager.class); 21834 UserManagerInternal umInternal = getUserManagerInternal(); 21835 for (UserInfo user : um.getUsers()) { 21836 final int flags; 21837 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21838 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21839 } else if (umInternal.isUserRunning(user.id)) { 21840 flags = StorageManager.FLAG_STORAGE_DE; 21841 } else { 21842 continue; 21843 } 21844 21845 try { 21846 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21847 synchronized (mInstallLock) { 21848 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21849 } 21850 } catch (IllegalStateException e) { 21851 // Device was probably ejected, and we'll process that event momentarily 21852 Slog.w(TAG, "Failed to prepare storage: " + e); 21853 } 21854 } 21855 21856 synchronized (mPackages) { 21857 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 21858 if (sdkUpdated) { 21859 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21860 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21861 } 21862 mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(), 21863 mPermissionCallback); 21864 21865 // Yay, everything is now upgraded 21866 ver.forceCurrent(); 21867 21868 mSettings.writeLPr(); 21869 } 21870 21871 for (PackageFreezer freezer : freezers) { 21872 freezer.close(); 21873 } 21874 21875 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21876 sendResourcesChangedBroadcast(true, false, loaded, null); 21877 mLoadedVolumes.add(vol.getId()); 21878 } 21879 21880 private void unloadPrivatePackages(final VolumeInfo vol) { 21881 mHandler.post(new Runnable() { 21882 @Override 21883 public void run() { 21884 unloadPrivatePackagesInner(vol); 21885 } 21886 }); 21887 } 21888 21889 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21890 final String volumeUuid = vol.fsUuid; 21891 if (TextUtils.isEmpty(volumeUuid)) { 21892 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21893 return; 21894 } 21895 21896 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21897 synchronized (mInstallLock) { 21898 synchronized (mPackages) { 21899 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21900 for (PackageSetting ps : packages) { 21901 if (ps.pkg == null) continue; 21902 21903 final ApplicationInfo info = ps.pkg.applicationInfo; 21904 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21905 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 21906 21907 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21908 "unloadPrivatePackagesInner")) { 21909 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21910 false, null)) { 21911 unloaded.add(info); 21912 } else { 21913 Slog.w(TAG, "Failed to unload " + ps.codePath); 21914 } 21915 } 21916 21917 // Try very hard to release any references to this package 21918 // so we don't risk the system server being killed due to 21919 // open FDs 21920 AttributeCache.instance().removePackage(ps.name); 21921 } 21922 21923 mSettings.writeLPr(); 21924 } 21925 } 21926 21927 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21928 sendResourcesChangedBroadcast(false, false, unloaded, null); 21929 mLoadedVolumes.remove(vol.getId()); 21930 21931 // Try very hard to release any references to this path so we don't risk 21932 // the system server being killed due to open FDs 21933 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21934 21935 for (int i = 0; i < 3; i++) { 21936 System.gc(); 21937 System.runFinalization(); 21938 } 21939 } 21940 21941 private void assertPackageKnown(String volumeUuid, String packageName) 21942 throws PackageManagerException { 21943 synchronized (mPackages) { 21944 // Normalize package name to handle renamed packages 21945 packageName = normalizePackageNameLPr(packageName); 21946 21947 final PackageSetting ps = mSettings.mPackages.get(packageName); 21948 if (ps == null) { 21949 throw new PackageManagerException("Package " + packageName + " is unknown"); 21950 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21951 throw new PackageManagerException( 21952 "Package " + packageName + " found on unknown volume " + volumeUuid 21953 + "; expected volume " + ps.volumeUuid); 21954 } 21955 } 21956 } 21957 21958 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21959 throws PackageManagerException { 21960 synchronized (mPackages) { 21961 // Normalize package name to handle renamed packages 21962 packageName = normalizePackageNameLPr(packageName); 21963 21964 final PackageSetting ps = mSettings.mPackages.get(packageName); 21965 if (ps == null) { 21966 throw new PackageManagerException("Package " + packageName + " is unknown"); 21967 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21968 throw new PackageManagerException( 21969 "Package " + packageName + " found on unknown volume " + volumeUuid 21970 + "; expected volume " + ps.volumeUuid); 21971 } else if (!ps.getInstalled(userId)) { 21972 throw new PackageManagerException( 21973 "Package " + packageName + " not installed for user " + userId); 21974 } 21975 } 21976 } 21977 21978 private List<String> collectAbsoluteCodePaths() { 21979 synchronized (mPackages) { 21980 List<String> codePaths = new ArrayList<>(); 21981 final int packageCount = mSettings.mPackages.size(); 21982 for (int i = 0; i < packageCount; i++) { 21983 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21984 codePaths.add(ps.codePath.getAbsolutePath()); 21985 } 21986 return codePaths; 21987 } 21988 } 21989 21990 /** 21991 * Examine all apps present on given mounted volume, and destroy apps that 21992 * aren't expected, either due to uninstallation or reinstallation on 21993 * another volume. 21994 */ 21995 private void reconcileApps(String volumeUuid) { 21996 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21997 List<File> filesToDelete = null; 21998 21999 final File[] files = FileUtils.listFilesOrEmpty( 22000 Environment.getDataAppDirectory(volumeUuid)); 22001 for (File file : files) { 22002 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 22003 && !PackageInstallerService.isStageName(file.getName()); 22004 if (!isPackage) { 22005 // Ignore entries which are not packages 22006 continue; 22007 } 22008 22009 String absolutePath = file.getAbsolutePath(); 22010 22011 boolean pathValid = false; 22012 final int absoluteCodePathCount = absoluteCodePaths.size(); 22013 for (int i = 0; i < absoluteCodePathCount; i++) { 22014 String absoluteCodePath = absoluteCodePaths.get(i); 22015 if (absolutePath.startsWith(absoluteCodePath)) { 22016 pathValid = true; 22017 break; 22018 } 22019 } 22020 22021 if (!pathValid) { 22022 if (filesToDelete == null) { 22023 filesToDelete = new ArrayList<>(); 22024 } 22025 filesToDelete.add(file); 22026 } 22027 } 22028 22029 if (filesToDelete != null) { 22030 final int fileToDeleteCount = filesToDelete.size(); 22031 for (int i = 0; i < fileToDeleteCount; i++) { 22032 File fileToDelete = filesToDelete.get(i); 22033 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 22034 synchronized (mInstallLock) { 22035 removeCodePathLI(fileToDelete); 22036 } 22037 } 22038 } 22039 } 22040 22041 /** 22042 * Reconcile all app data for the given user. 22043 * <p> 22044 * Verifies that directories exist and that ownership and labeling is 22045 * correct for all installed apps on all mounted volumes. 22046 */ 22047 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 22048 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22049 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 22050 final String volumeUuid = vol.getFsUuid(); 22051 synchronized (mInstallLock) { 22052 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 22053 } 22054 } 22055 } 22056 22057 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22058 boolean migrateAppData) { 22059 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 22060 } 22061 22062 /** 22063 * Reconcile all app data on given mounted volume. 22064 * <p> 22065 * Destroys app data that isn't expected, either due to uninstallation or 22066 * reinstallation on another volume. 22067 * <p> 22068 * Verifies that directories exist and that ownership and labeling is 22069 * correct for all installed apps. 22070 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 22071 */ 22072 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22073 boolean migrateAppData, boolean onlyCoreApps) { 22074 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 22075 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 22076 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 22077 22078 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 22079 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 22080 22081 // First look for stale data that doesn't belong, and check if things 22082 // have changed since we did our last restorecon 22083 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22084 if (StorageManager.isFileEncryptedNativeOrEmulated() 22085 && !StorageManager.isUserKeyUnlocked(userId)) { 22086 throw new RuntimeException( 22087 "Yikes, someone asked us to reconcile CE storage while " + userId 22088 + " was still locked; this would have caused massive data loss!"); 22089 } 22090 22091 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 22092 for (File file : files) { 22093 final String packageName = file.getName(); 22094 try { 22095 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22096 } catch (PackageManagerException e) { 22097 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22098 try { 22099 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22100 StorageManager.FLAG_STORAGE_CE, 0); 22101 } catch (InstallerException e2) { 22102 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22103 } 22104 } 22105 } 22106 } 22107 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 22108 final File[] files = FileUtils.listFilesOrEmpty(deDir); 22109 for (File file : files) { 22110 final String packageName = file.getName(); 22111 try { 22112 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22113 } catch (PackageManagerException e) { 22114 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22115 try { 22116 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22117 StorageManager.FLAG_STORAGE_DE, 0); 22118 } catch (InstallerException e2) { 22119 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22120 } 22121 } 22122 } 22123 } 22124 22125 // Ensure that data directories are ready to roll for all packages 22126 // installed for this volume and user 22127 final List<PackageSetting> packages; 22128 synchronized (mPackages) { 22129 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22130 } 22131 int preparedCount = 0; 22132 for (PackageSetting ps : packages) { 22133 final String packageName = ps.name; 22134 if (ps.pkg == null) { 22135 Slog.w(TAG, "Odd, missing scanned package " + packageName); 22136 // TODO: might be due to legacy ASEC apps; we should circle back 22137 // and reconcile again once they're scanned 22138 continue; 22139 } 22140 // Skip non-core apps if requested 22141 if (onlyCoreApps && !ps.pkg.coreApp) { 22142 result.add(packageName); 22143 continue; 22144 } 22145 22146 if (ps.getInstalled(userId)) { 22147 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 22148 preparedCount++; 22149 } 22150 } 22151 22152 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 22153 return result; 22154 } 22155 22156 /** 22157 * Prepare app data for the given app just after it was installed or 22158 * upgraded. This method carefully only touches users that it's installed 22159 * for, and it forces a restorecon to handle any seinfo changes. 22160 * <p> 22161 * Verifies that directories exist and that ownership and labeling is 22162 * correct for all installed apps. If there is an ownership mismatch, it 22163 * will try recovering system apps by wiping data; third-party app data is 22164 * left intact. 22165 * <p> 22166 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 22167 */ 22168 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 22169 final PackageSetting ps; 22170 synchronized (mPackages) { 22171 ps = mSettings.mPackages.get(pkg.packageName); 22172 mSettings.writeKernelMappingLPr(ps); 22173 } 22174 22175 final UserManager um = mContext.getSystemService(UserManager.class); 22176 UserManagerInternal umInternal = getUserManagerInternal(); 22177 for (UserInfo user : um.getUsers()) { 22178 final int flags; 22179 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22180 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22181 } else if (umInternal.isUserRunning(user.id)) { 22182 flags = StorageManager.FLAG_STORAGE_DE; 22183 } else { 22184 continue; 22185 } 22186 22187 if (ps.getInstalled(user.id)) { 22188 // TODO: when user data is locked, mark that we're still dirty 22189 prepareAppDataLIF(pkg, user.id, flags); 22190 } 22191 } 22192 } 22193 22194 /** 22195 * Prepare app data for the given app. 22196 * <p> 22197 * Verifies that directories exist and that ownership and labeling is 22198 * correct for all installed apps. If there is an ownership mismatch, this 22199 * will try recovering system apps by wiping data; third-party app data is 22200 * left intact. 22201 */ 22202 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 22203 if (pkg == null) { 22204 Slog.wtf(TAG, "Package was null!", new Throwable()); 22205 return; 22206 } 22207 prepareAppDataLeafLIF(pkg, userId, flags); 22208 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22209 for (int i = 0; i < childCount; i++) { 22210 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 22211 } 22212 } 22213 22214 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 22215 boolean maybeMigrateAppData) { 22216 prepareAppDataLIF(pkg, userId, flags); 22217 22218 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 22219 // We may have just shuffled around app data directories, so 22220 // prepare them one more time 22221 prepareAppDataLIF(pkg, userId, flags); 22222 } 22223 } 22224 22225 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22226 if (DEBUG_APP_DATA) { 22227 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 22228 + Integer.toHexString(flags)); 22229 } 22230 22231 final String volumeUuid = pkg.volumeUuid; 22232 final String packageName = pkg.packageName; 22233 final ApplicationInfo app = pkg.applicationInfo; 22234 final int appId = UserHandle.getAppId(app.uid); 22235 22236 Preconditions.checkNotNull(app.seInfo); 22237 22238 long ceDataInode = -1; 22239 try { 22240 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22241 appId, app.seInfo, app.targetSdkVersion); 22242 } catch (InstallerException e) { 22243 if (app.isSystemApp()) { 22244 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 22245 + ", but trying to recover: " + e); 22246 destroyAppDataLeafLIF(pkg, userId, flags); 22247 try { 22248 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22249 appId, app.seInfo, app.targetSdkVersion); 22250 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 22251 } catch (InstallerException e2) { 22252 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 22253 } 22254 } else { 22255 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22256 } 22257 } 22258 // Prepare the application profiles. 22259 mArtManagerService.prepareAppProfiles(pkg, userId); 22260 22261 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22262 // TODO: mark this structure as dirty so we persist it! 22263 synchronized (mPackages) { 22264 final PackageSetting ps = mSettings.mPackages.get(packageName); 22265 if (ps != null) { 22266 ps.setCeDataInode(ceDataInode, userId); 22267 } 22268 } 22269 } 22270 22271 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22272 } 22273 22274 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22275 if (pkg == null) { 22276 Slog.wtf(TAG, "Package was null!", new Throwable()); 22277 return; 22278 } 22279 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22280 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22281 for (int i = 0; i < childCount; i++) { 22282 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22283 } 22284 } 22285 22286 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22287 final String volumeUuid = pkg.volumeUuid; 22288 final String packageName = pkg.packageName; 22289 final ApplicationInfo app = pkg.applicationInfo; 22290 22291 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22292 // Create a native library symlink only if we have native libraries 22293 // and if the native libraries are 32 bit libraries. We do not provide 22294 // this symlink for 64 bit libraries. 22295 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22296 final String nativeLibPath = app.nativeLibraryDir; 22297 try { 22298 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22299 nativeLibPath, userId); 22300 } catch (InstallerException e) { 22301 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22302 } 22303 } 22304 } 22305 } 22306 22307 /** 22308 * For system apps on non-FBE devices, this method migrates any existing 22309 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22310 * requested by the app. 22311 */ 22312 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22313 if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated() 22314 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22315 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22316 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22317 try { 22318 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22319 storageTarget); 22320 } catch (InstallerException e) { 22321 logCriticalInfo(Log.WARN, 22322 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22323 } 22324 return true; 22325 } else { 22326 return false; 22327 } 22328 } 22329 22330 public PackageFreezer freezePackage(String packageName, String killReason) { 22331 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22332 } 22333 22334 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22335 return new PackageFreezer(packageName, userId, killReason); 22336 } 22337 22338 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22339 String killReason) { 22340 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22341 } 22342 22343 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22344 String killReason) { 22345 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22346 return new PackageFreezer(); 22347 } else { 22348 return freezePackage(packageName, userId, killReason); 22349 } 22350 } 22351 22352 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22353 String killReason) { 22354 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22355 } 22356 22357 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22358 String killReason) { 22359 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22360 return new PackageFreezer(); 22361 } else { 22362 return freezePackage(packageName, userId, killReason); 22363 } 22364 } 22365 22366 /** 22367 * Class that freezes and kills the given package upon creation, and 22368 * unfreezes it upon closing. This is typically used when doing surgery on 22369 * app code/data to prevent the app from running while you're working. 22370 */ 22371 private class PackageFreezer implements AutoCloseable { 22372 private final String mPackageName; 22373 private final PackageFreezer[] mChildren; 22374 22375 private final boolean mWeFroze; 22376 22377 private final AtomicBoolean mClosed = new AtomicBoolean(); 22378 private final CloseGuard mCloseGuard = CloseGuard.get(); 22379 22380 /** 22381 * Create and return a stub freezer that doesn't actually do anything, 22382 * typically used when someone requested 22383 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22384 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22385 */ 22386 public PackageFreezer() { 22387 mPackageName = null; 22388 mChildren = null; 22389 mWeFroze = false; 22390 mCloseGuard.open("close"); 22391 } 22392 22393 public PackageFreezer(String packageName, int userId, String killReason) { 22394 synchronized (mPackages) { 22395 mPackageName = packageName; 22396 mWeFroze = mFrozenPackages.add(mPackageName); 22397 22398 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22399 if (ps != null) { 22400 killApplication(ps.name, ps.appId, userId, killReason); 22401 } 22402 22403 final PackageParser.Package p = mPackages.get(packageName); 22404 if (p != null && p.childPackages != null) { 22405 final int N = p.childPackages.size(); 22406 mChildren = new PackageFreezer[N]; 22407 for (int i = 0; i < N; i++) { 22408 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22409 userId, killReason); 22410 } 22411 } else { 22412 mChildren = null; 22413 } 22414 } 22415 mCloseGuard.open("close"); 22416 } 22417 22418 @Override 22419 protected void finalize() throws Throwable { 22420 try { 22421 if (mCloseGuard != null) { 22422 mCloseGuard.warnIfOpen(); 22423 } 22424 22425 close(); 22426 } finally { 22427 super.finalize(); 22428 } 22429 } 22430 22431 @Override 22432 public void close() { 22433 mCloseGuard.close(); 22434 if (mClosed.compareAndSet(false, true)) { 22435 synchronized (mPackages) { 22436 if (mWeFroze) { 22437 mFrozenPackages.remove(mPackageName); 22438 } 22439 22440 if (mChildren != null) { 22441 for (PackageFreezer freezer : mChildren) { 22442 freezer.close(); 22443 } 22444 } 22445 } 22446 } 22447 } 22448 } 22449 22450 /** 22451 * Verify that given package is currently frozen. 22452 */ 22453 private void checkPackageFrozen(String packageName) { 22454 synchronized (mPackages) { 22455 if (!mFrozenPackages.contains(packageName)) { 22456 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22457 } 22458 } 22459 } 22460 22461 @Override 22462 public int movePackage(final String packageName, final String volumeUuid) { 22463 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22464 22465 final int callingUid = Binder.getCallingUid(); 22466 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 22467 final int moveId = mNextMoveId.getAndIncrement(); 22468 mHandler.post(new Runnable() { 22469 @Override 22470 public void run() { 22471 try { 22472 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 22473 } catch (PackageManagerException e) { 22474 Slog.w(TAG, "Failed to move " + packageName, e); 22475 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 22476 } 22477 } 22478 }); 22479 return moveId; 22480 } 22481 22482 private void movePackageInternal(final String packageName, final String volumeUuid, 22483 final int moveId, final int callingUid, UserHandle user) 22484 throws PackageManagerException { 22485 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22486 final PackageManager pm = mContext.getPackageManager(); 22487 22488 final boolean currentAsec; 22489 final String currentVolumeUuid; 22490 final File codeFile; 22491 final String installerPackageName; 22492 final String packageAbiOverride; 22493 final int appId; 22494 final String seinfo; 22495 final String label; 22496 final int targetSdkVersion; 22497 final PackageFreezer freezer; 22498 final int[] installedUserIds; 22499 22500 // reader 22501 synchronized (mPackages) { 22502 final PackageParser.Package pkg = mPackages.get(packageName); 22503 final PackageSetting ps = mSettings.mPackages.get(packageName); 22504 if (pkg == null 22505 || ps == null 22506 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 22507 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22508 } 22509 if (pkg.applicationInfo.isSystemApp()) { 22510 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22511 "Cannot move system application"); 22512 } 22513 22514 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22515 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22516 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22517 if (isInternalStorage && !allow3rdPartyOnInternal) { 22518 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22519 "3rd party apps are not allowed on internal storage"); 22520 } 22521 22522 if (pkg.applicationInfo.isExternalAsec()) { 22523 currentAsec = true; 22524 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22525 } else if (pkg.applicationInfo.isForwardLocked()) { 22526 currentAsec = true; 22527 currentVolumeUuid = "forward_locked"; 22528 } else { 22529 currentAsec = false; 22530 currentVolumeUuid = ps.volumeUuid; 22531 22532 final File probe = new File(pkg.codePath); 22533 final File probeOat = new File(probe, "oat"); 22534 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22535 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22536 "Move only supported for modern cluster style installs"); 22537 } 22538 } 22539 22540 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22541 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22542 "Package already moved to " + volumeUuid); 22543 } 22544 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22545 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22546 "Device admin cannot be moved"); 22547 } 22548 22549 if (mFrozenPackages.contains(packageName)) { 22550 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22551 "Failed to move already frozen package"); 22552 } 22553 22554 codeFile = new File(pkg.codePath); 22555 installerPackageName = ps.installerPackageName; 22556 packageAbiOverride = ps.cpuAbiOverrideString; 22557 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22558 seinfo = pkg.applicationInfo.seInfo; 22559 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22560 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22561 freezer = freezePackage(packageName, "movePackageInternal"); 22562 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22563 } 22564 22565 final Bundle extras = new Bundle(); 22566 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22567 extras.putString(Intent.EXTRA_TITLE, label); 22568 mMoveCallbacks.notifyCreated(moveId, extras); 22569 22570 int installFlags; 22571 final boolean moveCompleteApp; 22572 final File measurePath; 22573 22574 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22575 installFlags = INSTALL_INTERNAL; 22576 moveCompleteApp = !currentAsec; 22577 measurePath = Environment.getDataAppDirectory(volumeUuid); 22578 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22579 installFlags = INSTALL_EXTERNAL; 22580 moveCompleteApp = false; 22581 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22582 } else { 22583 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22584 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22585 || !volume.isMountedWritable()) { 22586 freezer.close(); 22587 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22588 "Move location not mounted private volume"); 22589 } 22590 22591 Preconditions.checkState(!currentAsec); 22592 22593 installFlags = INSTALL_INTERNAL; 22594 moveCompleteApp = true; 22595 measurePath = Environment.getDataAppDirectory(volumeUuid); 22596 } 22597 22598 // If we're moving app data around, we need all the users unlocked 22599 if (moveCompleteApp) { 22600 for (int userId : installedUserIds) { 22601 if (StorageManager.isFileEncryptedNativeOrEmulated() 22602 && !StorageManager.isUserKeyUnlocked(userId)) { 22603 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 22604 "User " + userId + " must be unlocked"); 22605 } 22606 } 22607 } 22608 22609 final PackageStats stats = new PackageStats(null, -1); 22610 synchronized (mInstaller) { 22611 for (int userId : installedUserIds) { 22612 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22613 freezer.close(); 22614 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22615 "Failed to measure package size"); 22616 } 22617 } 22618 } 22619 22620 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22621 + stats.dataSize); 22622 22623 final long startFreeBytes = measurePath.getUsableSpace(); 22624 final long sizeBytes; 22625 if (moveCompleteApp) { 22626 sizeBytes = stats.codeSize + stats.dataSize; 22627 } else { 22628 sizeBytes = stats.codeSize; 22629 } 22630 22631 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22632 freezer.close(); 22633 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22634 "Not enough free space to move"); 22635 } 22636 22637 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22638 22639 final CountDownLatch installedLatch = new CountDownLatch(1); 22640 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22641 @Override 22642 public void onUserActionRequired(Intent intent) throws RemoteException { 22643 throw new IllegalStateException(); 22644 } 22645 22646 @Override 22647 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22648 Bundle extras) throws RemoteException { 22649 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22650 + PackageManager.installStatusToString(returnCode, msg)); 22651 22652 installedLatch.countDown(); 22653 freezer.close(); 22654 22655 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22656 switch (status) { 22657 case PackageInstaller.STATUS_SUCCESS: 22658 mMoveCallbacks.notifyStatusChanged(moveId, 22659 PackageManager.MOVE_SUCCEEDED); 22660 break; 22661 case PackageInstaller.STATUS_FAILURE_STORAGE: 22662 mMoveCallbacks.notifyStatusChanged(moveId, 22663 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22664 break; 22665 default: 22666 mMoveCallbacks.notifyStatusChanged(moveId, 22667 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22668 break; 22669 } 22670 } 22671 }; 22672 22673 final MoveInfo move; 22674 if (moveCompleteApp) { 22675 // Kick off a thread to report progress estimates 22676 new Thread() { 22677 @Override 22678 public void run() { 22679 while (true) { 22680 try { 22681 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22682 break; 22683 } 22684 } catch (InterruptedException ignored) { 22685 } 22686 22687 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22688 final int progress = 10 + (int) MathUtils.constrain( 22689 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22690 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22691 } 22692 } 22693 }.start(); 22694 22695 final String dataAppName = codeFile.getName(); 22696 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22697 dataAppName, appId, seinfo, targetSdkVersion); 22698 } else { 22699 move = null; 22700 } 22701 22702 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22703 22704 final Message msg = mHandler.obtainMessage(INIT_COPY); 22705 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22706 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22707 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22708 packageAbiOverride, null /*grantedPermissions*/, 22709 PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN); 22710 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22711 msg.obj = params; 22712 22713 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22714 System.identityHashCode(msg.obj)); 22715 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22716 System.identityHashCode(msg.obj)); 22717 22718 mHandler.sendMessage(msg); 22719 } 22720 22721 @Override 22722 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22723 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22724 22725 final int realMoveId = mNextMoveId.getAndIncrement(); 22726 final Bundle extras = new Bundle(); 22727 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22728 mMoveCallbacks.notifyCreated(realMoveId, extras); 22729 22730 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22731 @Override 22732 public void onCreated(int moveId, Bundle extras) { 22733 // Ignored 22734 } 22735 22736 @Override 22737 public void onStatusChanged(int moveId, int status, long estMillis) { 22738 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22739 } 22740 }; 22741 22742 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22743 storage.setPrimaryStorageUuid(volumeUuid, callback); 22744 return realMoveId; 22745 } 22746 22747 @Override 22748 public int getMoveStatus(int moveId) { 22749 mContext.enforceCallingOrSelfPermission( 22750 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22751 return mMoveCallbacks.mLastStatus.get(moveId); 22752 } 22753 22754 @Override 22755 public void registerMoveCallback(IPackageMoveObserver callback) { 22756 mContext.enforceCallingOrSelfPermission( 22757 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22758 mMoveCallbacks.register(callback); 22759 } 22760 22761 @Override 22762 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22763 mContext.enforceCallingOrSelfPermission( 22764 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22765 mMoveCallbacks.unregister(callback); 22766 } 22767 22768 @Override 22769 public boolean setInstallLocation(int loc) { 22770 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22771 null); 22772 if (getInstallLocation() == loc) { 22773 return true; 22774 } 22775 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22776 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22777 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22778 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22779 return true; 22780 } 22781 return false; 22782 } 22783 22784 @Override 22785 public int getInstallLocation() { 22786 // allow instant app access 22787 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22788 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22789 PackageHelper.APP_INSTALL_AUTO); 22790 } 22791 22792 /** Called by UserManagerService */ 22793 void cleanUpUser(UserManagerService userManager, int userHandle) { 22794 synchronized (mPackages) { 22795 mDirtyUsers.remove(userHandle); 22796 mUserNeedsBadging.delete(userHandle); 22797 mSettings.removeUserLPw(userHandle); 22798 mPendingBroadcasts.remove(userHandle); 22799 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22800 removeUnusedPackagesLPw(userManager, userHandle); 22801 } 22802 } 22803 22804 /** 22805 * We're removing userHandle and would like to remove any downloaded packages 22806 * that are no longer in use by any other user. 22807 * @param userHandle the user being removed 22808 */ 22809 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22810 final boolean DEBUG_CLEAN_APKS = false; 22811 int [] users = userManager.getUserIds(); 22812 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22813 while (psit.hasNext()) { 22814 PackageSetting ps = psit.next(); 22815 if (ps.pkg == null) { 22816 continue; 22817 } 22818 final String packageName = ps.pkg.packageName; 22819 // Skip over if system app 22820 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22821 continue; 22822 } 22823 if (DEBUG_CLEAN_APKS) { 22824 Slog.i(TAG, "Checking package " + packageName); 22825 } 22826 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22827 if (keep) { 22828 if (DEBUG_CLEAN_APKS) { 22829 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22830 } 22831 } else { 22832 for (int i = 0; i < users.length; i++) { 22833 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22834 keep = true; 22835 if (DEBUG_CLEAN_APKS) { 22836 Slog.i(TAG, " Keeping package " + packageName + " for user " 22837 + users[i]); 22838 } 22839 break; 22840 } 22841 } 22842 } 22843 if (!keep) { 22844 if (DEBUG_CLEAN_APKS) { 22845 Slog.i(TAG, " Removing package " + packageName); 22846 } 22847 mHandler.post(new Runnable() { 22848 public void run() { 22849 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22850 userHandle, 0); 22851 } //end run 22852 }); 22853 } 22854 } 22855 } 22856 22857 /** Called by UserManagerService */ 22858 void createNewUser(int userId, String[] disallowedPackages) { 22859 synchronized (mInstallLock) { 22860 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22861 } 22862 synchronized (mPackages) { 22863 scheduleWritePackageRestrictionsLocked(userId); 22864 scheduleWritePackageListLocked(userId); 22865 applyFactoryDefaultBrowserLPw(userId); 22866 primeDomainVerificationsLPw(userId); 22867 } 22868 } 22869 22870 void onNewUserCreated(final int userId) { 22871 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22872 synchronized(mPackages) { 22873 // If permission review for legacy apps is required, we represent 22874 // dagerous permissions for such apps as always granted runtime 22875 // permissions to keep per user flag state whether review is needed. 22876 // Hence, if a new user is added we have to propagate dangerous 22877 // permission grants for these legacy apps. 22878 if (mSettings.mPermissions.mPermissionReviewRequired) { 22879// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG 22880 mPermissionManager.updateAllPermissions( 22881 StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(), 22882 mPermissionCallback); 22883 } 22884 } 22885 } 22886 22887 @Override 22888 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22889 mContext.enforceCallingOrSelfPermission( 22890 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22891 "Only package verification agents can read the verifier device identity"); 22892 22893 synchronized (mPackages) { 22894 return mSettings.getVerifierDeviceIdentityLPw(); 22895 } 22896 } 22897 22898 @Override 22899 public void setPermissionEnforced(String permission, boolean enforced) { 22900 // TODO: Now that we no longer change GID for storage, this should to away. 22901 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22902 "setPermissionEnforced"); 22903 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22904 synchronized (mPackages) { 22905 if (mSettings.mReadExternalStorageEnforced == null 22906 || mSettings.mReadExternalStorageEnforced != enforced) { 22907 mSettings.mReadExternalStorageEnforced = 22908 enforced ? Boolean.TRUE : Boolean.FALSE; 22909 mSettings.writeLPr(); 22910 } 22911 } 22912 // kill any non-foreground processes so we restart them and 22913 // grant/revoke the GID. 22914 final IActivityManager am = ActivityManager.getService(); 22915 if (am != null) { 22916 final long token = Binder.clearCallingIdentity(); 22917 try { 22918 am.killProcessesBelowForeground("setPermissionEnforcement"); 22919 } catch (RemoteException e) { 22920 } finally { 22921 Binder.restoreCallingIdentity(token); 22922 } 22923 } 22924 } else { 22925 throw new IllegalArgumentException("No selective enforcement for " + permission); 22926 } 22927 } 22928 22929 @Override 22930 @Deprecated 22931 public boolean isPermissionEnforced(String permission) { 22932 // allow instant applications 22933 return true; 22934 } 22935 22936 @Override 22937 public boolean isStorageLow() { 22938 // allow instant applications 22939 final long token = Binder.clearCallingIdentity(); 22940 try { 22941 final DeviceStorageMonitorInternal 22942 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22943 if (dsm != null) { 22944 return dsm.isMemoryLow(); 22945 } else { 22946 return false; 22947 } 22948 } finally { 22949 Binder.restoreCallingIdentity(token); 22950 } 22951 } 22952 22953 @Override 22954 public IPackageInstaller getPackageInstaller() { 22955 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 22956 return null; 22957 } 22958 return mInstallerService; 22959 } 22960 22961 @Override 22962 public IArtManager getArtManager() { 22963 return mArtManagerService; 22964 } 22965 22966 private boolean userNeedsBadging(int userId) { 22967 int index = mUserNeedsBadging.indexOfKey(userId); 22968 if (index < 0) { 22969 final UserInfo userInfo; 22970 final long token = Binder.clearCallingIdentity(); 22971 try { 22972 userInfo = sUserManager.getUserInfo(userId); 22973 } finally { 22974 Binder.restoreCallingIdentity(token); 22975 } 22976 final boolean b; 22977 if (userInfo != null && userInfo.isManagedProfile()) { 22978 b = true; 22979 } else { 22980 b = false; 22981 } 22982 mUserNeedsBadging.put(userId, b); 22983 return b; 22984 } 22985 return mUserNeedsBadging.valueAt(index); 22986 } 22987 22988 @Override 22989 public KeySet getKeySetByAlias(String packageName, String alias) { 22990 if (packageName == null || alias == null) { 22991 return null; 22992 } 22993 synchronized(mPackages) { 22994 final PackageParser.Package pkg = mPackages.get(packageName); 22995 if (pkg == null) { 22996 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22997 throw new IllegalArgumentException("Unknown package: " + packageName); 22998 } 22999 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23000 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 23001 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 23002 throw new IllegalArgumentException("Unknown package: " + packageName); 23003 } 23004 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23005 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 23006 } 23007 } 23008 23009 @Override 23010 public KeySet getSigningKeySet(String packageName) { 23011 if (packageName == null) { 23012 return null; 23013 } 23014 synchronized(mPackages) { 23015 final int callingUid = Binder.getCallingUid(); 23016 final int callingUserId = UserHandle.getUserId(callingUid); 23017 final PackageParser.Package pkg = mPackages.get(packageName); 23018 if (pkg == null) { 23019 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23020 throw new IllegalArgumentException("Unknown package: " + packageName); 23021 } 23022 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23023 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 23024 // filter and pretend the package doesn't exist 23025 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 23026 + ", uid:" + callingUid); 23027 throw new IllegalArgumentException("Unknown package: " + packageName); 23028 } 23029 if (pkg.applicationInfo.uid != callingUid 23030 && Process.SYSTEM_UID != callingUid) { 23031 throw new SecurityException("May not access signing KeySet of other apps."); 23032 } 23033 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23034 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 23035 } 23036 } 23037 23038 @Override 23039 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 23040 final int callingUid = Binder.getCallingUid(); 23041 if (getInstantAppPackageName(callingUid) != null) { 23042 return false; 23043 } 23044 if (packageName == null || ks == null) { 23045 return false; 23046 } 23047 synchronized(mPackages) { 23048 final PackageParser.Package pkg = mPackages.get(packageName); 23049 if (pkg == null 23050 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23051 UserHandle.getUserId(callingUid))) { 23052 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23053 throw new IllegalArgumentException("Unknown package: " + packageName); 23054 } 23055 IBinder ksh = ks.getToken(); 23056 if (ksh instanceof KeySetHandle) { 23057 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23058 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 23059 } 23060 return false; 23061 } 23062 } 23063 23064 @Override 23065 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 23066 final int callingUid = Binder.getCallingUid(); 23067 if (getInstantAppPackageName(callingUid) != null) { 23068 return false; 23069 } 23070 if (packageName == null || ks == null) { 23071 return false; 23072 } 23073 synchronized(mPackages) { 23074 final PackageParser.Package pkg = mPackages.get(packageName); 23075 if (pkg == null 23076 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23077 UserHandle.getUserId(callingUid))) { 23078 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23079 throw new IllegalArgumentException("Unknown package: " + packageName); 23080 } 23081 IBinder ksh = ks.getToken(); 23082 if (ksh instanceof KeySetHandle) { 23083 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23084 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 23085 } 23086 return false; 23087 } 23088 } 23089 23090 private void deletePackageIfUnusedLPr(final String packageName) { 23091 PackageSetting ps = mSettings.mPackages.get(packageName); 23092 if (ps == null) { 23093 return; 23094 } 23095 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 23096 // TODO Implement atomic delete if package is unused 23097 // It is currently possible that the package will be deleted even if it is installed 23098 // after this method returns. 23099 mHandler.post(new Runnable() { 23100 public void run() { 23101 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23102 0, PackageManager.DELETE_ALL_USERS); 23103 } 23104 }); 23105 } 23106 } 23107 23108 /** 23109 * Check and throw if the given before/after packages would be considered a 23110 * downgrade. 23111 */ 23112 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 23113 throws PackageManagerException { 23114 if (after.getLongVersionCode() < before.getLongVersionCode()) { 23115 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23116 "Update version code " + after.versionCode + " is older than current " 23117 + before.getLongVersionCode()); 23118 } else if (after.getLongVersionCode() == before.getLongVersionCode()) { 23119 if (after.baseRevisionCode < before.baseRevisionCode) { 23120 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23121 "Update base revision code " + after.baseRevisionCode 23122 + " is older than current " + before.baseRevisionCode); 23123 } 23124 23125 if (!ArrayUtils.isEmpty(after.splitNames)) { 23126 for (int i = 0; i < after.splitNames.length; i++) { 23127 final String splitName = after.splitNames[i]; 23128 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 23129 if (j != -1) { 23130 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 23131 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23132 "Update split " + splitName + " revision code " 23133 + after.splitRevisionCodes[i] + " is older than current " 23134 + before.splitRevisionCodes[j]); 23135 } 23136 } 23137 } 23138 } 23139 } 23140 } 23141 23142 private static class MoveCallbacks extends Handler { 23143 private static final int MSG_CREATED = 1; 23144 private static final int MSG_STATUS_CHANGED = 2; 23145 23146 private final RemoteCallbackList<IPackageMoveObserver> 23147 mCallbacks = new RemoteCallbackList<>(); 23148 23149 private final SparseIntArray mLastStatus = new SparseIntArray(); 23150 23151 public MoveCallbacks(Looper looper) { 23152 super(looper); 23153 } 23154 23155 public void register(IPackageMoveObserver callback) { 23156 mCallbacks.register(callback); 23157 } 23158 23159 public void unregister(IPackageMoveObserver callback) { 23160 mCallbacks.unregister(callback); 23161 } 23162 23163 @Override 23164 public void handleMessage(Message msg) { 23165 final SomeArgs args = (SomeArgs) msg.obj; 23166 final int n = mCallbacks.beginBroadcast(); 23167 for (int i = 0; i < n; i++) { 23168 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 23169 try { 23170 invokeCallback(callback, msg.what, args); 23171 } catch (RemoteException ignored) { 23172 } 23173 } 23174 mCallbacks.finishBroadcast(); 23175 args.recycle(); 23176 } 23177 23178 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 23179 throws RemoteException { 23180 switch (what) { 23181 case MSG_CREATED: { 23182 callback.onCreated(args.argi1, (Bundle) args.arg2); 23183 break; 23184 } 23185 case MSG_STATUS_CHANGED: { 23186 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 23187 break; 23188 } 23189 } 23190 } 23191 23192 private void notifyCreated(int moveId, Bundle extras) { 23193 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 23194 23195 final SomeArgs args = SomeArgs.obtain(); 23196 args.argi1 = moveId; 23197 args.arg2 = extras; 23198 obtainMessage(MSG_CREATED, args).sendToTarget(); 23199 } 23200 23201 private void notifyStatusChanged(int moveId, int status) { 23202 notifyStatusChanged(moveId, status, -1); 23203 } 23204 23205 private void notifyStatusChanged(int moveId, int status, long estMillis) { 23206 Slog.v(TAG, "Move " + moveId + " status " + status); 23207 23208 final SomeArgs args = SomeArgs.obtain(); 23209 args.argi1 = moveId; 23210 args.argi2 = status; 23211 args.arg3 = estMillis; 23212 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 23213 23214 synchronized (mLastStatus) { 23215 mLastStatus.put(moveId, status); 23216 } 23217 } 23218 } 23219 23220 private final static class OnPermissionChangeListeners extends Handler { 23221 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 23222 23223 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 23224 new RemoteCallbackList<>(); 23225 23226 public OnPermissionChangeListeners(Looper looper) { 23227 super(looper); 23228 } 23229 23230 @Override 23231 public void handleMessage(Message msg) { 23232 switch (msg.what) { 23233 case MSG_ON_PERMISSIONS_CHANGED: { 23234 final int uid = msg.arg1; 23235 handleOnPermissionsChanged(uid); 23236 } break; 23237 } 23238 } 23239 23240 public void addListenerLocked(IOnPermissionsChangeListener listener) { 23241 mPermissionListeners.register(listener); 23242 23243 } 23244 23245 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 23246 mPermissionListeners.unregister(listener); 23247 } 23248 23249 public void onPermissionsChanged(int uid) { 23250 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 23251 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 23252 } 23253 } 23254 23255 private void handleOnPermissionsChanged(int uid) { 23256 final int count = mPermissionListeners.beginBroadcast(); 23257 try { 23258 for (int i = 0; i < count; i++) { 23259 IOnPermissionsChangeListener callback = mPermissionListeners 23260 .getBroadcastItem(i); 23261 try { 23262 callback.onPermissionsChanged(uid); 23263 } catch (RemoteException e) { 23264 Log.e(TAG, "Permission listener is dead", e); 23265 } 23266 } 23267 } finally { 23268 mPermissionListeners.finishBroadcast(); 23269 } 23270 } 23271 } 23272 23273 private class PackageManagerNative extends IPackageManagerNative.Stub { 23274 @Override 23275 public String[] getNamesForUids(int[] uids) throws RemoteException { 23276 final String[] results = PackageManagerService.this.getNamesForUids(uids); 23277 // massage results so they can be parsed by the native binder 23278 for (int i = results.length - 1; i >= 0; --i) { 23279 if (results[i] == null) { 23280 results[i] = ""; 23281 } 23282 } 23283 return results; 23284 } 23285 23286 // NB: this differentiates between preloads and sideloads 23287 @Override 23288 public String getInstallerForPackage(String packageName) throws RemoteException { 23289 final String installerName = getInstallerPackageName(packageName); 23290 if (!TextUtils.isEmpty(installerName)) { 23291 return installerName; 23292 } 23293 // differentiate between preload and sideload 23294 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23295 ApplicationInfo appInfo = getApplicationInfo(packageName, 23296 /*flags*/ 0, 23297 /*userId*/ callingUser); 23298 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 23299 return "preload"; 23300 } 23301 return ""; 23302 } 23303 23304 @Override 23305 public long getVersionCodeForPackage(String packageName) throws RemoteException { 23306 try { 23307 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23308 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 23309 if (pInfo != null) { 23310 return pInfo.getLongVersionCode(); 23311 } 23312 } catch (Exception e) { 23313 } 23314 return 0; 23315 } 23316 } 23317 23318 private class PackageManagerInternalImpl extends PackageManagerInternal { 23319 @Override 23320 public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask, 23321 int flagValues, int userId) { 23322 PackageManagerService.this.updatePermissionFlags( 23323 permName, packageName, flagMask, flagValues, userId); 23324 } 23325 23326 @Override 23327 public int getPermissionFlagsTEMP(String permName, String packageName, int userId) { 23328 return PackageManagerService.this.getPermissionFlags(permName, packageName, userId); 23329 } 23330 23331 @Override 23332 public boolean isInstantApp(String packageName, int userId) { 23333 return PackageManagerService.this.isInstantApp(packageName, userId); 23334 } 23335 23336 @Override 23337 public String getInstantAppPackageName(int uid) { 23338 return PackageManagerService.this.getInstantAppPackageName(uid); 23339 } 23340 23341 @Override 23342 public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) { 23343 synchronized (mPackages) { 23344 return PackageManagerService.this.filterAppAccessLPr( 23345 (PackageSetting) pkg.mExtras, callingUid, userId); 23346 } 23347 } 23348 23349 @Override 23350 public PackageParser.Package getPackage(String packageName) { 23351 synchronized (mPackages) { 23352 packageName = resolveInternalPackageNameLPr( 23353 packageName, PackageManager.VERSION_CODE_HIGHEST); 23354 return mPackages.get(packageName); 23355 } 23356 } 23357 23358 @Override 23359 public PackageList getPackageList(PackageListObserver observer) { 23360 synchronized (mPackages) { 23361 final int N = mPackages.size(); 23362 final ArrayList<String> list = new ArrayList<>(N); 23363 for (int i = 0; i < N; i++) { 23364 list.add(mPackages.keyAt(i)); 23365 } 23366 final PackageList packageList = new PackageList(list, observer); 23367 if (observer != null) { 23368 mPackageListObservers.add(packageList); 23369 } 23370 return packageList; 23371 } 23372 } 23373 23374 @Override 23375 public void removePackageListObserver(PackageListObserver observer) { 23376 synchronized (mPackages) { 23377 mPackageListObservers.remove(observer); 23378 } 23379 } 23380 23381 @Override 23382 public PackageParser.Package getDisabledPackage(String packageName) { 23383 synchronized (mPackages) { 23384 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 23385 return (ps != null) ? ps.pkg : null; 23386 } 23387 } 23388 23389 @Override 23390 public String getKnownPackageName(int knownPackage, int userId) { 23391 switch(knownPackage) { 23392 case PackageManagerInternal.PACKAGE_BROWSER: 23393 return getDefaultBrowserPackageName(userId); 23394 case PackageManagerInternal.PACKAGE_INSTALLER: 23395 return mRequiredInstallerPackage; 23396 case PackageManagerInternal.PACKAGE_SETUP_WIZARD: 23397 return mSetupWizardPackage; 23398 case PackageManagerInternal.PACKAGE_SYSTEM: 23399 return "android"; 23400 case PackageManagerInternal.PACKAGE_VERIFIER: 23401 return mRequiredVerifierPackage; 23402 } 23403 return null; 23404 } 23405 23406 @Override 23407 public boolean isResolveActivityComponent(ComponentInfo component) { 23408 return mResolveActivity.packageName.equals(component.packageName) 23409 && mResolveActivity.name.equals(component.name); 23410 } 23411 23412 @Override 23413 public void setLocationPackagesProvider(PackagesProvider provider) { 23414 mDefaultPermissionPolicy.setLocationPackagesProvider(provider); 23415 } 23416 23417 @Override 23418 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23419 mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider); 23420 } 23421 23422 @Override 23423 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23424 mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider); 23425 } 23426 23427 @Override 23428 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23429 mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider); 23430 } 23431 23432 @Override 23433 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23434 mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider); 23435 } 23436 23437 @Override 23438 public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) { 23439 mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider); 23440 } 23441 23442 @Override 23443 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23444 mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider); 23445 } 23446 23447 @Override 23448 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23449 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId); 23450 } 23451 23452 @Override 23453 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23454 synchronized (mPackages) { 23455 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23456 } 23457 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId); 23458 } 23459 23460 @Override 23461 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23462 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager( 23463 packageName, userId); 23464 } 23465 23466 @Override 23467 public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) { 23468 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp( 23469 packageName, userId); 23470 } 23471 23472 @Override 23473 public void setKeepUninstalledPackages(final List<String> packageList) { 23474 Preconditions.checkNotNull(packageList); 23475 List<String> removedFromList = null; 23476 synchronized (mPackages) { 23477 if (mKeepUninstalledPackages != null) { 23478 final int packagesCount = mKeepUninstalledPackages.size(); 23479 for (int i = 0; i < packagesCount; i++) { 23480 String oldPackage = mKeepUninstalledPackages.get(i); 23481 if (packageList != null && packageList.contains(oldPackage)) { 23482 continue; 23483 } 23484 if (removedFromList == null) { 23485 removedFromList = new ArrayList<>(); 23486 } 23487 removedFromList.add(oldPackage); 23488 } 23489 } 23490 mKeepUninstalledPackages = new ArrayList<>(packageList); 23491 if (removedFromList != null) { 23492 final int removedCount = removedFromList.size(); 23493 for (int i = 0; i < removedCount; i++) { 23494 deletePackageIfUnusedLPr(removedFromList.get(i)); 23495 } 23496 } 23497 } 23498 } 23499 23500 @Override 23501 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23502 synchronized (mPackages) { 23503 return mPermissionManager.isPermissionsReviewRequired( 23504 mPackages.get(packageName), userId); 23505 } 23506 } 23507 23508 @Override 23509 public PackageInfo getPackageInfo( 23510 String packageName, int flags, int filterCallingUid, int userId) { 23511 return PackageManagerService.this 23512 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 23513 flags, filterCallingUid, userId); 23514 } 23515 23516 @Override 23517 public int getPackageUid(String packageName, int flags, int userId) { 23518 return PackageManagerService.this 23519 .getPackageUid(packageName, flags, userId); 23520 } 23521 23522 @Override 23523 public ApplicationInfo getApplicationInfo( 23524 String packageName, int flags, int filterCallingUid, int userId) { 23525 return PackageManagerService.this 23526 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 23527 } 23528 23529 @Override 23530 public ActivityInfo getActivityInfo( 23531 ComponentName component, int flags, int filterCallingUid, int userId) { 23532 return PackageManagerService.this 23533 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 23534 } 23535 23536 @Override 23537 public List<ResolveInfo> queryIntentActivities( 23538 Intent intent, int flags, int filterCallingUid, int userId) { 23539 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23540 return PackageManagerService.this 23541 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 23542 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 23543 } 23544 23545 @Override 23546 public List<ResolveInfo> queryIntentServices( 23547 Intent intent, int flags, int callingUid, int userId) { 23548 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23549 return PackageManagerService.this 23550 .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid, 23551 false); 23552 } 23553 23554 @Override 23555 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23556 int userId) { 23557 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23558 } 23559 23560 @Override 23561 public void setDeviceAndProfileOwnerPackages( 23562 int deviceOwnerUserId, String deviceOwnerPackage, 23563 SparseArray<String> profileOwnerPackages) { 23564 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23565 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23566 } 23567 23568 @Override 23569 public boolean isPackageDataProtected(int userId, String packageName) { 23570 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23571 } 23572 23573 @Override 23574 public boolean isPackageEphemeral(int userId, String packageName) { 23575 synchronized (mPackages) { 23576 final PackageSetting ps = mSettings.mPackages.get(packageName); 23577 return ps != null ? ps.getInstantApp(userId) : false; 23578 } 23579 } 23580 23581 @Override 23582 public boolean wasPackageEverLaunched(String packageName, int userId) { 23583 synchronized (mPackages) { 23584 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23585 } 23586 } 23587 23588 @Override 23589 public void grantRuntimePermission(String packageName, String permName, int userId, 23590 boolean overridePolicy) { 23591 PackageManagerService.this.mPermissionManager.grantRuntimePermission( 23592 permName, packageName, overridePolicy, getCallingUid(), userId, 23593 mPermissionCallback); 23594 } 23595 23596 @Override 23597 public void revokeRuntimePermission(String packageName, String permName, int userId, 23598 boolean overridePolicy) { 23599 mPermissionManager.revokeRuntimePermission( 23600 permName, packageName, overridePolicy, getCallingUid(), userId, 23601 mPermissionCallback); 23602 } 23603 23604 @Override 23605 public String getNameForUid(int uid) { 23606 return PackageManagerService.this.getNameForUid(uid); 23607 } 23608 23609 @Override 23610 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23611 Intent origIntent, String resolvedType, String callingPackage, 23612 Bundle verificationBundle, int userId) { 23613 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23614 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 23615 userId); 23616 } 23617 23618 @Override 23619 public void grantEphemeralAccess(int userId, Intent intent, 23620 int targetAppId, int ephemeralAppId) { 23621 synchronized (mPackages) { 23622 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23623 targetAppId, ephemeralAppId); 23624 } 23625 } 23626 23627 @Override 23628 public boolean isInstantAppInstallerComponent(ComponentName component) { 23629 synchronized (mPackages) { 23630 return mInstantAppInstallerActivity != null 23631 && mInstantAppInstallerActivity.getComponentName().equals(component); 23632 } 23633 } 23634 23635 @Override 23636 public void pruneInstantApps() { 23637 mInstantAppRegistry.pruneInstantApps(); 23638 } 23639 23640 @Override 23641 public String getSetupWizardPackageName() { 23642 return mSetupWizardPackage; 23643 } 23644 23645 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23646 if (policy != null) { 23647 mExternalSourcesPolicy = policy; 23648 } 23649 } 23650 23651 @Override 23652 public boolean isPackagePersistent(String packageName) { 23653 synchronized (mPackages) { 23654 PackageParser.Package pkg = mPackages.get(packageName); 23655 return pkg != null 23656 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23657 | ApplicationInfo.FLAG_PERSISTENT)) == 23658 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23659 : false; 23660 } 23661 } 23662 23663 @Override 23664 public boolean isLegacySystemApp(Package pkg) { 23665 synchronized (mPackages) { 23666 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23667 return mPromoteSystemApps 23668 && ps.isSystem() 23669 && mExistingSystemPackages.contains(ps.name); 23670 } 23671 } 23672 23673 @Override 23674 public List<PackageInfo> getOverlayPackages(int userId) { 23675 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23676 synchronized (mPackages) { 23677 for (PackageParser.Package p : mPackages.values()) { 23678 if (p.mOverlayTarget != null) { 23679 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23680 if (pkg != null) { 23681 overlayPackages.add(pkg); 23682 } 23683 } 23684 } 23685 } 23686 return overlayPackages; 23687 } 23688 23689 @Override 23690 public List<String> getTargetPackageNames(int userId) { 23691 List<String> targetPackages = new ArrayList<>(); 23692 synchronized (mPackages) { 23693 for (PackageParser.Package p : mPackages.values()) { 23694 if (p.mOverlayTarget == null) { 23695 targetPackages.add(p.packageName); 23696 } 23697 } 23698 } 23699 return targetPackages; 23700 } 23701 23702 @Override 23703 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23704 @Nullable List<String> overlayPackageNames) { 23705 synchronized (mPackages) { 23706 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23707 Slog.e(TAG, "failed to find package " + targetPackageName); 23708 return false; 23709 } 23710 ArrayList<String> overlayPaths = null; 23711 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 23712 final int N = overlayPackageNames.size(); 23713 overlayPaths = new ArrayList<>(N); 23714 for (int i = 0; i < N; i++) { 23715 final String packageName = overlayPackageNames.get(i); 23716 final PackageParser.Package pkg = mPackages.get(packageName); 23717 if (pkg == null) { 23718 Slog.e(TAG, "failed to find package " + packageName); 23719 return false; 23720 } 23721 overlayPaths.add(pkg.baseCodePath); 23722 } 23723 } 23724 23725 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 23726 ps.setOverlayPaths(overlayPaths, userId); 23727 return true; 23728 } 23729 } 23730 23731 @Override 23732 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23733 int flags, int userId, boolean resolveForStart) { 23734 return resolveIntentInternal( 23735 intent, resolvedType, flags, userId, resolveForStart); 23736 } 23737 23738 @Override 23739 public ResolveInfo resolveService(Intent intent, String resolvedType, 23740 int flags, int userId, int callingUid) { 23741 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 23742 } 23743 23744 @Override 23745 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 23746 return PackageManagerService.this.resolveContentProviderInternal( 23747 name, flags, userId); 23748 } 23749 23750 @Override 23751 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23752 synchronized (mPackages) { 23753 mIsolatedOwners.put(isolatedUid, ownerUid); 23754 } 23755 } 23756 23757 @Override 23758 public void removeIsolatedUid(int isolatedUid) { 23759 synchronized (mPackages) { 23760 mIsolatedOwners.delete(isolatedUid); 23761 } 23762 } 23763 23764 @Override 23765 public int getUidTargetSdkVersion(int uid) { 23766 synchronized (mPackages) { 23767 return getUidTargetSdkVersionLockedLPr(uid); 23768 } 23769 } 23770 23771 @Override 23772 public int getPackageTargetSdkVersion(String packageName) { 23773 synchronized (mPackages) { 23774 return getPackageTargetSdkVersionLockedLPr(packageName); 23775 } 23776 } 23777 23778 @Override 23779 public boolean canAccessInstantApps(int callingUid, int userId) { 23780 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 23781 } 23782 23783 @Override 23784 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 23785 synchronized (mPackages) { 23786 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 23787 } 23788 } 23789 23790 @Override 23791 public void notifyPackageUse(String packageName, int reason) { 23792 synchronized (mPackages) { 23793 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 23794 } 23795 } 23796 } 23797 23798 @Override 23799 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23800 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23801 synchronized (mPackages) { 23802 final long identity = Binder.clearCallingIdentity(); 23803 try { 23804 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps( 23805 packageNames, userId); 23806 } finally { 23807 Binder.restoreCallingIdentity(identity); 23808 } 23809 } 23810 } 23811 23812 @Override 23813 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23814 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23815 synchronized (mPackages) { 23816 final long identity = Binder.clearCallingIdentity(); 23817 try { 23818 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices( 23819 packageNames, userId); 23820 } finally { 23821 Binder.restoreCallingIdentity(identity); 23822 } 23823 } 23824 } 23825 23826 private static void enforceSystemOrPhoneCaller(String tag) { 23827 int callingUid = Binder.getCallingUid(); 23828 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23829 throw new SecurityException( 23830 "Cannot call " + tag + " from UID " + callingUid); 23831 } 23832 } 23833 23834 boolean isHistoricalPackageUsageAvailable() { 23835 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23836 } 23837 23838 /** 23839 * Return a <b>copy</b> of the collection of packages known to the package manager. 23840 * @return A copy of the values of mPackages. 23841 */ 23842 Collection<PackageParser.Package> getPackages() { 23843 synchronized (mPackages) { 23844 return new ArrayList<>(mPackages.values()); 23845 } 23846 } 23847 23848 /** 23849 * Logs process start information (including base APK hash) to the security log. 23850 * @hide 23851 */ 23852 @Override 23853 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23854 String apkFile, int pid) { 23855 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23856 return; 23857 } 23858 if (!SecurityLog.isLoggingEnabled()) { 23859 return; 23860 } 23861 Bundle data = new Bundle(); 23862 data.putLong("startTimestamp", System.currentTimeMillis()); 23863 data.putString("processName", processName); 23864 data.putInt("uid", uid); 23865 data.putString("seinfo", seinfo); 23866 data.putString("apkFile", apkFile); 23867 data.putInt("pid", pid); 23868 Message msg = mProcessLoggingHandler.obtainMessage( 23869 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23870 msg.setData(data); 23871 mProcessLoggingHandler.sendMessage(msg); 23872 } 23873 23874 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23875 return mCompilerStats.getPackageStats(pkgName); 23876 } 23877 23878 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23879 return getOrCreateCompilerPackageStats(pkg.packageName); 23880 } 23881 23882 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23883 return mCompilerStats.getOrCreatePackageStats(pkgName); 23884 } 23885 23886 public void deleteCompilerPackageStats(String pkgName) { 23887 mCompilerStats.deletePackageStats(pkgName); 23888 } 23889 23890 @Override 23891 public int getInstallReason(String packageName, int userId) { 23892 final int callingUid = Binder.getCallingUid(); 23893 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23894 true /* requireFullPermission */, false /* checkShell */, 23895 "get install reason"); 23896 synchronized (mPackages) { 23897 final PackageSetting ps = mSettings.mPackages.get(packageName); 23898 if (filterAppAccessLPr(ps, callingUid, userId)) { 23899 return PackageManager.INSTALL_REASON_UNKNOWN; 23900 } 23901 if (ps != null) { 23902 return ps.getInstallReason(userId); 23903 } 23904 } 23905 return PackageManager.INSTALL_REASON_UNKNOWN; 23906 } 23907 23908 @Override 23909 public boolean canRequestPackageInstalls(String packageName, int userId) { 23910 return canRequestPackageInstallsInternal(packageName, 0, userId, 23911 true /* throwIfPermNotDeclared*/); 23912 } 23913 23914 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 23915 boolean throwIfPermNotDeclared) { 23916 int callingUid = Binder.getCallingUid(); 23917 int uid = getPackageUid(packageName, 0, userId); 23918 if (callingUid != uid && callingUid != Process.ROOT_UID 23919 && callingUid != Process.SYSTEM_UID) { 23920 throw new SecurityException( 23921 "Caller uid " + callingUid + " does not own package " + packageName); 23922 } 23923 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 23924 if (info == null) { 23925 return false; 23926 } 23927 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23928 return false; 23929 } 23930 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23931 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23932 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23933 if (throwIfPermNotDeclared) { 23934 throw new SecurityException("Need to declare " + appOpPermission 23935 + " to call this api"); 23936 } else { 23937 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 23938 return false; 23939 } 23940 } 23941 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23942 return false; 23943 } 23944 if (mExternalSourcesPolicy != null) { 23945 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23946 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23947 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23948 } 23949 } 23950 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23951 } 23952 23953 @Override 23954 public ComponentName getInstantAppResolverSettingsComponent() { 23955 return mInstantAppResolverSettingsComponent; 23956 } 23957 23958 @Override 23959 public ComponentName getInstantAppInstallerComponent() { 23960 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23961 return null; 23962 } 23963 return mInstantAppInstallerActivity == null 23964 ? null : mInstantAppInstallerActivity.getComponentName(); 23965 } 23966 23967 @Override 23968 public String getInstantAppAndroidId(String packageName, int userId) { 23969 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 23970 "getInstantAppAndroidId"); 23971 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 23972 true /* requireFullPermission */, false /* checkShell */, 23973 "getInstantAppAndroidId"); 23974 // Make sure the target is an Instant App. 23975 if (!isInstantApp(packageName, userId)) { 23976 return null; 23977 } 23978 synchronized (mPackages) { 23979 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 23980 } 23981 } 23982 23983 boolean canHaveOatDir(String packageName) { 23984 synchronized (mPackages) { 23985 PackageParser.Package p = mPackages.get(packageName); 23986 if (p == null) { 23987 return false; 23988 } 23989 return p.canHaveOatDir(); 23990 } 23991 } 23992 23993 private String getOatDir(PackageParser.Package pkg) { 23994 if (!pkg.canHaveOatDir()) { 23995 return null; 23996 } 23997 File codePath = new File(pkg.codePath); 23998 if (codePath.isDirectory()) { 23999 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 24000 } 24001 return null; 24002 } 24003 24004 void deleteOatArtifactsOfPackage(String packageName) { 24005 final String[] instructionSets; 24006 final List<String> codePaths; 24007 final String oatDir; 24008 final PackageParser.Package pkg; 24009 synchronized (mPackages) { 24010 pkg = mPackages.get(packageName); 24011 } 24012 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 24013 codePaths = pkg.getAllCodePaths(); 24014 oatDir = getOatDir(pkg); 24015 24016 for (String codePath : codePaths) { 24017 for (String isa : instructionSets) { 24018 try { 24019 mInstaller.deleteOdex(codePath, isa, oatDir); 24020 } catch (InstallerException e) { 24021 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 24022 } 24023 } 24024 } 24025 } 24026 24027 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 24028 Set<String> unusedPackages = new HashSet<>(); 24029 long currentTimeInMillis = System.currentTimeMillis(); 24030 synchronized (mPackages) { 24031 for (PackageParser.Package pkg : mPackages.values()) { 24032 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 24033 if (ps == null) { 24034 continue; 24035 } 24036 PackageDexUsage.PackageUseInfo packageUseInfo = 24037 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 24038 if (PackageManagerServiceUtils 24039 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 24040 downgradeTimeThresholdMillis, packageUseInfo, 24041 pkg.getLatestPackageUseTimeInMills(), 24042 pkg.getLatestForegroundPackageUseTimeInMills())) { 24043 unusedPackages.add(pkg.packageName); 24044 } 24045 } 24046 } 24047 return unusedPackages; 24048 } 24049 24050 @Override 24051 public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning, 24052 int userId) { 24053 final int callingUid = Binder.getCallingUid(); 24054 final int callingAppId = UserHandle.getAppId(callingUid); 24055 24056 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24057 true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo"); 24058 24059 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24060 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24061 throw new SecurityException("Caller must have the " 24062 + SET_HARMFUL_APP_WARNINGS + " permission."); 24063 } 24064 24065 synchronized(mPackages) { 24066 mSettings.setHarmfulAppWarningLPw(packageName, warning, userId); 24067 scheduleWritePackageRestrictionsLocked(userId); 24068 } 24069 } 24070 24071 @Nullable 24072 @Override 24073 public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) { 24074 final int callingUid = Binder.getCallingUid(); 24075 final int callingAppId = UserHandle.getAppId(callingUid); 24076 24077 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24078 true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo"); 24079 24080 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24081 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24082 throw new SecurityException("Caller must have the " 24083 + SET_HARMFUL_APP_WARNINGS + " permission."); 24084 } 24085 24086 synchronized(mPackages) { 24087 return mSettings.getHarmfulAppWarningLPr(packageName, userId); 24088 } 24089 } 24090} 24091 24092interface PackageSender { 24093 /** 24094 * @param userIds User IDs where the action occurred on a full application 24095 * @param instantUserIds User IDs where the action occurred on an instant application 24096 */ 24097 void sendPackageBroadcast(final String action, final String pkg, 24098 final Bundle extras, final int flags, final String targetPkg, 24099 final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds); 24100 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 24101 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds); 24102 void notifyPackageAdded(String packageName); 24103 void notifyPackageRemoved(String packageName); 24104} 24105