PackageManagerService.java revision 3d70a03aa9e10382f385da0a26592d56eaf9cc96
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.DELETE_PACKAGES; 20import static android.Manifest.permission.INSTALL_PACKAGES; 21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS; 22import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 25import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 31import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 39import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_NEWER_SDK; 51import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 53import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 55import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 56import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 57import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 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.verifySignatures; 112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE; 113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS; 114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 115 116import android.Manifest; 117import android.annotation.IntDef; 118import android.annotation.NonNull; 119import android.annotation.Nullable; 120import android.app.ActivityManager; 121import android.app.AppOpsManager; 122import android.app.IActivityManager; 123import android.app.ResourcesManager; 124import android.app.admin.IDevicePolicyManager; 125import android.app.admin.SecurityLog; 126import android.app.backup.IBackupManager; 127import android.content.BroadcastReceiver; 128import android.content.ComponentName; 129import android.content.ContentResolver; 130import android.content.Context; 131import android.content.IIntentReceiver; 132import android.content.Intent; 133import android.content.IntentFilter; 134import android.content.IntentSender; 135import android.content.IntentSender.SendIntentException; 136import android.content.ServiceConnection; 137import android.content.pm.ActivityInfo; 138import android.content.pm.ApplicationInfo; 139import android.content.pm.AppsQueryHelper; 140import android.content.pm.AuxiliaryResolveInfo; 141import android.content.pm.ChangedPackages; 142import android.content.pm.ComponentInfo; 143import android.content.pm.FallbackCategoryProvider; 144import android.content.pm.FeatureInfo; 145import android.content.pm.IDexModuleRegisterCallback; 146import android.content.pm.IOnPermissionsChangeListener; 147import android.content.pm.IPackageDataObserver; 148import android.content.pm.IPackageDeleteObserver; 149import android.content.pm.IPackageDeleteObserver2; 150import android.content.pm.IPackageInstallObserver2; 151import android.content.pm.IPackageInstaller; 152import android.content.pm.IPackageManager; 153import android.content.pm.IPackageManagerNative; 154import android.content.pm.IPackageMoveObserver; 155import android.content.pm.IPackageStatsObserver; 156import android.content.pm.InstantAppInfo; 157import android.content.pm.InstantAppRequest; 158import android.content.pm.InstantAppResolveInfo; 159import android.content.pm.InstrumentationInfo; 160import android.content.pm.IntentFilterVerificationInfo; 161import android.content.pm.KeySet; 162import android.content.pm.PackageCleanItem; 163import android.content.pm.PackageInfo; 164import android.content.pm.PackageInfoLite; 165import android.content.pm.PackageInstaller; 166import android.content.pm.PackageList; 167import android.content.pm.PackageManager; 168import android.content.pm.PackageManagerInternal; 169import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 170import android.content.pm.PackageManager.PackageInfoFlags; 171import android.content.pm.PackageManagerInternal.PackageListObserver; 172import android.content.pm.PackageParser; 173import android.content.pm.PackageParser.ActivityIntentInfo; 174import android.content.pm.PackageParser.Package; 175import android.content.pm.PackageParser.PackageLite; 176import android.content.pm.PackageParser.PackageParserException; 177import android.content.pm.PackageParser.ParseFlags; 178import android.content.pm.PackageParser.ServiceIntentInfo; 179import android.content.pm.PackageStats; 180import android.content.pm.PackageUserState; 181import android.content.pm.ParceledListSlice; 182import android.content.pm.PermissionGroupInfo; 183import android.content.pm.PermissionInfo; 184import android.content.pm.ProviderInfo; 185import android.content.pm.ResolveInfo; 186import android.content.pm.ServiceInfo; 187import android.content.pm.SharedLibraryInfo; 188import android.content.pm.Signature; 189import android.content.pm.UserInfo; 190import android.content.pm.VerifierDeviceIdentity; 191import android.content.pm.VerifierInfo; 192import android.content.pm.VersionedPackage; 193import android.content.pm.dex.IArtManager; 194import android.content.res.Resources; 195import android.database.ContentObserver; 196import android.graphics.Bitmap; 197import android.hardware.display.DisplayManager; 198import android.net.Uri; 199import android.os.Binder; 200import android.os.Build; 201import android.os.Bundle; 202import android.os.Debug; 203import android.os.Environment; 204import android.os.Environment.UserEnvironment; 205import android.os.FileUtils; 206import android.os.Handler; 207import android.os.IBinder; 208import android.os.Looper; 209import android.os.Message; 210import android.os.Parcel; 211import android.os.ParcelFileDescriptor; 212import android.os.PatternMatcher; 213import android.os.Process; 214import android.os.RemoteCallbackList; 215import android.os.RemoteException; 216import android.os.ResultReceiver; 217import android.os.SELinux; 218import android.os.ServiceManager; 219import android.os.ShellCallback; 220import android.os.SystemClock; 221import android.os.SystemProperties; 222import android.os.Trace; 223import android.os.UserHandle; 224import android.os.UserManager; 225import android.os.UserManagerInternal; 226import android.os.storage.IStorageManager; 227import android.os.storage.StorageEventListener; 228import android.os.storage.StorageManager; 229import android.os.storage.StorageManagerInternal; 230import android.os.storage.VolumeInfo; 231import android.os.storage.VolumeRecord; 232import android.provider.Settings.Global; 233import android.provider.Settings.Secure; 234import android.security.KeyStore; 235import android.security.SystemKeyStore; 236import android.service.pm.PackageServiceDumpProto; 237import android.system.ErrnoException; 238import android.system.Os; 239import android.text.TextUtils; 240import android.text.format.DateUtils; 241import android.util.ArrayMap; 242import android.util.ArraySet; 243import android.util.Base64; 244import android.util.DisplayMetrics; 245import android.util.EventLog; 246import android.util.ExceptionUtils; 247import android.util.Log; 248import android.util.LogPrinter; 249import android.util.LongSparseArray; 250import android.util.LongSparseLongArray; 251import android.util.MathUtils; 252import android.util.PackageUtils; 253import android.util.Pair; 254import android.util.PrintStreamPrinter; 255import android.util.Slog; 256import android.util.SparseArray; 257import android.util.SparseBooleanArray; 258import android.util.SparseIntArray; 259import android.util.TimingsTraceLog; 260import android.util.Xml; 261import android.util.jar.StrictJarFile; 262import android.util.proto.ProtoOutputStream; 263import android.view.Display; 264 265import com.android.internal.R; 266import com.android.internal.annotations.GuardedBy; 267import com.android.internal.app.IMediaContainerService; 268import com.android.internal.app.ResolverActivity; 269import com.android.internal.content.NativeLibraryHelper; 270import com.android.internal.content.PackageHelper; 271import com.android.internal.logging.MetricsLogger; 272import com.android.internal.os.IParcelFileDescriptorFactory; 273import com.android.internal.os.SomeArgs; 274import com.android.internal.os.Zygote; 275import com.android.internal.telephony.CarrierAppUtils; 276import com.android.internal.util.ArrayUtils; 277import com.android.internal.util.ConcurrentUtils; 278import com.android.internal.util.DumpUtils; 279import com.android.internal.util.FastXmlSerializer; 280import com.android.internal.util.IndentingPrintWriter; 281import com.android.internal.util.Preconditions; 282import com.android.internal.util.XmlUtils; 283import com.android.server.AttributeCache; 284import com.android.server.DeviceIdleController; 285import com.android.server.EventLogTags; 286import com.android.server.FgThread; 287import com.android.server.IntentResolver; 288import com.android.server.LocalServices; 289import com.android.server.LockGuard; 290import com.android.server.ServiceThread; 291import com.android.server.SystemConfig; 292import com.android.server.SystemServerInitThreadPool; 293import com.android.server.Watchdog; 294import com.android.server.net.NetworkPolicyManagerInternal; 295import com.android.server.pm.Installer.InstallerException; 296import com.android.server.pm.Settings.DatabaseVersion; 297import com.android.server.pm.Settings.VersionInfo; 298import com.android.server.pm.dex.ArtManagerService; 299import com.android.server.pm.dex.DexLogger; 300import com.android.server.pm.dex.DexManager; 301import com.android.server.pm.dex.DexoptOptions; 302import com.android.server.pm.dex.PackageDexUsage; 303import com.android.server.pm.permission.BasePermission; 304import com.android.server.pm.permission.DefaultPermissionGrantPolicy; 305import com.android.server.pm.permission.PermissionManagerService; 306import com.android.server.pm.permission.PermissionManagerInternal; 307import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback; 308import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback; 309import com.android.server.pm.permission.PermissionsState; 310import com.android.server.pm.permission.PermissionsState.PermissionState; 311import com.android.server.storage.DeviceStorageMonitorInternal; 312 313import dalvik.system.CloseGuard; 314import dalvik.system.VMRuntime; 315 316import libcore.io.IoUtils; 317 318import org.xmlpull.v1.XmlPullParser; 319import org.xmlpull.v1.XmlPullParserException; 320import org.xmlpull.v1.XmlSerializer; 321 322import java.io.BufferedOutputStream; 323import java.io.ByteArrayInputStream; 324import java.io.ByteArrayOutputStream; 325import java.io.File; 326import java.io.FileDescriptor; 327import java.io.FileInputStream; 328import java.io.FileOutputStream; 329import java.io.FilenameFilter; 330import java.io.IOException; 331import java.io.PrintWriter; 332import java.lang.annotation.Retention; 333import java.lang.annotation.RetentionPolicy; 334import java.nio.charset.StandardCharsets; 335import java.security.DigestInputStream; 336import java.security.MessageDigest; 337import java.security.NoSuchAlgorithmException; 338import java.security.PublicKey; 339import java.security.SecureRandom; 340import java.security.cert.Certificate; 341import java.security.cert.CertificateException; 342import java.util.ArrayList; 343import java.util.Arrays; 344import java.util.Collection; 345import java.util.Collections; 346import java.util.Comparator; 347import java.util.HashMap; 348import java.util.HashSet; 349import java.util.Iterator; 350import java.util.LinkedHashSet; 351import java.util.List; 352import java.util.Map; 353import java.util.Objects; 354import java.util.Set; 355import java.util.concurrent.CountDownLatch; 356import java.util.concurrent.Future; 357import java.util.concurrent.TimeUnit; 358import java.util.concurrent.atomic.AtomicBoolean; 359import java.util.concurrent.atomic.AtomicInteger; 360 361/** 362 * Keep track of all those APKs everywhere. 363 * <p> 364 * Internally there are two important locks: 365 * <ul> 366 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 367 * and other related state. It is a fine-grained lock that should only be held 368 * momentarily, as it's one of the most contended locks in the system. 369 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 370 * operations typically involve heavy lifting of application data on disk. Since 371 * {@code installd} is single-threaded, and it's operations can often be slow, 372 * this lock should never be acquired while already holding {@link #mPackages}. 373 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 374 * holding {@link #mInstallLock}. 375 * </ul> 376 * Many internal methods rely on the caller to hold the appropriate locks, and 377 * this contract is expressed through method name suffixes: 378 * <ul> 379 * <li>fooLI(): the caller must hold {@link #mInstallLock} 380 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 381 * being modified must be frozen 382 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 383 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 384 * </ul> 385 * <p> 386 * Because this class is very central to the platform's security; please run all 387 * CTS and unit tests whenever making modifications: 388 * 389 * <pre> 390 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 391 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 392 * </pre> 393 */ 394public class PackageManagerService extends IPackageManager.Stub 395 implements PackageSender { 396 static final String TAG = "PackageManager"; 397 public static final boolean DEBUG_SETTINGS = false; 398 static final boolean DEBUG_PREFERRED = false; 399 static final boolean DEBUG_UPGRADE = false; 400 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 401 private static final boolean DEBUG_BACKUP = false; 402 public static final boolean DEBUG_INSTALL = false; 403 public static final boolean DEBUG_REMOVE = false; 404 private static final boolean DEBUG_BROADCASTS = false; 405 private static final boolean DEBUG_SHOW_INFO = false; 406 private static final boolean DEBUG_PACKAGE_INFO = false; 407 private static final boolean DEBUG_INTENT_MATCHING = false; 408 public static final boolean DEBUG_PACKAGE_SCANNING = false; 409 private static final boolean DEBUG_VERIFY = false; 410 private static final boolean DEBUG_FILTERS = false; 411 public static final boolean DEBUG_PERMISSIONS = false; 412 private static final boolean DEBUG_SHARED_LIBRARIES = false; 413 public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE; 414 415 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 416 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 417 // user, but by default initialize to this. 418 public static final boolean DEBUG_DEXOPT = false; 419 420 private static final boolean DEBUG_ABI_SELECTION = false; 421 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 422 private static final boolean DEBUG_TRIAGED_MISSING = false; 423 private static final boolean DEBUG_APP_DATA = false; 424 425 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 426 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 427 428 private static final boolean HIDE_EPHEMERAL_APIS = false; 429 430 private static final boolean ENABLE_FREE_CACHE_V2 = 431 SystemProperties.getBoolean("fw.free_cache_v2", true); 432 433 private static final int RADIO_UID = Process.PHONE_UID; 434 private static final int LOG_UID = Process.LOG_UID; 435 private static final int NFC_UID = Process.NFC_UID; 436 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 437 private static final int SHELL_UID = Process.SHELL_UID; 438 439 // Suffix used during package installation when copying/moving 440 // package apks to install directory. 441 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 442 443 static final int SCAN_NO_DEX = 1<<0; 444 static final int SCAN_UPDATE_SIGNATURE = 1<<1; 445 static final int SCAN_NEW_INSTALL = 1<<2; 446 static final int SCAN_UPDATE_TIME = 1<<3; 447 static final int SCAN_BOOTING = 1<<4; 448 static final int SCAN_TRUSTED_OVERLAY = 1<<5; 449 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6; 450 static final int SCAN_REQUIRE_KNOWN = 1<<7; 451 static final int SCAN_MOVE = 1<<8; 452 static final int SCAN_INITIAL = 1<<9; 453 static final int SCAN_CHECK_ONLY = 1<<10; 454 static final int SCAN_DONT_KILL_APP = 1<<11; 455 static final int SCAN_IGNORE_FROZEN = 1<<12; 456 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13; 457 static final int SCAN_AS_INSTANT_APP = 1<<14; 458 static final int SCAN_AS_FULL_APP = 1<<15; 459 static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16; 460 static final int SCAN_AS_SYSTEM = 1<<17; 461 static final int SCAN_AS_PRIVILEGED = 1<<18; 462 static final int SCAN_AS_OEM = 1<<19; 463 static final int SCAN_AS_VENDOR = 1<<20; 464 465 @IntDef(flag = true, prefix = { "SCAN_" }, value = { 466 SCAN_NO_DEX, 467 SCAN_UPDATE_SIGNATURE, 468 SCAN_NEW_INSTALL, 469 SCAN_UPDATE_TIME, 470 SCAN_BOOTING, 471 SCAN_TRUSTED_OVERLAY, 472 SCAN_DELETE_DATA_ON_FAILURES, 473 SCAN_REQUIRE_KNOWN, 474 SCAN_MOVE, 475 SCAN_INITIAL, 476 SCAN_CHECK_ONLY, 477 SCAN_DONT_KILL_APP, 478 SCAN_IGNORE_FROZEN, 479 SCAN_FIRST_BOOT_OR_UPGRADE, 480 SCAN_AS_INSTANT_APP, 481 SCAN_AS_FULL_APP, 482 SCAN_AS_VIRTUAL_PRELOAD, 483 }) 484 @Retention(RetentionPolicy.SOURCE) 485 public @interface ScanFlags {} 486 487 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 488 /** Extension of the compressed packages */ 489 public final static String COMPRESSED_EXTENSION = ".gz"; 490 /** Suffix of stub packages on the system partition */ 491 public final static String STUB_SUFFIX = "-Stub"; 492 493 private static final int[] EMPTY_INT_ARRAY = new int[0]; 494 495 private static final int TYPE_UNKNOWN = 0; 496 private static final int TYPE_ACTIVITY = 1; 497 private static final int TYPE_RECEIVER = 2; 498 private static final int TYPE_SERVICE = 3; 499 private static final int TYPE_PROVIDER = 4; 500 @IntDef(prefix = { "TYPE_" }, value = { 501 TYPE_UNKNOWN, 502 TYPE_ACTIVITY, 503 TYPE_RECEIVER, 504 TYPE_SERVICE, 505 TYPE_PROVIDER, 506 }) 507 @Retention(RetentionPolicy.SOURCE) 508 public @interface ComponentType {} 509 510 /** 511 * Timeout (in milliseconds) after which the watchdog should declare that 512 * our handler thread is wedged. The usual default for such things is one 513 * minute but we sometimes do very lengthy I/O operations on this thread, 514 * such as installing multi-gigabyte applications, so ours needs to be longer. 515 */ 516 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 517 518 /** 519 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 520 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 521 * settings entry if available, otherwise we use the hardcoded default. If it's been 522 * more than this long since the last fstrim, we force one during the boot sequence. 523 * 524 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 525 * one gets run at the next available charging+idle time. This final mandatory 526 * no-fstrim check kicks in only of the other scheduling criteria is never met. 527 */ 528 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 529 530 /** 531 * Whether verification is enabled by default. 532 */ 533 private static final boolean DEFAULT_VERIFY_ENABLE = true; 534 535 /** 536 * The default maximum time to wait for the verification agent to return in 537 * milliseconds. 538 */ 539 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 540 541 /** 542 * The default response for package verification timeout. 543 * 544 * This can be either PackageManager.VERIFICATION_ALLOW or 545 * PackageManager.VERIFICATION_REJECT. 546 */ 547 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 548 549 public static final String PLATFORM_PACKAGE_NAME = "android"; 550 551 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 552 553 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 554 DEFAULT_CONTAINER_PACKAGE, 555 "com.android.defcontainer.DefaultContainerService"); 556 557 private static final String KILL_APP_REASON_GIDS_CHANGED = 558 "permission grant or revoke changed gids"; 559 560 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 561 "permissions revoked"; 562 563 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 564 565 private static final String PACKAGE_SCHEME = "package"; 566 567 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 568 569 private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob"; 570 571 /** Canonical intent used to identify what counts as a "web browser" app */ 572 private static final Intent sBrowserIntent; 573 static { 574 sBrowserIntent = new Intent(); 575 sBrowserIntent.setAction(Intent.ACTION_VIEW); 576 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 577 sBrowserIntent.setData(Uri.parse("http:")); 578 } 579 580 /** 581 * The set of all protected actions [i.e. those actions for which a high priority 582 * intent filter is disallowed]. 583 */ 584 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 585 static { 586 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 587 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 588 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 589 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 590 } 591 592 // Compilation reasons. 593 public static final int REASON_FIRST_BOOT = 0; 594 public static final int REASON_BOOT = 1; 595 public static final int REASON_INSTALL = 2; 596 public static final int REASON_BACKGROUND_DEXOPT = 3; 597 public static final int REASON_AB_OTA = 4; 598 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5; 599 public static final int REASON_SHARED = 6; 600 601 public static final int REASON_LAST = REASON_SHARED; 602 603 /** 604 * Version number for the package parser cache. Increment this whenever the format or 605 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 606 */ 607 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 608 609 /** 610 * Whether the package parser cache is enabled. 611 */ 612 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 613 614 /** 615 * Permissions required in order to receive instant application lifecycle broadcasts. 616 */ 617 private static final String[] INSTANT_APP_BROADCAST_PERMISSION = 618 new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS }; 619 620 final ServiceThread mHandlerThread; 621 622 final PackageHandler mHandler; 623 624 private final ProcessLoggingHandler mProcessLoggingHandler; 625 626 /** 627 * Messages for {@link #mHandler} that need to wait for system ready before 628 * being dispatched. 629 */ 630 private ArrayList<Message> mPostSystemReadyMessages; 631 632 final int mSdkVersion = Build.VERSION.SDK_INT; 633 634 final Context mContext; 635 final boolean mFactoryTest; 636 final boolean mOnlyCore; 637 final DisplayMetrics mMetrics; 638 final int mDefParseFlags; 639 final String[] mSeparateProcesses; 640 final boolean mIsUpgrade; 641 final boolean mIsPreNUpgrade; 642 final boolean mIsPreNMR1Upgrade; 643 644 // Have we told the Activity Manager to whitelist the default container service by uid yet? 645 @GuardedBy("mPackages") 646 boolean mDefaultContainerWhitelisted = false; 647 648 @GuardedBy("mPackages") 649 private boolean mDexOptDialogShown; 650 651 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 652 // LOCK HELD. Can be called with mInstallLock held. 653 @GuardedBy("mInstallLock") 654 final Installer mInstaller; 655 656 /** Directory where installed applications are stored */ 657 private static final File sAppInstallDir = 658 new File(Environment.getDataDirectory(), "app"); 659 /** Directory where installed application's 32-bit native libraries are copied. */ 660 private static final File sAppLib32InstallDir = 661 new File(Environment.getDataDirectory(), "app-lib"); 662 /** Directory where code and non-resource assets of forward-locked applications are stored */ 663 private static final File sDrmAppPrivateInstallDir = 664 new File(Environment.getDataDirectory(), "app-private"); 665 666 // ---------------------------------------------------------------- 667 668 // Lock for state used when installing and doing other long running 669 // operations. Methods that must be called with this lock held have 670 // the suffix "LI". 671 final Object mInstallLock = new Object(); 672 673 // ---------------------------------------------------------------- 674 675 // Keys are String (package name), values are Package. This also serves 676 // as the lock for the global state. Methods that must be called with 677 // this lock held have the prefix "LP". 678 @GuardedBy("mPackages") 679 final ArrayMap<String, PackageParser.Package> mPackages = 680 new ArrayMap<String, PackageParser.Package>(); 681 682 final ArrayMap<String, Set<String>> mKnownCodebase = 683 new ArrayMap<String, Set<String>>(); 684 685 // Keys are isolated uids and values are the uid of the application 686 // that created the isolated proccess. 687 @GuardedBy("mPackages") 688 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 689 690 /** 691 * Tracks new system packages [received in an OTA] that we expect to 692 * find updated user-installed versions. Keys are package name, values 693 * are package location. 694 */ 695 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 696 /** 697 * Tracks high priority intent filters for protected actions. During boot, certain 698 * filter actions are protected and should never be allowed to have a high priority 699 * intent filter for them. However, there is one, and only one exception -- the 700 * setup wizard. It must be able to define a high priority intent filter for these 701 * actions to ensure there are no escapes from the wizard. We need to delay processing 702 * of these during boot as we need to look at all of the system packages in order 703 * to know which component is the setup wizard. 704 */ 705 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 706 /** 707 * Whether or not processing protected filters should be deferred. 708 */ 709 private boolean mDeferProtectedFilters = true; 710 711 /** 712 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 713 */ 714 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 715 /** 716 * Whether or not system app permissions should be promoted from install to runtime. 717 */ 718 boolean mPromoteSystemApps; 719 720 @GuardedBy("mPackages") 721 final Settings mSettings; 722 723 /** 724 * Set of package names that are currently "frozen", which means active 725 * surgery is being done on the code/data for that package. The platform 726 * will refuse to launch frozen packages to avoid race conditions. 727 * 728 * @see PackageFreezer 729 */ 730 @GuardedBy("mPackages") 731 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 732 733 final ProtectedPackages mProtectedPackages; 734 735 @GuardedBy("mLoadedVolumes") 736 final ArraySet<String> mLoadedVolumes = new ArraySet<>(); 737 738 boolean mFirstBoot; 739 740 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 741 742 @GuardedBy("mAvailableFeatures") 743 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 744 745 private final InstantAppRegistry mInstantAppRegistry; 746 747 @GuardedBy("mPackages") 748 int mChangedPackagesSequenceNumber; 749 /** 750 * List of changed [installed, removed or updated] packages. 751 * mapping from user id -> sequence number -> package name 752 */ 753 @GuardedBy("mPackages") 754 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 755 /** 756 * The sequence number of the last change to a package. 757 * mapping from user id -> package name -> sequence number 758 */ 759 @GuardedBy("mPackages") 760 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 761 762 @GuardedBy("mPackages") 763 final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>(); 764 765 class PackageParserCallback implements PackageParser.Callback { 766 @Override public final boolean hasFeature(String feature) { 767 return PackageManagerService.this.hasSystemFeature(feature, 0); 768 } 769 770 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 771 Collection<PackageParser.Package> allPackages, String targetPackageName) { 772 List<PackageParser.Package> overlayPackages = null; 773 for (PackageParser.Package p : allPackages) { 774 if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) { 775 if (overlayPackages == null) { 776 overlayPackages = new ArrayList<PackageParser.Package>(); 777 } 778 overlayPackages.add(p); 779 } 780 } 781 if (overlayPackages != null) { 782 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 783 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 784 return p1.mOverlayPriority - p2.mOverlayPriority; 785 } 786 }; 787 Collections.sort(overlayPackages, cmp); 788 } 789 return overlayPackages; 790 } 791 792 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 793 String targetPackageName, String targetPath) { 794 if ("android".equals(targetPackageName)) { 795 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 796 // native AssetManager. 797 return null; 798 } 799 List<PackageParser.Package> overlayPackages = 800 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 801 if (overlayPackages == null || overlayPackages.isEmpty()) { 802 return null; 803 } 804 List<String> overlayPathList = null; 805 for (PackageParser.Package overlayPackage : overlayPackages) { 806 if (targetPath == null) { 807 if (overlayPathList == null) { 808 overlayPathList = new ArrayList<String>(); 809 } 810 overlayPathList.add(overlayPackage.baseCodePath); 811 continue; 812 } 813 814 try { 815 // Creates idmaps for system to parse correctly the Android manifest of the 816 // target package. 817 // 818 // OverlayManagerService will update each of them with a correct gid from its 819 // target package app id. 820 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 821 UserHandle.getSharedAppGid( 822 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 823 if (overlayPathList == null) { 824 overlayPathList = new ArrayList<String>(); 825 } 826 overlayPathList.add(overlayPackage.baseCodePath); 827 } catch (InstallerException e) { 828 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 829 overlayPackage.baseCodePath); 830 } 831 } 832 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 833 } 834 835 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 836 synchronized (mPackages) { 837 return getStaticOverlayPathsLocked( 838 mPackages.values(), targetPackageName, targetPath); 839 } 840 } 841 842 @Override public final String[] getOverlayApks(String targetPackageName) { 843 return getStaticOverlayPaths(targetPackageName, null); 844 } 845 846 @Override public final String[] getOverlayPaths(String targetPackageName, 847 String targetPath) { 848 return getStaticOverlayPaths(targetPackageName, targetPath); 849 } 850 } 851 852 class ParallelPackageParserCallback extends PackageParserCallback { 853 List<PackageParser.Package> mOverlayPackages = null; 854 855 void findStaticOverlayPackages() { 856 synchronized (mPackages) { 857 for (PackageParser.Package p : mPackages.values()) { 858 if (p.mIsStaticOverlay) { 859 if (mOverlayPackages == null) { 860 mOverlayPackages = new ArrayList<PackageParser.Package>(); 861 } 862 mOverlayPackages.add(p); 863 } 864 } 865 } 866 } 867 868 @Override 869 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 870 // We can trust mOverlayPackages without holding mPackages because package uninstall 871 // can't happen while running parallel parsing. 872 // Moreover holding mPackages on each parsing thread causes dead-lock. 873 return mOverlayPackages == null ? null : 874 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 875 } 876 } 877 878 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 879 final ParallelPackageParserCallback mParallelPackageParserCallback = 880 new ParallelPackageParserCallback(); 881 882 public static final class SharedLibraryEntry { 883 public final @Nullable String path; 884 public final @Nullable String apk; 885 public final @NonNull SharedLibraryInfo info; 886 887 SharedLibraryEntry(String _path, String _apk, String name, long version, int type, 888 String declaringPackageName, long declaringPackageVersionCode) { 889 path = _path; 890 apk = _apk; 891 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 892 declaringPackageName, declaringPackageVersionCode), null); 893 } 894 } 895 896 // Currently known shared libraries. 897 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 898 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 899 new ArrayMap<>(); 900 901 // All available activities, for your resolving pleasure. 902 final ActivityIntentResolver mActivities = 903 new ActivityIntentResolver(); 904 905 // All available receivers, for your resolving pleasure. 906 final ActivityIntentResolver mReceivers = 907 new ActivityIntentResolver(); 908 909 // All available services, for your resolving pleasure. 910 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 911 912 // All available providers, for your resolving pleasure. 913 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 914 915 // Mapping from provider base names (first directory in content URI codePath) 916 // to the provider information. 917 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 918 new ArrayMap<String, PackageParser.Provider>(); 919 920 // Mapping from instrumentation class names to info about them. 921 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 922 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 923 924 // Packages whose data we have transfered into another package, thus 925 // should no longer exist. 926 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 927 928 // Broadcast actions that are only available to the system. 929 @GuardedBy("mProtectedBroadcasts") 930 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>(); 931 932 /** List of packages waiting for verification. */ 933 final SparseArray<PackageVerificationState> mPendingVerification 934 = new SparseArray<PackageVerificationState>(); 935 936 final PackageInstallerService mInstallerService; 937 938 final ArtManagerService mArtManagerService; 939 940 private final PackageDexOptimizer mPackageDexOptimizer; 941 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 942 // is used by other apps). 943 private final DexManager mDexManager; 944 945 private AtomicInteger mNextMoveId = new AtomicInteger(); 946 private final MoveCallbacks mMoveCallbacks; 947 948 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 949 950 // Cache of users who need badging. 951 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 952 953 /** Token for keys in mPendingVerification. */ 954 private int mPendingVerificationToken = 0; 955 956 volatile boolean mSystemReady; 957 volatile boolean mSafeMode; 958 volatile boolean mHasSystemUidErrors; 959 private volatile boolean mEphemeralAppsDisabled; 960 961 ApplicationInfo mAndroidApplication; 962 final ActivityInfo mResolveActivity = new ActivityInfo(); 963 final ResolveInfo mResolveInfo = new ResolveInfo(); 964 ComponentName mResolveComponentName; 965 PackageParser.Package mPlatformPackage; 966 ComponentName mCustomResolverComponentName; 967 968 boolean mResolverReplaced = false; 969 970 private final @Nullable ComponentName mIntentFilterVerifierComponent; 971 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 972 973 private int mIntentFilterVerificationToken = 0; 974 975 /** The service connection to the ephemeral resolver */ 976 final EphemeralResolverConnection mInstantAppResolverConnection; 977 /** Component used to show resolver settings for Instant Apps */ 978 final ComponentName mInstantAppResolverSettingsComponent; 979 980 /** Activity used to install instant applications */ 981 ActivityInfo mInstantAppInstallerActivity; 982 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 983 984 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 985 = new SparseArray<IntentFilterVerificationState>(); 986 987 // TODO remove this and go through mPermissonManager directly 988 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 989 private final PermissionManagerInternal mPermissionManager; 990 991 // List of packages names to keep cached, even if they are uninstalled for all users 992 private List<String> mKeepUninstalledPackages; 993 994 private UserManagerInternal mUserManagerInternal; 995 996 private DeviceIdleController.LocalService mDeviceIdleController; 997 998 private File mCacheDir; 999 1000 private Future<?> mPrepareAppDataFuture; 1001 1002 private static class IFVerificationParams { 1003 PackageParser.Package pkg; 1004 boolean replacing; 1005 int userId; 1006 int verifierUid; 1007 1008 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1009 int _userId, int _verifierUid) { 1010 pkg = _pkg; 1011 replacing = _replacing; 1012 userId = _userId; 1013 replacing = _replacing; 1014 verifierUid = _verifierUid; 1015 } 1016 } 1017 1018 private interface IntentFilterVerifier<T extends IntentFilter> { 1019 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1020 T filter, String packageName); 1021 void startVerifications(int userId); 1022 void receiveVerificationResponse(int verificationId); 1023 } 1024 1025 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1026 private Context mContext; 1027 private ComponentName mIntentFilterVerifierComponent; 1028 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1029 1030 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1031 mContext = context; 1032 mIntentFilterVerifierComponent = verifierComponent; 1033 } 1034 1035 private String getDefaultScheme() { 1036 return IntentFilter.SCHEME_HTTPS; 1037 } 1038 1039 @Override 1040 public void startVerifications(int userId) { 1041 // Launch verifications requests 1042 int count = mCurrentIntentFilterVerifications.size(); 1043 for (int n=0; n<count; n++) { 1044 int verificationId = mCurrentIntentFilterVerifications.get(n); 1045 final IntentFilterVerificationState ivs = 1046 mIntentFilterVerificationStates.get(verificationId); 1047 1048 String packageName = ivs.getPackageName(); 1049 1050 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1051 final int filterCount = filters.size(); 1052 ArraySet<String> domainsSet = new ArraySet<>(); 1053 for (int m=0; m<filterCount; m++) { 1054 PackageParser.ActivityIntentInfo filter = filters.get(m); 1055 domainsSet.addAll(filter.getHostsList()); 1056 } 1057 synchronized (mPackages) { 1058 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1059 packageName, domainsSet) != null) { 1060 scheduleWriteSettingsLocked(); 1061 } 1062 } 1063 sendVerificationRequest(verificationId, ivs); 1064 } 1065 mCurrentIntentFilterVerifications.clear(); 1066 } 1067 1068 private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) { 1069 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1070 verificationIntent.putExtra( 1071 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1072 verificationId); 1073 verificationIntent.putExtra( 1074 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1075 getDefaultScheme()); 1076 verificationIntent.putExtra( 1077 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1078 ivs.getHostsString()); 1079 verificationIntent.putExtra( 1080 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1081 ivs.getPackageName()); 1082 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1083 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1084 1085 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1086 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1087 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1088 UserHandle.USER_SYSTEM, true, "intent filter verifier"); 1089 1090 mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM); 1091 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1092 "Sending IntentFilter verification broadcast"); 1093 } 1094 1095 public void receiveVerificationResponse(int verificationId) { 1096 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1097 1098 final boolean verified = ivs.isVerified(); 1099 1100 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1101 final int count = filters.size(); 1102 if (DEBUG_DOMAIN_VERIFICATION) { 1103 Slog.i(TAG, "Received verification response " + verificationId 1104 + " for " + count + " filters, verified=" + verified); 1105 } 1106 for (int n=0; n<count; n++) { 1107 PackageParser.ActivityIntentInfo filter = filters.get(n); 1108 filter.setVerified(verified); 1109 1110 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1111 + " verified with result:" + verified + " and hosts:" 1112 + ivs.getHostsString()); 1113 } 1114 1115 mIntentFilterVerificationStates.remove(verificationId); 1116 1117 final String packageName = ivs.getPackageName(); 1118 IntentFilterVerificationInfo ivi = null; 1119 1120 synchronized (mPackages) { 1121 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1122 } 1123 if (ivi == null) { 1124 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1125 + verificationId + " packageName:" + packageName); 1126 return; 1127 } 1128 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1129 "Updating IntentFilterVerificationInfo for package " + packageName 1130 +" verificationId:" + verificationId); 1131 1132 synchronized (mPackages) { 1133 if (verified) { 1134 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1135 } else { 1136 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1137 } 1138 scheduleWriteSettingsLocked(); 1139 1140 final int userId = ivs.getUserId(); 1141 if (userId != UserHandle.USER_ALL) { 1142 final int userStatus = 1143 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1144 1145 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1146 boolean needUpdate = false; 1147 1148 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1149 // already been set by the User thru the Disambiguation dialog 1150 switch (userStatus) { 1151 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1152 if (verified) { 1153 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1154 } else { 1155 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1156 } 1157 needUpdate = true; 1158 break; 1159 1160 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1161 if (verified) { 1162 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1163 needUpdate = true; 1164 } 1165 break; 1166 1167 default: 1168 // Nothing to do 1169 } 1170 1171 if (needUpdate) { 1172 mSettings.updateIntentFilterVerificationStatusLPw( 1173 packageName, updatedStatus, userId); 1174 scheduleWritePackageRestrictionsLocked(userId); 1175 } 1176 } 1177 } 1178 } 1179 1180 @Override 1181 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1182 ActivityIntentInfo filter, String packageName) { 1183 if (!hasValidDomains(filter)) { 1184 return false; 1185 } 1186 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1187 if (ivs == null) { 1188 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1189 packageName); 1190 } 1191 if (DEBUG_DOMAIN_VERIFICATION) { 1192 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1193 } 1194 ivs.addFilter(filter); 1195 return true; 1196 } 1197 1198 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1199 int userId, int verificationId, String packageName) { 1200 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1201 verifierUid, userId, packageName); 1202 ivs.setPendingState(); 1203 synchronized (mPackages) { 1204 mIntentFilterVerificationStates.append(verificationId, ivs); 1205 mCurrentIntentFilterVerifications.add(verificationId); 1206 } 1207 return ivs; 1208 } 1209 } 1210 1211 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1212 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1213 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1214 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1215 } 1216 1217 // Set of pending broadcasts for aggregating enable/disable of components. 1218 static class PendingPackageBroadcasts { 1219 // for each user id, a map of <package name -> components within that package> 1220 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1221 1222 public PendingPackageBroadcasts() { 1223 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1224 } 1225 1226 public ArrayList<String> get(int userId, String packageName) { 1227 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1228 return packages.get(packageName); 1229 } 1230 1231 public void put(int userId, String packageName, ArrayList<String> components) { 1232 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1233 packages.put(packageName, components); 1234 } 1235 1236 public void remove(int userId, String packageName) { 1237 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1238 if (packages != null) { 1239 packages.remove(packageName); 1240 } 1241 } 1242 1243 public void remove(int userId) { 1244 mUidMap.remove(userId); 1245 } 1246 1247 public int userIdCount() { 1248 return mUidMap.size(); 1249 } 1250 1251 public int userIdAt(int n) { 1252 return mUidMap.keyAt(n); 1253 } 1254 1255 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1256 return mUidMap.get(userId); 1257 } 1258 1259 public int size() { 1260 // total number of pending broadcast entries across all userIds 1261 int num = 0; 1262 for (int i = 0; i< mUidMap.size(); i++) { 1263 num += mUidMap.valueAt(i).size(); 1264 } 1265 return num; 1266 } 1267 1268 public void clear() { 1269 mUidMap.clear(); 1270 } 1271 1272 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1273 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1274 if (map == null) { 1275 map = new ArrayMap<String, ArrayList<String>>(); 1276 mUidMap.put(userId, map); 1277 } 1278 return map; 1279 } 1280 } 1281 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1282 1283 // Service Connection to remote media container service to copy 1284 // package uri's from external media onto secure containers 1285 // or internal storage. 1286 private IMediaContainerService mContainerService = null; 1287 1288 static final int SEND_PENDING_BROADCAST = 1; 1289 static final int MCS_BOUND = 3; 1290 static final int END_COPY = 4; 1291 static final int INIT_COPY = 5; 1292 static final int MCS_UNBIND = 6; 1293 static final int START_CLEANING_PACKAGE = 7; 1294 static final int FIND_INSTALL_LOC = 8; 1295 static final int POST_INSTALL = 9; 1296 static final int MCS_RECONNECT = 10; 1297 static final int MCS_GIVE_UP = 11; 1298 static final int WRITE_SETTINGS = 13; 1299 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1300 static final int PACKAGE_VERIFIED = 15; 1301 static final int CHECK_PENDING_VERIFICATION = 16; 1302 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1303 static final int INTENT_FILTER_VERIFIED = 18; 1304 static final int WRITE_PACKAGE_LIST = 19; 1305 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1306 1307 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1308 1309 // Delay time in millisecs 1310 static final int BROADCAST_DELAY = 10 * 1000; 1311 1312 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1313 2 * 60 * 60 * 1000L; /* two hours */ 1314 1315 static UserManagerService sUserManager; 1316 1317 // Stores a list of users whose package restrictions file needs to be updated 1318 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1319 1320 final private DefaultContainerConnection mDefContainerConn = 1321 new DefaultContainerConnection(); 1322 class DefaultContainerConnection implements ServiceConnection { 1323 public void onServiceConnected(ComponentName name, IBinder service) { 1324 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1325 final IMediaContainerService imcs = IMediaContainerService.Stub 1326 .asInterface(Binder.allowBlocking(service)); 1327 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1328 } 1329 1330 public void onServiceDisconnected(ComponentName name) { 1331 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1332 } 1333 } 1334 1335 // Recordkeeping of restore-after-install operations that are currently in flight 1336 // between the Package Manager and the Backup Manager 1337 static class PostInstallData { 1338 public InstallArgs args; 1339 public PackageInstalledInfo res; 1340 1341 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1342 args = _a; 1343 res = _r; 1344 } 1345 } 1346 1347 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1348 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1349 1350 // XML tags for backup/restore of various bits of state 1351 private static final String TAG_PREFERRED_BACKUP = "pa"; 1352 private static final String TAG_DEFAULT_APPS = "da"; 1353 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1354 1355 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1356 private static final String TAG_ALL_GRANTS = "rt-grants"; 1357 private static final String TAG_GRANT = "grant"; 1358 private static final String ATTR_PACKAGE_NAME = "pkg"; 1359 1360 private static final String TAG_PERMISSION = "perm"; 1361 private static final String ATTR_PERMISSION_NAME = "name"; 1362 private static final String ATTR_IS_GRANTED = "g"; 1363 private static final String ATTR_USER_SET = "set"; 1364 private static final String ATTR_USER_FIXED = "fixed"; 1365 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1366 1367 // System/policy permission grants are not backed up 1368 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1369 FLAG_PERMISSION_POLICY_FIXED 1370 | FLAG_PERMISSION_SYSTEM_FIXED 1371 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1372 1373 // And we back up these user-adjusted states 1374 private static final int USER_RUNTIME_GRANT_MASK = 1375 FLAG_PERMISSION_USER_SET 1376 | FLAG_PERMISSION_USER_FIXED 1377 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1378 1379 final @Nullable String mRequiredVerifierPackage; 1380 final @NonNull String mRequiredInstallerPackage; 1381 final @NonNull String mRequiredUninstallerPackage; 1382 final @Nullable String mSetupWizardPackage; 1383 final @Nullable String mStorageManagerPackage; 1384 final @NonNull String mServicesSystemSharedLibraryPackageName; 1385 final @NonNull String mSharedSystemSharedLibraryPackageName; 1386 1387 private final PackageUsage mPackageUsage = new PackageUsage(); 1388 private final CompilerStats mCompilerStats = new CompilerStats(); 1389 1390 class PackageHandler extends Handler { 1391 private boolean mBound = false; 1392 final ArrayList<HandlerParams> mPendingInstalls = 1393 new ArrayList<HandlerParams>(); 1394 1395 private boolean connectToService() { 1396 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1397 " DefaultContainerService"); 1398 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1399 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1400 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1401 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1402 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1403 mBound = true; 1404 return true; 1405 } 1406 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1407 return false; 1408 } 1409 1410 private void disconnectService() { 1411 mContainerService = null; 1412 mBound = false; 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1414 mContext.unbindService(mDefContainerConn); 1415 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1416 } 1417 1418 PackageHandler(Looper looper) { 1419 super(looper); 1420 } 1421 1422 public void handleMessage(Message msg) { 1423 try { 1424 doHandleMessage(msg); 1425 } finally { 1426 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1427 } 1428 } 1429 1430 void doHandleMessage(Message msg) { 1431 switch (msg.what) { 1432 case INIT_COPY: { 1433 HandlerParams params = (HandlerParams) msg.obj; 1434 int idx = mPendingInstalls.size(); 1435 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1436 // If a bind was already initiated we dont really 1437 // need to do anything. The pending install 1438 // will be processed later on. 1439 if (!mBound) { 1440 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1441 System.identityHashCode(mHandler)); 1442 // If this is the only one pending we might 1443 // have to bind to the service again. 1444 if (!connectToService()) { 1445 Slog.e(TAG, "Failed to bind to media container service"); 1446 params.serviceError(); 1447 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1448 System.identityHashCode(mHandler)); 1449 if (params.traceMethod != null) { 1450 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1451 params.traceCookie); 1452 } 1453 return; 1454 } else { 1455 // Once we bind to the service, the first 1456 // pending request will be processed. 1457 mPendingInstalls.add(idx, params); 1458 } 1459 } else { 1460 mPendingInstalls.add(idx, params); 1461 // Already bound to the service. Just make 1462 // sure we trigger off processing the first request. 1463 if (idx == 0) { 1464 mHandler.sendEmptyMessage(MCS_BOUND); 1465 } 1466 } 1467 break; 1468 } 1469 case MCS_BOUND: { 1470 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1471 if (msg.obj != null) { 1472 mContainerService = (IMediaContainerService) msg.obj; 1473 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1474 System.identityHashCode(mHandler)); 1475 } 1476 if (mContainerService == null) { 1477 if (!mBound) { 1478 // Something seriously wrong since we are not bound and we are not 1479 // waiting for connection. Bail out. 1480 Slog.e(TAG, "Cannot bind to media container service"); 1481 for (HandlerParams params : mPendingInstalls) { 1482 // Indicate service bind error 1483 params.serviceError(); 1484 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1485 System.identityHashCode(params)); 1486 if (params.traceMethod != null) { 1487 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1488 params.traceMethod, params.traceCookie); 1489 } 1490 return; 1491 } 1492 mPendingInstalls.clear(); 1493 } else { 1494 Slog.w(TAG, "Waiting to connect to media container service"); 1495 } 1496 } else if (mPendingInstalls.size() > 0) { 1497 HandlerParams params = mPendingInstalls.get(0); 1498 if (params != null) { 1499 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1500 System.identityHashCode(params)); 1501 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1502 if (params.startCopy()) { 1503 // We are done... look for more work or to 1504 // go idle. 1505 if (DEBUG_SD_INSTALL) Log.i(TAG, 1506 "Checking for more work or unbind..."); 1507 // Delete pending install 1508 if (mPendingInstalls.size() > 0) { 1509 mPendingInstalls.remove(0); 1510 } 1511 if (mPendingInstalls.size() == 0) { 1512 if (mBound) { 1513 if (DEBUG_SD_INSTALL) Log.i(TAG, 1514 "Posting delayed MCS_UNBIND"); 1515 removeMessages(MCS_UNBIND); 1516 Message ubmsg = obtainMessage(MCS_UNBIND); 1517 // Unbind after a little delay, to avoid 1518 // continual thrashing. 1519 sendMessageDelayed(ubmsg, 10000); 1520 } 1521 } else { 1522 // There are more pending requests in queue. 1523 // Just post MCS_BOUND message to trigger processing 1524 // of next pending install. 1525 if (DEBUG_SD_INSTALL) Log.i(TAG, 1526 "Posting MCS_BOUND for next work"); 1527 mHandler.sendEmptyMessage(MCS_BOUND); 1528 } 1529 } 1530 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1531 } 1532 } else { 1533 // Should never happen ideally. 1534 Slog.w(TAG, "Empty queue"); 1535 } 1536 break; 1537 } 1538 case MCS_RECONNECT: { 1539 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1540 if (mPendingInstalls.size() > 0) { 1541 if (mBound) { 1542 disconnectService(); 1543 } 1544 if (!connectToService()) { 1545 Slog.e(TAG, "Failed to bind to media container service"); 1546 for (HandlerParams params : mPendingInstalls) { 1547 // Indicate service bind error 1548 params.serviceError(); 1549 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1550 System.identityHashCode(params)); 1551 } 1552 mPendingInstalls.clear(); 1553 } 1554 } 1555 break; 1556 } 1557 case MCS_UNBIND: { 1558 // If there is no actual work left, then time to unbind. 1559 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1560 1561 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1562 if (mBound) { 1563 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1564 1565 disconnectService(); 1566 } 1567 } else if (mPendingInstalls.size() > 0) { 1568 // There are more pending requests in queue. 1569 // Just post MCS_BOUND message to trigger processing 1570 // of next pending install. 1571 mHandler.sendEmptyMessage(MCS_BOUND); 1572 } 1573 1574 break; 1575 } 1576 case MCS_GIVE_UP: { 1577 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1578 HandlerParams params = mPendingInstalls.remove(0); 1579 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1580 System.identityHashCode(params)); 1581 break; 1582 } 1583 case SEND_PENDING_BROADCAST: { 1584 String packages[]; 1585 ArrayList<String> components[]; 1586 int size = 0; 1587 int uids[]; 1588 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1589 synchronized (mPackages) { 1590 if (mPendingBroadcasts == null) { 1591 return; 1592 } 1593 size = mPendingBroadcasts.size(); 1594 if (size <= 0) { 1595 // Nothing to be done. Just return 1596 return; 1597 } 1598 packages = new String[size]; 1599 components = new ArrayList[size]; 1600 uids = new int[size]; 1601 int i = 0; // filling out the above arrays 1602 1603 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1604 int packageUserId = mPendingBroadcasts.userIdAt(n); 1605 Iterator<Map.Entry<String, ArrayList<String>>> it 1606 = mPendingBroadcasts.packagesForUserId(packageUserId) 1607 .entrySet().iterator(); 1608 while (it.hasNext() && i < size) { 1609 Map.Entry<String, ArrayList<String>> ent = it.next(); 1610 packages[i] = ent.getKey(); 1611 components[i] = ent.getValue(); 1612 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1613 uids[i] = (ps != null) 1614 ? UserHandle.getUid(packageUserId, ps.appId) 1615 : -1; 1616 i++; 1617 } 1618 } 1619 size = i; 1620 mPendingBroadcasts.clear(); 1621 } 1622 // Send broadcasts 1623 for (int i = 0; i < size; i++) { 1624 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1625 } 1626 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1627 break; 1628 } 1629 case START_CLEANING_PACKAGE: { 1630 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1631 final String packageName = (String)msg.obj; 1632 final int userId = msg.arg1; 1633 final boolean andCode = msg.arg2 != 0; 1634 synchronized (mPackages) { 1635 if (userId == UserHandle.USER_ALL) { 1636 int[] users = sUserManager.getUserIds(); 1637 for (int user : users) { 1638 mSettings.addPackageToCleanLPw( 1639 new PackageCleanItem(user, packageName, andCode)); 1640 } 1641 } else { 1642 mSettings.addPackageToCleanLPw( 1643 new PackageCleanItem(userId, packageName, andCode)); 1644 } 1645 } 1646 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1647 startCleaningPackages(); 1648 } break; 1649 case POST_INSTALL: { 1650 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1651 1652 PostInstallData data = mRunningInstalls.get(msg.arg1); 1653 final boolean didRestore = (msg.arg2 != 0); 1654 mRunningInstalls.delete(msg.arg1); 1655 1656 if (data != null) { 1657 InstallArgs args = data.args; 1658 PackageInstalledInfo parentRes = data.res; 1659 1660 final boolean grantPermissions = (args.installFlags 1661 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1662 final boolean killApp = (args.installFlags 1663 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1664 final boolean virtualPreload = ((args.installFlags 1665 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 1666 final String[] grantedPermissions = args.installGrantPermissions; 1667 1668 // Handle the parent package 1669 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1670 virtualPreload, grantedPermissions, didRestore, 1671 args.installerPackageName, args.observer); 1672 1673 // Handle the child packages 1674 final int childCount = (parentRes.addedChildPackages != null) 1675 ? parentRes.addedChildPackages.size() : 0; 1676 for (int i = 0; i < childCount; i++) { 1677 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1678 handlePackagePostInstall(childRes, grantPermissions, killApp, 1679 virtualPreload, grantedPermissions, false /*didRestore*/, 1680 args.installerPackageName, args.observer); 1681 } 1682 1683 // Log tracing if needed 1684 if (args.traceMethod != null) { 1685 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1686 args.traceCookie); 1687 } 1688 } else { 1689 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1690 } 1691 1692 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1693 } break; 1694 case WRITE_SETTINGS: { 1695 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1696 synchronized (mPackages) { 1697 removeMessages(WRITE_SETTINGS); 1698 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1699 mSettings.writeLPr(); 1700 mDirtyUsers.clear(); 1701 } 1702 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1703 } break; 1704 case WRITE_PACKAGE_RESTRICTIONS: { 1705 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1706 synchronized (mPackages) { 1707 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1708 for (int userId : mDirtyUsers) { 1709 mSettings.writePackageRestrictionsLPr(userId); 1710 } 1711 mDirtyUsers.clear(); 1712 } 1713 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1714 } break; 1715 case WRITE_PACKAGE_LIST: { 1716 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1717 synchronized (mPackages) { 1718 removeMessages(WRITE_PACKAGE_LIST); 1719 mSettings.writePackageListLPr(msg.arg1); 1720 } 1721 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1722 } break; 1723 case CHECK_PENDING_VERIFICATION: { 1724 final int verificationId = msg.arg1; 1725 final PackageVerificationState state = mPendingVerification.get(verificationId); 1726 1727 if ((state != null) && !state.timeoutExtended()) { 1728 final InstallArgs args = state.getInstallArgs(); 1729 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1730 1731 Slog.i(TAG, "Verification timed out for " + originUri); 1732 mPendingVerification.remove(verificationId); 1733 1734 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1735 1736 final UserHandle user = args.getUser(); 1737 if (getDefaultVerificationResponse(user) 1738 == PackageManager.VERIFICATION_ALLOW) { 1739 Slog.i(TAG, "Continuing with installation of " + originUri); 1740 state.setVerifierResponse(Binder.getCallingUid(), 1741 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1742 broadcastPackageVerified(verificationId, originUri, 1743 PackageManager.VERIFICATION_ALLOW, user); 1744 try { 1745 ret = args.copyApk(mContainerService, true); 1746 } catch (RemoteException e) { 1747 Slog.e(TAG, "Could not contact the ContainerService"); 1748 } 1749 } else { 1750 broadcastPackageVerified(verificationId, originUri, 1751 PackageManager.VERIFICATION_REJECT, user); 1752 } 1753 1754 Trace.asyncTraceEnd( 1755 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1756 1757 processPendingInstall(args, ret); 1758 mHandler.sendEmptyMessage(MCS_UNBIND); 1759 } 1760 break; 1761 } 1762 case PACKAGE_VERIFIED: { 1763 final int verificationId = msg.arg1; 1764 1765 final PackageVerificationState state = mPendingVerification.get(verificationId); 1766 if (state == null) { 1767 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1768 break; 1769 } 1770 1771 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1772 1773 state.setVerifierResponse(response.callerUid, response.code); 1774 1775 if (state.isVerificationComplete()) { 1776 mPendingVerification.remove(verificationId); 1777 1778 final InstallArgs args = state.getInstallArgs(); 1779 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1780 1781 int ret; 1782 if (state.isInstallAllowed()) { 1783 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1784 broadcastPackageVerified(verificationId, originUri, 1785 response.code, state.getInstallArgs().getUser()); 1786 try { 1787 ret = args.copyApk(mContainerService, true); 1788 } catch (RemoteException e) { 1789 Slog.e(TAG, "Could not contact the ContainerService"); 1790 } 1791 } else { 1792 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1793 } 1794 1795 Trace.asyncTraceEnd( 1796 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1797 1798 processPendingInstall(args, ret); 1799 mHandler.sendEmptyMessage(MCS_UNBIND); 1800 } 1801 1802 break; 1803 } 1804 case START_INTENT_FILTER_VERIFICATIONS: { 1805 IFVerificationParams params = (IFVerificationParams) msg.obj; 1806 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1807 params.replacing, params.pkg); 1808 break; 1809 } 1810 case INTENT_FILTER_VERIFIED: { 1811 final int verificationId = msg.arg1; 1812 1813 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1814 verificationId); 1815 if (state == null) { 1816 Slog.w(TAG, "Invalid IntentFilter verification token " 1817 + verificationId + " received"); 1818 break; 1819 } 1820 1821 final int userId = state.getUserId(); 1822 1823 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1824 "Processing IntentFilter verification with token:" 1825 + verificationId + " and userId:" + userId); 1826 1827 final IntentFilterVerificationResponse response = 1828 (IntentFilterVerificationResponse) msg.obj; 1829 1830 state.setVerifierResponse(response.callerUid, response.code); 1831 1832 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1833 "IntentFilter verification with token:" + verificationId 1834 + " and userId:" + userId 1835 + " is settings verifier response with response code:" 1836 + response.code); 1837 1838 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1839 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1840 + response.getFailedDomainsString()); 1841 } 1842 1843 if (state.isVerificationComplete()) { 1844 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1845 } else { 1846 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1847 "IntentFilter verification with token:" + verificationId 1848 + " was not said to be complete"); 1849 } 1850 1851 break; 1852 } 1853 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1854 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1855 mInstantAppResolverConnection, 1856 (InstantAppRequest) msg.obj, 1857 mInstantAppInstallerActivity, 1858 mHandler); 1859 } 1860 } 1861 } 1862 } 1863 1864 private PermissionCallback mPermissionCallback = new PermissionCallback() { 1865 @Override 1866 public void onGidsChanged(int appId, int userId) { 1867 mHandler.post(new Runnable() { 1868 @Override 1869 public void run() { 1870 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 1871 } 1872 }); 1873 } 1874 @Override 1875 public void onPermissionGranted(int uid, int userId) { 1876 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1877 1878 // Not critical; if this is lost, the application has to request again. 1879 synchronized (mPackages) { 1880 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 1881 } 1882 } 1883 @Override 1884 public void onInstallPermissionGranted() { 1885 synchronized (mPackages) { 1886 scheduleWriteSettingsLocked(); 1887 } 1888 } 1889 @Override 1890 public void onPermissionRevoked(int uid, int userId) { 1891 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1892 1893 synchronized (mPackages) { 1894 // Critical; after this call the application should never have the permission 1895 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 1896 } 1897 1898 final int appId = UserHandle.getAppId(uid); 1899 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 1900 } 1901 @Override 1902 public void onInstallPermissionRevoked() { 1903 synchronized (mPackages) { 1904 scheduleWriteSettingsLocked(); 1905 } 1906 } 1907 @Override 1908 public void onPermissionUpdated(int[] updatedUserIds, boolean sync) { 1909 synchronized (mPackages) { 1910 for (int userId : updatedUserIds) { 1911 mSettings.writeRuntimePermissionsForUserLPr(userId, sync); 1912 } 1913 } 1914 } 1915 @Override 1916 public void onInstallPermissionUpdated() { 1917 synchronized (mPackages) { 1918 scheduleWriteSettingsLocked(); 1919 } 1920 } 1921 @Override 1922 public void onPermissionRemoved() { 1923 synchronized (mPackages) { 1924 mSettings.writeLPr(); 1925 } 1926 } 1927 }; 1928 1929 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1930 boolean killApp, boolean virtualPreload, String[] grantedPermissions, 1931 boolean launchedForRestore, String installerPackage, 1932 IPackageInstallObserver2 installObserver) { 1933 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1934 // Send the removed broadcasts 1935 if (res.removedInfo != null) { 1936 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1937 } 1938 1939 // Now that we successfully installed the package, grant runtime 1940 // permissions if requested before broadcasting the install. Also 1941 // for legacy apps in permission review mode we clear the permission 1942 // review flag which is used to emulate runtime permissions for 1943 // legacy apps. 1944 if (grantPermissions) { 1945 final int callingUid = Binder.getCallingUid(); 1946 mPermissionManager.grantRequestedRuntimePermissions( 1947 res.pkg, res.newUsers, grantedPermissions, callingUid, 1948 mPermissionCallback); 1949 } 1950 1951 final boolean update = res.removedInfo != null 1952 && res.removedInfo.removedPackage != null; 1953 final String installerPackageName = 1954 res.installerPackageName != null 1955 ? res.installerPackageName 1956 : res.removedInfo != null 1957 ? res.removedInfo.installerPackageName 1958 : null; 1959 1960 // If this is the first time we have child packages for a disabled privileged 1961 // app that had no children, we grant requested runtime permissions to the new 1962 // children if the parent on the system image had them already granted. 1963 if (res.pkg.parentPackage != null) { 1964 final int callingUid = Binder.getCallingUid(); 1965 mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage( 1966 res.pkg, callingUid, mPermissionCallback); 1967 } 1968 1969 synchronized (mPackages) { 1970 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1971 } 1972 1973 final String packageName = res.pkg.applicationInfo.packageName; 1974 1975 // Determine the set of users who are adding this package for 1976 // the first time vs. those who are seeing an update. 1977 int[] firstUserIds = EMPTY_INT_ARRAY; 1978 int[] firstInstantUserIds = EMPTY_INT_ARRAY; 1979 int[] updateUserIds = EMPTY_INT_ARRAY; 1980 int[] instantUserIds = EMPTY_INT_ARRAY; 1981 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1982 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1983 for (int newUser : res.newUsers) { 1984 final boolean isInstantApp = ps.getInstantApp(newUser); 1985 if (allNewUsers) { 1986 if (isInstantApp) { 1987 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 1988 } else { 1989 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 1990 } 1991 continue; 1992 } 1993 boolean isNew = true; 1994 for (int origUser : res.origUsers) { 1995 if (origUser == newUser) { 1996 isNew = false; 1997 break; 1998 } 1999 } 2000 if (isNew) { 2001 if (isInstantApp) { 2002 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 2003 } else { 2004 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 2005 } 2006 } else { 2007 if (isInstantApp) { 2008 instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser); 2009 } else { 2010 updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser); 2011 } 2012 } 2013 } 2014 2015 // Send installed broadcasts if the package is not a static shared lib. 2016 if (res.pkg.staticSharedLibName == null) { 2017 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 2018 2019 // Send added for users that see the package for the first time 2020 // sendPackageAddedForNewUsers also deals with system apps 2021 int appId = UserHandle.getAppId(res.uid); 2022 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 2023 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload, 2024 virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds); 2025 2026 // Send added for users that don't see the package for the first time 2027 Bundle extras = new Bundle(1); 2028 extras.putInt(Intent.EXTRA_UID, res.uid); 2029 if (update) { 2030 extras.putBoolean(Intent.EXTRA_REPLACING, true); 2031 } 2032 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2033 extras, 0 /*flags*/, 2034 null /*targetPackage*/, null /*finishedReceiver*/, 2035 updateUserIds, instantUserIds); 2036 if (installerPackageName != null) { 2037 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2038 extras, 0 /*flags*/, 2039 installerPackageName, null /*finishedReceiver*/, 2040 updateUserIds, instantUserIds); 2041 } 2042 2043 // Send replaced for users that don't see the package for the first time 2044 if (update) { 2045 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 2046 packageName, extras, 0 /*flags*/, 2047 null /*targetPackage*/, null /*finishedReceiver*/, 2048 updateUserIds, instantUserIds); 2049 if (installerPackageName != null) { 2050 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 2051 extras, 0 /*flags*/, 2052 installerPackageName, null /*finishedReceiver*/, 2053 updateUserIds, instantUserIds); 2054 } 2055 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 2056 null /*package*/, null /*extras*/, 0 /*flags*/, 2057 packageName /*targetPackage*/, 2058 null /*finishedReceiver*/, updateUserIds, instantUserIds); 2059 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 2060 // First-install and we did a restore, so we're responsible for the 2061 // first-launch broadcast. 2062 if (DEBUG_BACKUP) { 2063 Slog.i(TAG, "Post-restore of " + packageName 2064 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds)); 2065 } 2066 sendFirstLaunchBroadcast(packageName, installerPackage, 2067 firstUserIds, firstInstantUserIds); 2068 } 2069 2070 // Send broadcast package appeared if forward locked/external for all users 2071 // treat asec-hosted packages like removable media on upgrade 2072 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 2073 if (DEBUG_INSTALL) { 2074 Slog.i(TAG, "upgrading pkg " + res.pkg 2075 + " is ASEC-hosted -> AVAILABLE"); 2076 } 2077 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2078 ArrayList<String> pkgList = new ArrayList<>(1); 2079 pkgList.add(packageName); 2080 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2081 } 2082 } 2083 2084 // Work that needs to happen on first install within each user 2085 if (firstUserIds != null && firstUserIds.length > 0) { 2086 synchronized (mPackages) { 2087 for (int userId : firstUserIds) { 2088 // If this app is a browser and it's newly-installed for some 2089 // users, clear any default-browser state in those users. The 2090 // app's nature doesn't depend on the user, so we can just check 2091 // its browser nature in any user and generalize. 2092 if (packageIsBrowser(packageName, userId)) { 2093 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2094 } 2095 2096 // We may also need to apply pending (restored) runtime 2097 // permission grants within these users. 2098 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2099 } 2100 } 2101 } 2102 2103 if (allNewUsers && !update) { 2104 notifyPackageAdded(packageName); 2105 } 2106 2107 // Log current value of "unknown sources" setting 2108 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2109 getUnknownSourcesSettings()); 2110 2111 // Remove the replaced package's older resources safely now 2112 // We delete after a gc for applications on sdcard. 2113 if (res.removedInfo != null && res.removedInfo.args != null) { 2114 Runtime.getRuntime().gc(); 2115 synchronized (mInstallLock) { 2116 res.removedInfo.args.doPostDeleteLI(true); 2117 } 2118 } else { 2119 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2120 // and not block here. 2121 VMRuntime.getRuntime().requestConcurrentGC(); 2122 } 2123 2124 // Notify DexManager that the package was installed for new users. 2125 // The updated users should already be indexed and the package code paths 2126 // should not change. 2127 // Don't notify the manager for ephemeral apps as they are not expected to 2128 // survive long enough to benefit of background optimizations. 2129 for (int userId : firstUserIds) { 2130 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2131 // There's a race currently where some install events may interleave with an uninstall. 2132 // This can lead to package info being null (b/36642664). 2133 if (info != null) { 2134 mDexManager.notifyPackageInstalled(info, userId); 2135 } 2136 } 2137 } 2138 2139 // If someone is watching installs - notify them 2140 if (installObserver != null) { 2141 try { 2142 Bundle extras = extrasForInstallResult(res); 2143 installObserver.onPackageInstalled(res.name, res.returnCode, 2144 res.returnMsg, extras); 2145 } catch (RemoteException e) { 2146 Slog.i(TAG, "Observer no longer exists."); 2147 } 2148 } 2149 } 2150 2151 private StorageEventListener mStorageListener = new StorageEventListener() { 2152 @Override 2153 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2154 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2155 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2156 final String volumeUuid = vol.getFsUuid(); 2157 2158 // Clean up any users or apps that were removed or recreated 2159 // while this volume was missing 2160 sUserManager.reconcileUsers(volumeUuid); 2161 reconcileApps(volumeUuid); 2162 2163 // Clean up any install sessions that expired or were 2164 // cancelled while this volume was missing 2165 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2166 2167 loadPrivatePackages(vol); 2168 2169 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2170 unloadPrivatePackages(vol); 2171 } 2172 } 2173 } 2174 2175 @Override 2176 public void onVolumeForgotten(String fsUuid) { 2177 if (TextUtils.isEmpty(fsUuid)) { 2178 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2179 return; 2180 } 2181 2182 // Remove any apps installed on the forgotten volume 2183 synchronized (mPackages) { 2184 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2185 for (PackageSetting ps : packages) { 2186 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2187 deletePackageVersioned(new VersionedPackage(ps.name, 2188 PackageManager.VERSION_CODE_HIGHEST), 2189 new LegacyPackageDeleteObserver(null).getBinder(), 2190 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2191 // Try very hard to release any references to this package 2192 // so we don't risk the system server being killed due to 2193 // open FDs 2194 AttributeCache.instance().removePackage(ps.name); 2195 } 2196 2197 mSettings.onVolumeForgotten(fsUuid); 2198 mSettings.writeLPr(); 2199 } 2200 } 2201 }; 2202 2203 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2204 Bundle extras = null; 2205 switch (res.returnCode) { 2206 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2207 extras = new Bundle(); 2208 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2209 res.origPermission); 2210 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2211 res.origPackage); 2212 break; 2213 } 2214 case PackageManager.INSTALL_SUCCEEDED: { 2215 extras = new Bundle(); 2216 extras.putBoolean(Intent.EXTRA_REPLACING, 2217 res.removedInfo != null && res.removedInfo.removedPackage != null); 2218 break; 2219 } 2220 } 2221 return extras; 2222 } 2223 2224 void scheduleWriteSettingsLocked() { 2225 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2226 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2227 } 2228 } 2229 2230 void scheduleWritePackageListLocked(int userId) { 2231 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2232 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2233 msg.arg1 = userId; 2234 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2235 } 2236 } 2237 2238 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2239 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2240 scheduleWritePackageRestrictionsLocked(userId); 2241 } 2242 2243 void scheduleWritePackageRestrictionsLocked(int userId) { 2244 final int[] userIds = (userId == UserHandle.USER_ALL) 2245 ? sUserManager.getUserIds() : new int[]{userId}; 2246 for (int nextUserId : userIds) { 2247 if (!sUserManager.exists(nextUserId)) return; 2248 mDirtyUsers.add(nextUserId); 2249 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2250 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2251 } 2252 } 2253 } 2254 2255 public static PackageManagerService main(Context context, Installer installer, 2256 boolean factoryTest, boolean onlyCore) { 2257 // Self-check for initial settings. 2258 PackageManagerServiceCompilerMapping.checkProperties(); 2259 2260 PackageManagerService m = new PackageManagerService(context, installer, 2261 factoryTest, onlyCore); 2262 m.enableSystemUserPackages(); 2263 ServiceManager.addService("package", m); 2264 final PackageManagerNative pmn = m.new PackageManagerNative(); 2265 ServiceManager.addService("package_native", pmn); 2266 return m; 2267 } 2268 2269 private void enableSystemUserPackages() { 2270 if (!UserManager.isSplitSystemUser()) { 2271 return; 2272 } 2273 // For system user, enable apps based on the following conditions: 2274 // - app is whitelisted or belong to one of these groups: 2275 // -- system app which has no launcher icons 2276 // -- system app which has INTERACT_ACROSS_USERS permission 2277 // -- system IME app 2278 // - app is not in the blacklist 2279 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2280 Set<String> enableApps = new ArraySet<>(); 2281 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2282 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2283 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2284 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2285 enableApps.addAll(wlApps); 2286 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2287 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2288 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2289 enableApps.removeAll(blApps); 2290 Log.i(TAG, "Applications installed for system user: " + enableApps); 2291 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2292 UserHandle.SYSTEM); 2293 final int allAppsSize = allAps.size(); 2294 synchronized (mPackages) { 2295 for (int i = 0; i < allAppsSize; i++) { 2296 String pName = allAps.get(i); 2297 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2298 // Should not happen, but we shouldn't be failing if it does 2299 if (pkgSetting == null) { 2300 continue; 2301 } 2302 boolean install = enableApps.contains(pName); 2303 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2304 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2305 + " for system user"); 2306 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2307 } 2308 } 2309 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2310 } 2311 } 2312 2313 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2314 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2315 Context.DISPLAY_SERVICE); 2316 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2317 } 2318 2319 /** 2320 * Requests that files preopted on a secondary system partition be copied to the data partition 2321 * if possible. Note that the actual copying of the files is accomplished by init for security 2322 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2323 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2324 */ 2325 private static void requestCopyPreoptedFiles() { 2326 final int WAIT_TIME_MS = 100; 2327 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2328 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2329 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2330 // We will wait for up to 100 seconds. 2331 final long timeStart = SystemClock.uptimeMillis(); 2332 final long timeEnd = timeStart + 100 * 1000; 2333 long timeNow = timeStart; 2334 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2335 try { 2336 Thread.sleep(WAIT_TIME_MS); 2337 } catch (InterruptedException e) { 2338 // Do nothing 2339 } 2340 timeNow = SystemClock.uptimeMillis(); 2341 if (timeNow > timeEnd) { 2342 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2343 Slog.wtf(TAG, "cppreopt did not finish!"); 2344 break; 2345 } 2346 } 2347 2348 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2349 } 2350 } 2351 2352 public PackageManagerService(Context context, Installer installer, 2353 boolean factoryTest, boolean onlyCore) { 2354 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2355 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2356 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2357 SystemClock.uptimeMillis()); 2358 2359 if (mSdkVersion <= 0) { 2360 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2361 } 2362 2363 mContext = context; 2364 2365 mFactoryTest = factoryTest; 2366 mOnlyCore = onlyCore; 2367 mMetrics = new DisplayMetrics(); 2368 mInstaller = installer; 2369 2370 // Create sub-components that provide services / data. Order here is important. 2371 synchronized (mInstallLock) { 2372 synchronized (mPackages) { 2373 // Expose private service for system components to use. 2374 LocalServices.addService( 2375 PackageManagerInternal.class, new PackageManagerInternalImpl()); 2376 sUserManager = new UserManagerService(context, this, 2377 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2378 mPermissionManager = PermissionManagerService.create(context, 2379 new DefaultPermissionGrantedCallback() { 2380 @Override 2381 public void onDefaultRuntimePermissionsGranted(int userId) { 2382 synchronized(mPackages) { 2383 mSettings.onDefaultRuntimePermissionsGrantedLPr(userId); 2384 } 2385 } 2386 }, mPackages /*externalLock*/); 2387 mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy(); 2388 mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages); 2389 } 2390 } 2391 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2392 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2393 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2394 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2395 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2396 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2397 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2398 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2399 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2400 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2401 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2402 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2403 2404 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2405 if (separateProcesses != null && separateProcesses.length() > 0) { 2406 if ("*".equals(separateProcesses)) { 2407 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2408 mSeparateProcesses = null; 2409 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2410 } else { 2411 mDefParseFlags = 0; 2412 mSeparateProcesses = separateProcesses.split(","); 2413 Slog.w(TAG, "Running with debug.separate_processes: " 2414 + separateProcesses); 2415 } 2416 } else { 2417 mDefParseFlags = 0; 2418 mSeparateProcesses = null; 2419 } 2420 2421 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2422 "*dexopt*"); 2423 DexManager.Listener dexManagerListener = DexLogger.getListener(this, 2424 installer, mInstallLock); 2425 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock, 2426 dexManagerListener); 2427 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2428 2429 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2430 FgThread.get().getLooper()); 2431 2432 getDefaultDisplayMetrics(context, mMetrics); 2433 2434 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2435 SystemConfig systemConfig = SystemConfig.getInstance(); 2436 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2437 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2438 2439 mProtectedPackages = new ProtectedPackages(mContext); 2440 2441 synchronized (mInstallLock) { 2442 // writer 2443 synchronized (mPackages) { 2444 mHandlerThread = new ServiceThread(TAG, 2445 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2446 mHandlerThread.start(); 2447 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2448 mProcessLoggingHandler = new ProcessLoggingHandler(); 2449 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2450 mInstantAppRegistry = new InstantAppRegistry(this); 2451 2452 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2453 final int builtInLibCount = libConfig.size(); 2454 for (int i = 0; i < builtInLibCount; i++) { 2455 String name = libConfig.keyAt(i); 2456 String path = libConfig.valueAt(i); 2457 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2458 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2459 } 2460 2461 SELinuxMMAC.readInstallPolicy(); 2462 2463 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2464 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2465 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2466 2467 // Clean up orphaned packages for which the code path doesn't exist 2468 // and they are an update to a system app - caused by bug/32321269 2469 final int packageSettingCount = mSettings.mPackages.size(); 2470 for (int i = packageSettingCount - 1; i >= 0; i--) { 2471 PackageSetting ps = mSettings.mPackages.valueAt(i); 2472 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2473 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2474 mSettings.mPackages.removeAt(i); 2475 mSettings.enableSystemPackageLPw(ps.name); 2476 } 2477 } 2478 2479 if (mFirstBoot) { 2480 requestCopyPreoptedFiles(); 2481 } 2482 2483 String customResolverActivity = Resources.getSystem().getString( 2484 R.string.config_customResolverActivity); 2485 if (TextUtils.isEmpty(customResolverActivity)) { 2486 customResolverActivity = null; 2487 } else { 2488 mCustomResolverComponentName = ComponentName.unflattenFromString( 2489 customResolverActivity); 2490 } 2491 2492 long startTime = SystemClock.uptimeMillis(); 2493 2494 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2495 startTime); 2496 2497 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2498 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2499 2500 if (bootClassPath == null) { 2501 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2502 } 2503 2504 if (systemServerClassPath == null) { 2505 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2506 } 2507 2508 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2509 2510 final VersionInfo ver = mSettings.getInternalVersion(); 2511 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2512 if (mIsUpgrade) { 2513 logCriticalInfo(Log.INFO, 2514 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2515 } 2516 2517 // when upgrading from pre-M, promote system app permissions from install to runtime 2518 mPromoteSystemApps = 2519 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2520 2521 // When upgrading from pre-N, we need to handle package extraction like first boot, 2522 // as there is no profiling data available. 2523 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2524 2525 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2526 2527 // save off the names of pre-existing system packages prior to scanning; we don't 2528 // want to automatically grant runtime permissions for new system apps 2529 if (mPromoteSystemApps) { 2530 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2531 while (pkgSettingIter.hasNext()) { 2532 PackageSetting ps = pkgSettingIter.next(); 2533 if (isSystemApp(ps)) { 2534 mExistingSystemPackages.add(ps.name); 2535 } 2536 } 2537 } 2538 2539 mCacheDir = preparePackageParserCache(mIsUpgrade); 2540 2541 // Set flag to monitor and not change apk file paths when 2542 // scanning install directories. 2543 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2544 2545 if (mIsUpgrade || mFirstBoot) { 2546 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2547 } 2548 2549 // Collect vendor overlay packages. (Do this before scanning any apps.) 2550 // For security and version matching reason, only consider 2551 // overlay packages if they reside in the right directory. 2552 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), 2553 mDefParseFlags 2554 | PackageParser.PARSE_IS_SYSTEM_DIR, 2555 scanFlags 2556 | SCAN_AS_SYSTEM 2557 | SCAN_TRUSTED_OVERLAY, 2558 0); 2559 2560 mParallelPackageParserCallback.findStaticOverlayPackages(); 2561 2562 // Find base frameworks (resource packages without code). 2563 scanDirTracedLI(frameworkDir, 2564 mDefParseFlags 2565 | PackageParser.PARSE_IS_SYSTEM_DIR, 2566 scanFlags 2567 | SCAN_NO_DEX 2568 | SCAN_AS_SYSTEM 2569 | SCAN_AS_PRIVILEGED, 2570 0); 2571 2572 // Collected privileged system packages. 2573 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2574 scanDirTracedLI(privilegedAppDir, 2575 mDefParseFlags 2576 | PackageParser.PARSE_IS_SYSTEM_DIR, 2577 scanFlags 2578 | SCAN_AS_SYSTEM 2579 | SCAN_AS_PRIVILEGED, 2580 0); 2581 2582 // Collect ordinary system packages. 2583 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2584 scanDirTracedLI(systemAppDir, 2585 mDefParseFlags 2586 | PackageParser.PARSE_IS_SYSTEM_DIR, 2587 scanFlags 2588 | SCAN_AS_SYSTEM, 2589 0); 2590 2591 // Collected privileged vendor packages. 2592 File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), 2593 "priv-app"); 2594 try { 2595 privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile(); 2596 } catch (IOException e) { 2597 // failed to look up canonical path, continue with original one 2598 } 2599 scanDirTracedLI(privilegedVendorAppDir, 2600 mDefParseFlags 2601 | PackageParser.PARSE_IS_SYSTEM_DIR, 2602 scanFlags 2603 | SCAN_AS_SYSTEM 2604 | SCAN_AS_VENDOR 2605 | SCAN_AS_PRIVILEGED, 2606 0); 2607 2608 // Collect ordinary vendor packages. 2609 File vendorAppDir = new File(Environment.getVendorDirectory(), "app"); 2610 try { 2611 vendorAppDir = vendorAppDir.getCanonicalFile(); 2612 } catch (IOException e) { 2613 // failed to look up canonical path, continue with original one 2614 } 2615 scanDirTracedLI(vendorAppDir, 2616 mDefParseFlags 2617 | PackageParser.PARSE_IS_SYSTEM_DIR, 2618 scanFlags 2619 | SCAN_AS_SYSTEM 2620 | SCAN_AS_VENDOR, 2621 0); 2622 2623 // Collect all OEM packages. 2624 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2625 scanDirTracedLI(oemAppDir, 2626 mDefParseFlags 2627 | PackageParser.PARSE_IS_SYSTEM_DIR, 2628 scanFlags 2629 | SCAN_AS_SYSTEM 2630 | SCAN_AS_OEM, 2631 0); 2632 2633 // Prune any system packages that no longer exist. 2634 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>(); 2635 // Stub packages must either be replaced with full versions in the /data 2636 // partition or be disabled. 2637 final List<String> stubSystemApps = new ArrayList<>(); 2638 if (!mOnlyCore) { 2639 // do this first before mucking with mPackages for the "expecting better" case 2640 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator(); 2641 while (pkgIterator.hasNext()) { 2642 final PackageParser.Package pkg = pkgIterator.next(); 2643 if (pkg.isStub) { 2644 stubSystemApps.add(pkg.packageName); 2645 } 2646 } 2647 2648 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2649 while (psit.hasNext()) { 2650 PackageSetting ps = psit.next(); 2651 2652 /* 2653 * If this is not a system app, it can't be a 2654 * disable system app. 2655 */ 2656 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2657 continue; 2658 } 2659 2660 /* 2661 * If the package is scanned, it's not erased. 2662 */ 2663 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2664 if (scannedPkg != null) { 2665 /* 2666 * If the system app is both scanned and in the 2667 * disabled packages list, then it must have been 2668 * added via OTA. Remove it from the currently 2669 * scanned package so the previously user-installed 2670 * application can be scanned. 2671 */ 2672 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2673 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2674 + ps.name + "; removing system app. Last known codePath=" 2675 + ps.codePathString + ", installStatus=" + ps.installStatus 2676 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2677 + scannedPkg.getLongVersionCode()); 2678 removePackageLI(scannedPkg, true); 2679 mExpectingBetter.put(ps.name, ps.codePath); 2680 } 2681 2682 continue; 2683 } 2684 2685 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2686 psit.remove(); 2687 logCriticalInfo(Log.WARN, "System package " + ps.name 2688 + " no longer exists; it's data will be wiped"); 2689 // Actual deletion of code and data will be handled by later 2690 // reconciliation step 2691 } else { 2692 // we still have a disabled system package, but, it still might have 2693 // been removed. check the code path still exists and check there's 2694 // still a package. the latter can happen if an OTA keeps the same 2695 // code path, but, changes the package name. 2696 final PackageSetting disabledPs = 2697 mSettings.getDisabledSystemPkgLPr(ps.name); 2698 if (disabledPs.codePath == null || !disabledPs.codePath.exists() 2699 || disabledPs.pkg == null) { 2700 possiblyDeletedUpdatedSystemApps.add(ps.name); 2701 } 2702 } 2703 } 2704 } 2705 2706 //look for any incomplete package installations 2707 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2708 for (int i = 0; i < deletePkgsList.size(); i++) { 2709 // Actual deletion of code and data will be handled by later 2710 // reconciliation step 2711 final String packageName = deletePkgsList.get(i).name; 2712 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2713 synchronized (mPackages) { 2714 mSettings.removePackageLPw(packageName); 2715 } 2716 } 2717 2718 //delete tmp files 2719 deleteTempPackageFiles(); 2720 2721 final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get(); 2722 2723 // Remove any shared userIDs that have no associated packages 2724 mSettings.pruneSharedUsersLPw(); 2725 final long systemScanTime = SystemClock.uptimeMillis() - startTime; 2726 final int systemPackagesCount = mPackages.size(); 2727 Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime 2728 + " ms, packageCount: " + systemPackagesCount 2729 + " , timePerPackage: " 2730 + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount) 2731 + " , cached: " + cachedSystemApps); 2732 if (mIsUpgrade && systemPackagesCount > 0) { 2733 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time", 2734 ((int) systemScanTime) / systemPackagesCount); 2735 } 2736 if (!mOnlyCore) { 2737 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2738 SystemClock.uptimeMillis()); 2739 scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2740 2741 scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags 2742 | PackageParser.PARSE_FORWARD_LOCK, 2743 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2744 2745 // Remove disable package settings for updated system apps that were 2746 // removed via an OTA. If the update is no longer present, remove the 2747 // app completely. Otherwise, revoke their system privileges. 2748 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2749 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2750 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2751 2752 final String msg; 2753 if (deletedPkg == null) { 2754 // should have found an update, but, we didn't; remove everything 2755 msg = "Updated system package " + deletedAppName 2756 + " no longer exists; removing its data"; 2757 // Actual deletion of code and data will be handled by later 2758 // reconciliation step 2759 } else { 2760 // found an update; revoke system privileges 2761 msg = "Updated system package + " + deletedAppName 2762 + " no longer exists; revoking system privileges"; 2763 2764 // Don't do anything if a stub is removed from the system image. If 2765 // we were to remove the uncompressed version from the /data partition, 2766 // this is where it'd be done. 2767 2768 final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2769 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2770 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2771 } 2772 logCriticalInfo(Log.WARN, msg); 2773 } 2774 2775 /* 2776 * Make sure all system apps that we expected to appear on 2777 * the userdata partition actually showed up. If they never 2778 * appeared, crawl back and revive the system version. 2779 */ 2780 for (int i = 0; i < mExpectingBetter.size(); i++) { 2781 final String packageName = mExpectingBetter.keyAt(i); 2782 if (!mPackages.containsKey(packageName)) { 2783 final File scanFile = mExpectingBetter.valueAt(i); 2784 2785 logCriticalInfo(Log.WARN, "Expected better " + packageName 2786 + " but never showed up; reverting to system"); 2787 2788 final @ParseFlags int reparseFlags; 2789 final @ScanFlags int rescanFlags; 2790 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2791 reparseFlags = 2792 mDefParseFlags | 2793 PackageParser.PARSE_IS_SYSTEM_DIR; 2794 rescanFlags = 2795 scanFlags 2796 | SCAN_AS_SYSTEM 2797 | SCAN_AS_PRIVILEGED; 2798 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2799 reparseFlags = 2800 mDefParseFlags | 2801 PackageParser.PARSE_IS_SYSTEM_DIR; 2802 rescanFlags = 2803 scanFlags 2804 | SCAN_AS_SYSTEM; 2805 } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) { 2806 reparseFlags = 2807 mDefParseFlags | 2808 PackageParser.PARSE_IS_SYSTEM_DIR; 2809 rescanFlags = 2810 scanFlags 2811 | SCAN_AS_SYSTEM 2812 | SCAN_AS_VENDOR 2813 | SCAN_AS_PRIVILEGED; 2814 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2815 reparseFlags = 2816 mDefParseFlags | 2817 PackageParser.PARSE_IS_SYSTEM_DIR; 2818 rescanFlags = 2819 scanFlags 2820 | SCAN_AS_SYSTEM 2821 | SCAN_AS_VENDOR; 2822 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2823 reparseFlags = 2824 mDefParseFlags | 2825 PackageParser.PARSE_IS_SYSTEM_DIR; 2826 rescanFlags = 2827 scanFlags 2828 | SCAN_AS_SYSTEM 2829 | SCAN_AS_OEM; 2830 } else { 2831 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2832 continue; 2833 } 2834 2835 mSettings.enableSystemPackageLPw(packageName); 2836 2837 try { 2838 scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null); 2839 } catch (PackageManagerException e) { 2840 Slog.e(TAG, "Failed to parse original system package: " 2841 + e.getMessage()); 2842 } 2843 } 2844 } 2845 2846 // Uncompress and install any stubbed system applications. 2847 // This must be done last to ensure all stubs are replaced or disabled. 2848 decompressSystemApplications(stubSystemApps, scanFlags); 2849 2850 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get() 2851 - cachedSystemApps; 2852 2853 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime; 2854 final int dataPackagesCount = mPackages.size() - systemPackagesCount; 2855 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime 2856 + " ms, packageCount: " + dataPackagesCount 2857 + " , timePerPackage: " 2858 + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) 2859 + " , cached: " + cachedNonSystemApps); 2860 if (mIsUpgrade && dataPackagesCount > 0) { 2861 MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time", 2862 ((int) dataScanTime) / dataPackagesCount); 2863 } 2864 } 2865 mExpectingBetter.clear(); 2866 2867 // Resolve the storage manager. 2868 mStorageManagerPackage = getStorageManagerPackageName(); 2869 2870 // Resolve protected action filters. Only the setup wizard is allowed to 2871 // have a high priority filter for these actions. 2872 mSetupWizardPackage = getSetupWizardPackageName(); 2873 if (mProtectedFilters.size() > 0) { 2874 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2875 Slog.i(TAG, "No setup wizard;" 2876 + " All protected intents capped to priority 0"); 2877 } 2878 for (ActivityIntentInfo filter : mProtectedFilters) { 2879 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2880 if (DEBUG_FILTERS) { 2881 Slog.i(TAG, "Found setup wizard;" 2882 + " allow priority " + filter.getPriority() + ";" 2883 + " package: " + filter.activity.info.packageName 2884 + " activity: " + filter.activity.className 2885 + " priority: " + filter.getPriority()); 2886 } 2887 // skip setup wizard; allow it to keep the high priority filter 2888 continue; 2889 } 2890 if (DEBUG_FILTERS) { 2891 Slog.i(TAG, "Protected action; cap priority to 0;" 2892 + " package: " + filter.activity.info.packageName 2893 + " activity: " + filter.activity.className 2894 + " origPrio: " + filter.getPriority()); 2895 } 2896 filter.setPriority(0); 2897 } 2898 } 2899 mDeferProtectedFilters = false; 2900 mProtectedFilters.clear(); 2901 2902 // Now that we know all of the shared libraries, update all clients to have 2903 // the correct library paths. 2904 updateAllSharedLibrariesLPw(null); 2905 2906 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2907 // NOTE: We ignore potential failures here during a system scan (like 2908 // the rest of the commands above) because there's precious little we 2909 // can do about it. A settings error is reported, though. 2910 final List<String> changedAbiCodePath = 2911 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2912 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 2913 for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) { 2914 final String codePathString = changedAbiCodePath.get(i); 2915 try { 2916 mInstaller.rmdex(codePathString, 2917 getDexCodeInstructionSet(getPreferredInstructionSet())); 2918 } catch (InstallerException ignored) { 2919 } 2920 } 2921 } 2922 } 2923 2924 // Now that we know all the packages we are keeping, 2925 // read and update their last usage times. 2926 mPackageUsage.read(mPackages); 2927 mCompilerStats.read(); 2928 2929 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2930 SystemClock.uptimeMillis()); 2931 Slog.i(TAG, "Time to scan packages: " 2932 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2933 + " seconds"); 2934 2935 // If the platform SDK has changed since the last time we booted, 2936 // we need to re-grant app permission to catch any new ones that 2937 // appear. This is really a hack, and means that apps can in some 2938 // cases get permissions that the user didn't initially explicitly 2939 // allow... it would be nice to have some better way to handle 2940 // this situation. 2941 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 2942 if (sdkUpdated) { 2943 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2944 + mSdkVersion + "; regranting permissions for internal storage"); 2945 } 2946 mPermissionManager.updateAllPermissions( 2947 StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(), 2948 mPermissionCallback); 2949 ver.sdkVersion = mSdkVersion; 2950 2951 // If this is the first boot or an update from pre-M, and it is a normal 2952 // boot, then we need to initialize the default preferred apps across 2953 // all defined users. 2954 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2955 for (UserInfo user : sUserManager.getUsers(true)) { 2956 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2957 applyFactoryDefaultBrowserLPw(user.id); 2958 primeDomainVerificationsLPw(user.id); 2959 } 2960 } 2961 2962 // Prepare storage for system user really early during boot, 2963 // since core system apps like SettingsProvider and SystemUI 2964 // can't wait for user to start 2965 final int storageFlags; 2966 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2967 storageFlags = StorageManager.FLAG_STORAGE_DE; 2968 } else { 2969 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2970 } 2971 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2972 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2973 true /* onlyCoreApps */); 2974 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2975 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync", 2976 Trace.TRACE_TAG_PACKAGE_MANAGER); 2977 traceLog.traceBegin("AppDataFixup"); 2978 try { 2979 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2980 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2981 } catch (InstallerException e) { 2982 Slog.w(TAG, "Trouble fixing GIDs", e); 2983 } 2984 traceLog.traceEnd(); 2985 2986 traceLog.traceBegin("AppDataPrepare"); 2987 if (deferPackages == null || deferPackages.isEmpty()) { 2988 return; 2989 } 2990 int count = 0; 2991 for (String pkgName : deferPackages) { 2992 PackageParser.Package pkg = null; 2993 synchronized (mPackages) { 2994 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2995 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2996 pkg = ps.pkg; 2997 } 2998 } 2999 if (pkg != null) { 3000 synchronized (mInstallLock) { 3001 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 3002 true /* maybeMigrateAppData */); 3003 } 3004 count++; 3005 } 3006 } 3007 traceLog.traceEnd(); 3008 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 3009 }, "prepareAppData"); 3010 3011 // If this is first boot after an OTA, and a normal boot, then 3012 // we need to clear code cache directories. 3013 // Note that we do *not* clear the application profiles. These remain valid 3014 // across OTAs and are used to drive profile verification (post OTA) and 3015 // profile compilation (without waiting to collect a fresh set of profiles). 3016 if (mIsUpgrade && !onlyCore) { 3017 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 3018 for (int i = 0; i < mSettings.mPackages.size(); i++) { 3019 final PackageSetting ps = mSettings.mPackages.valueAt(i); 3020 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 3021 // No apps are running this early, so no need to freeze 3022 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 3023 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 3024 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 3025 } 3026 } 3027 ver.fingerprint = Build.FINGERPRINT; 3028 } 3029 3030 checkDefaultBrowser(); 3031 3032 // clear only after permissions and other defaults have been updated 3033 mExistingSystemPackages.clear(); 3034 mPromoteSystemApps = false; 3035 3036 // All the changes are done during package scanning. 3037 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 3038 3039 // can downgrade to reader 3040 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 3041 mSettings.writeLPr(); 3042 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3043 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 3044 SystemClock.uptimeMillis()); 3045 3046 if (!mOnlyCore) { 3047 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 3048 mRequiredInstallerPackage = getRequiredInstallerLPr(); 3049 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 3050 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 3051 if (mIntentFilterVerifierComponent != null) { 3052 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 3053 mIntentFilterVerifierComponent); 3054 } else { 3055 mIntentFilterVerifier = null; 3056 } 3057 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3058 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 3059 SharedLibraryInfo.VERSION_UNDEFINED); 3060 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3061 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 3062 SharedLibraryInfo.VERSION_UNDEFINED); 3063 } else { 3064 mRequiredVerifierPackage = null; 3065 mRequiredInstallerPackage = null; 3066 mRequiredUninstallerPackage = null; 3067 mIntentFilterVerifierComponent = null; 3068 mIntentFilterVerifier = null; 3069 mServicesSystemSharedLibraryPackageName = null; 3070 mSharedSystemSharedLibraryPackageName = null; 3071 } 3072 3073 mInstallerService = new PackageInstallerService(context, this); 3074 mArtManagerService = new ArtManagerService(this, mInstaller, mInstallLock); 3075 final Pair<ComponentName, String> instantAppResolverComponent = 3076 getInstantAppResolverLPr(); 3077 if (instantAppResolverComponent != null) { 3078 if (DEBUG_EPHEMERAL) { 3079 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 3080 } 3081 mInstantAppResolverConnection = new EphemeralResolverConnection( 3082 mContext, instantAppResolverComponent.first, 3083 instantAppResolverComponent.second); 3084 mInstantAppResolverSettingsComponent = 3085 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 3086 } else { 3087 mInstantAppResolverConnection = null; 3088 mInstantAppResolverSettingsComponent = null; 3089 } 3090 updateInstantAppInstallerLocked(null); 3091 3092 // Read and update the usage of dex files. 3093 // Do this at the end of PM init so that all the packages have their 3094 // data directory reconciled. 3095 // At this point we know the code paths of the packages, so we can validate 3096 // the disk file and build the internal cache. 3097 // The usage file is expected to be small so loading and verifying it 3098 // should take a fairly small time compare to the other activities (e.g. package 3099 // scanning). 3100 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3101 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 3102 for (int userId : currentUserIds) { 3103 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3104 } 3105 mDexManager.load(userPackages); 3106 if (mIsUpgrade) { 3107 MetricsLogger.histogram(null, "ota_package_manager_init_time", 3108 (int) (SystemClock.uptimeMillis() - startTime)); 3109 } 3110 } // synchronized (mPackages) 3111 } // synchronized (mInstallLock) 3112 3113 // Now after opening every single application zip, make sure they 3114 // are all flushed. Not really needed, but keeps things nice and 3115 // tidy. 3116 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3117 Runtime.getRuntime().gc(); 3118 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3119 3120 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 3121 FallbackCategoryProvider.loadFallbacks(); 3122 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3123 3124 // The initial scanning above does many calls into installd while 3125 // holding the mPackages lock, but we're mostly interested in yelling 3126 // once we have a booted system. 3127 mInstaller.setWarnIfHeld(mPackages); 3128 3129 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3130 } 3131 3132 /** 3133 * Uncompress and install stub applications. 3134 * <p>In order to save space on the system partition, some applications are shipped in a 3135 * compressed form. In addition the compressed bits for the full application, the 3136 * system image contains a tiny stub comprised of only the Android manifest. 3137 * <p>During the first boot, attempt to uncompress and install the full application. If 3138 * the application can't be installed for any reason, disable the stub and prevent 3139 * uncompressing the full application during future boots. 3140 * <p>In order to forcefully attempt an installation of a full application, go to app 3141 * settings and enable the application. 3142 */ 3143 private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) { 3144 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3145 final String pkgName = stubSystemApps.get(i); 3146 // skip if the system package is already disabled 3147 if (mSettings.isDisabledSystemPackageLPr(pkgName)) { 3148 stubSystemApps.remove(i); 3149 continue; 3150 } 3151 // skip if the package isn't installed (?!); this should never happen 3152 final PackageParser.Package pkg = mPackages.get(pkgName); 3153 if (pkg == null) { 3154 stubSystemApps.remove(i); 3155 continue; 3156 } 3157 // skip if the package has been disabled by the user 3158 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3159 if (ps != null) { 3160 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM); 3161 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) { 3162 stubSystemApps.remove(i); 3163 continue; 3164 } 3165 } 3166 3167 if (DEBUG_COMPRESSION) { 3168 Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName); 3169 } 3170 3171 // uncompress the binary to its eventual destination on /data 3172 final File scanFile = decompressPackage(pkg); 3173 if (scanFile == null) { 3174 continue; 3175 } 3176 3177 // install the package to replace the stub on /system 3178 try { 3179 mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/); 3180 removePackageLI(pkg, true /*chatty*/); 3181 scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null); 3182 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 3183 UserHandle.USER_SYSTEM, "android"); 3184 stubSystemApps.remove(i); 3185 continue; 3186 } catch (PackageManagerException e) { 3187 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage()); 3188 } 3189 3190 // any failed attempt to install the package will be cleaned up later 3191 } 3192 3193 // disable any stub still left; these failed to install the full application 3194 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3195 final String pkgName = stubSystemApps.get(i); 3196 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3197 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 3198 UserHandle.USER_SYSTEM, "android"); 3199 logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName); 3200 } 3201 } 3202 3203 /** 3204 * Decompresses the given package on the system image onto 3205 * the /data partition. 3206 * @return The directory the package was decompressed into. Otherwise, {@code null}. 3207 */ 3208 private File decompressPackage(PackageParser.Package pkg) { 3209 final File[] compressedFiles = getCompressedFiles(pkg.codePath); 3210 if (compressedFiles == null || compressedFiles.length == 0) { 3211 if (DEBUG_COMPRESSION) { 3212 Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath); 3213 } 3214 return null; 3215 } 3216 final File dstCodePath = 3217 getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName); 3218 int ret = PackageManager.INSTALL_SUCCEEDED; 3219 try { 3220 Os.mkdir(dstCodePath.getAbsolutePath(), 0755); 3221 Os.chmod(dstCodePath.getAbsolutePath(), 0755); 3222 for (File srcFile : compressedFiles) { 3223 final String srcFileName = srcFile.getName(); 3224 final String dstFileName = srcFileName.substring( 3225 0, srcFileName.length() - COMPRESSED_EXTENSION.length()); 3226 final File dstFile = new File(dstCodePath, dstFileName); 3227 ret = decompressFile(srcFile, dstFile); 3228 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3229 logCriticalInfo(Log.ERROR, "Failed to decompress" 3230 + "; pkg: " + pkg.packageName 3231 + ", file: " + dstFileName); 3232 break; 3233 } 3234 } 3235 } catch (ErrnoException e) { 3236 logCriticalInfo(Log.ERROR, "Failed to decompress" 3237 + "; pkg: " + pkg.packageName 3238 + ", err: " + e.errno); 3239 } 3240 if (ret == PackageManager.INSTALL_SUCCEEDED) { 3241 final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME); 3242 NativeLibraryHelper.Handle handle = null; 3243 try { 3244 handle = NativeLibraryHelper.Handle.create(dstCodePath); 3245 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 3246 null /*abiOverride*/); 3247 } catch (IOException e) { 3248 logCriticalInfo(Log.ERROR, "Failed to extract native libraries" 3249 + "; pkg: " + pkg.packageName); 3250 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3251 } finally { 3252 IoUtils.closeQuietly(handle); 3253 } 3254 } 3255 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3256 if (dstCodePath == null || !dstCodePath.exists()) { 3257 return null; 3258 } 3259 removeCodePathLI(dstCodePath); 3260 return null; 3261 } 3262 3263 return dstCodePath; 3264 } 3265 3266 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3267 // we're only interested in updating the installer appliction when 1) it's not 3268 // already set or 2) the modified package is the installer 3269 if (mInstantAppInstallerActivity != null 3270 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3271 .equals(modifiedPackage)) { 3272 return; 3273 } 3274 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3275 } 3276 3277 private static File preparePackageParserCache(boolean isUpgrade) { 3278 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3279 return null; 3280 } 3281 3282 // Disable package parsing on eng builds to allow for faster incremental development. 3283 if (Build.IS_ENG) { 3284 return null; 3285 } 3286 3287 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3288 Slog.i(TAG, "Disabling package parser cache due to system property."); 3289 return null; 3290 } 3291 3292 // The base directory for the package parser cache lives under /data/system/. 3293 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3294 "package_cache"); 3295 if (cacheBaseDir == null) { 3296 return null; 3297 } 3298 3299 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3300 // This also serves to "GC" unused entries when the package cache version changes (which 3301 // can only happen during upgrades). 3302 if (isUpgrade) { 3303 FileUtils.deleteContents(cacheBaseDir); 3304 } 3305 3306 3307 // Return the versioned package cache directory. This is something like 3308 // "/data/system/package_cache/1" 3309 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3310 3311 // The following is a workaround to aid development on non-numbered userdebug 3312 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3313 // the system partition is newer. 3314 // 3315 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3316 // that starts with "eng." to signify that this is an engineering build and not 3317 // destined for release. 3318 if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3319 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3320 3321 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3322 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3323 // in general and should not be used for production changes. In this specific case, 3324 // we know that they will work. 3325 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3326 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3327 FileUtils.deleteContents(cacheBaseDir); 3328 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3329 } 3330 } 3331 3332 return cacheDir; 3333 } 3334 3335 @Override 3336 public boolean isFirstBoot() { 3337 // allow instant applications 3338 return mFirstBoot; 3339 } 3340 3341 @Override 3342 public boolean isOnlyCoreApps() { 3343 // allow instant applications 3344 return mOnlyCore; 3345 } 3346 3347 @Override 3348 public boolean isUpgrade() { 3349 // allow instant applications 3350 // The system property allows testing ota flow when upgraded to the same image. 3351 return mIsUpgrade || SystemProperties.getBoolean( 3352 "persist.pm.mock-upgrade", false /* default */); 3353 } 3354 3355 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3356 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3357 3358 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3359 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3360 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3361 if (matches.size() == 1) { 3362 return matches.get(0).getComponentInfo().packageName; 3363 } else if (matches.size() == 0) { 3364 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3365 return null; 3366 } 3367 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3368 } 3369 3370 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3371 synchronized (mPackages) { 3372 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3373 if (libraryEntry == null) { 3374 throw new IllegalStateException("Missing required shared library:" + name); 3375 } 3376 return libraryEntry.apk; 3377 } 3378 } 3379 3380 private @NonNull String getRequiredInstallerLPr() { 3381 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3382 intent.addCategory(Intent.CATEGORY_DEFAULT); 3383 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3384 3385 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3386 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3387 UserHandle.USER_SYSTEM); 3388 if (matches.size() == 1) { 3389 ResolveInfo resolveInfo = matches.get(0); 3390 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3391 throw new RuntimeException("The installer must be a privileged app"); 3392 } 3393 return matches.get(0).getComponentInfo().packageName; 3394 } else { 3395 throw new RuntimeException("There must be exactly one installer; found " + matches); 3396 } 3397 } 3398 3399 private @NonNull String getRequiredUninstallerLPr() { 3400 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3401 intent.addCategory(Intent.CATEGORY_DEFAULT); 3402 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3403 3404 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3405 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3406 UserHandle.USER_SYSTEM); 3407 if (resolveInfo == null || 3408 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3409 throw new RuntimeException("There must be exactly one uninstaller; found " 3410 + resolveInfo); 3411 } 3412 return resolveInfo.getComponentInfo().packageName; 3413 } 3414 3415 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3416 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3417 3418 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3419 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3420 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3421 ResolveInfo best = null; 3422 final int N = matches.size(); 3423 for (int i = 0; i < N; i++) { 3424 final ResolveInfo cur = matches.get(i); 3425 final String packageName = cur.getComponentInfo().packageName; 3426 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3427 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3428 continue; 3429 } 3430 3431 if (best == null || cur.priority > best.priority) { 3432 best = cur; 3433 } 3434 } 3435 3436 if (best != null) { 3437 return best.getComponentInfo().getComponentName(); 3438 } 3439 Slog.w(TAG, "Intent filter verifier not found"); 3440 return null; 3441 } 3442 3443 @Override 3444 public @Nullable ComponentName getInstantAppResolverComponent() { 3445 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3446 return null; 3447 } 3448 synchronized (mPackages) { 3449 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3450 if (instantAppResolver == null) { 3451 return null; 3452 } 3453 return instantAppResolver.first; 3454 } 3455 } 3456 3457 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3458 final String[] packageArray = 3459 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3460 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3461 if (DEBUG_EPHEMERAL) { 3462 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3463 } 3464 return null; 3465 } 3466 3467 final int callingUid = Binder.getCallingUid(); 3468 final int resolveFlags = 3469 MATCH_DIRECT_BOOT_AWARE 3470 | MATCH_DIRECT_BOOT_UNAWARE 3471 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3472 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3473 final Intent resolverIntent = new Intent(actionName); 3474 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3475 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3476 // temporarily look for the old action 3477 if (resolvers.size() == 0) { 3478 if (DEBUG_EPHEMERAL) { 3479 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3480 } 3481 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE; 3482 resolverIntent.setAction(actionName); 3483 resolvers = queryIntentServicesInternal(resolverIntent, null, 3484 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3485 } 3486 final int N = resolvers.size(); 3487 if (N == 0) { 3488 if (DEBUG_EPHEMERAL) { 3489 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3490 } 3491 return null; 3492 } 3493 3494 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3495 for (int i = 0; i < N; i++) { 3496 final ResolveInfo info = resolvers.get(i); 3497 3498 if (info.serviceInfo == null) { 3499 continue; 3500 } 3501 3502 final String packageName = info.serviceInfo.packageName; 3503 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3504 if (DEBUG_EPHEMERAL) { 3505 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3506 + " pkg: " + packageName + ", info:" + info); 3507 } 3508 continue; 3509 } 3510 3511 if (DEBUG_EPHEMERAL) { 3512 Slog.v(TAG, "Ephemeral resolver found;" 3513 + " pkg: " + packageName + ", info:" + info); 3514 } 3515 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3516 } 3517 if (DEBUG_EPHEMERAL) { 3518 Slog.v(TAG, "Ephemeral resolver NOT found"); 3519 } 3520 return null; 3521 } 3522 3523 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3524 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3525 intent.addCategory(Intent.CATEGORY_DEFAULT); 3526 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3527 3528 final int resolveFlags = 3529 MATCH_DIRECT_BOOT_AWARE 3530 | MATCH_DIRECT_BOOT_UNAWARE 3531 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3532 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3533 resolveFlags, UserHandle.USER_SYSTEM); 3534 // temporarily look for the old action 3535 if (matches.isEmpty()) { 3536 if (DEBUG_EPHEMERAL) { 3537 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3538 } 3539 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3540 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3541 resolveFlags, UserHandle.USER_SYSTEM); 3542 } 3543 Iterator<ResolveInfo> iter = matches.iterator(); 3544 while (iter.hasNext()) { 3545 final ResolveInfo rInfo = iter.next(); 3546 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3547 if (ps != null) { 3548 final PermissionsState permissionsState = ps.getPermissionsState(); 3549 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3550 continue; 3551 } 3552 } 3553 iter.remove(); 3554 } 3555 if (matches.size() == 0) { 3556 return null; 3557 } else if (matches.size() == 1) { 3558 return (ActivityInfo) matches.get(0).getComponentInfo(); 3559 } else { 3560 throw new RuntimeException( 3561 "There must be at most one ephemeral installer; found " + matches); 3562 } 3563 } 3564 3565 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3566 @NonNull ComponentName resolver) { 3567 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3568 .addCategory(Intent.CATEGORY_DEFAULT) 3569 .setPackage(resolver.getPackageName()); 3570 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3571 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3572 UserHandle.USER_SYSTEM); 3573 // temporarily look for the old action 3574 if (matches.isEmpty()) { 3575 if (DEBUG_EPHEMERAL) { 3576 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3577 } 3578 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3579 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3580 UserHandle.USER_SYSTEM); 3581 } 3582 if (matches.isEmpty()) { 3583 return null; 3584 } 3585 return matches.get(0).getComponentInfo().getComponentName(); 3586 } 3587 3588 private void primeDomainVerificationsLPw(int userId) { 3589 if (DEBUG_DOMAIN_VERIFICATION) { 3590 Slog.d(TAG, "Priming domain verifications in user " + userId); 3591 } 3592 3593 SystemConfig systemConfig = SystemConfig.getInstance(); 3594 ArraySet<String> packages = systemConfig.getLinkedApps(); 3595 3596 for (String packageName : packages) { 3597 PackageParser.Package pkg = mPackages.get(packageName); 3598 if (pkg != null) { 3599 if (!pkg.isSystem()) { 3600 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3601 continue; 3602 } 3603 3604 ArraySet<String> domains = null; 3605 for (PackageParser.Activity a : pkg.activities) { 3606 for (ActivityIntentInfo filter : a.intents) { 3607 if (hasValidDomains(filter)) { 3608 if (domains == null) { 3609 domains = new ArraySet<String>(); 3610 } 3611 domains.addAll(filter.getHostsList()); 3612 } 3613 } 3614 } 3615 3616 if (domains != null && domains.size() > 0) { 3617 if (DEBUG_DOMAIN_VERIFICATION) { 3618 Slog.v(TAG, " + " + packageName); 3619 } 3620 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3621 // state w.r.t. the formal app-linkage "no verification attempted" state; 3622 // and then 'always' in the per-user state actually used for intent resolution. 3623 final IntentFilterVerificationInfo ivi; 3624 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3625 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3626 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3627 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3628 } else { 3629 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3630 + "' does not handle web links"); 3631 } 3632 } else { 3633 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3634 } 3635 } 3636 3637 scheduleWritePackageRestrictionsLocked(userId); 3638 scheduleWriteSettingsLocked(); 3639 } 3640 3641 private void applyFactoryDefaultBrowserLPw(int userId) { 3642 // The default browser app's package name is stored in a string resource, 3643 // with a product-specific overlay used for vendor customization. 3644 String browserPkg = mContext.getResources().getString( 3645 com.android.internal.R.string.default_browser); 3646 if (!TextUtils.isEmpty(browserPkg)) { 3647 // non-empty string => required to be a known package 3648 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3649 if (ps == null) { 3650 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3651 browserPkg = null; 3652 } else { 3653 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3654 } 3655 } 3656 3657 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3658 // default. If there's more than one, just leave everything alone. 3659 if (browserPkg == null) { 3660 calculateDefaultBrowserLPw(userId); 3661 } 3662 } 3663 3664 private void calculateDefaultBrowserLPw(int userId) { 3665 List<String> allBrowsers = resolveAllBrowserApps(userId); 3666 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3667 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3668 } 3669 3670 private List<String> resolveAllBrowserApps(int userId) { 3671 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3672 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3673 PackageManager.MATCH_ALL, userId); 3674 3675 final int count = list.size(); 3676 List<String> result = new ArrayList<String>(count); 3677 for (int i=0; i<count; i++) { 3678 ResolveInfo info = list.get(i); 3679 if (info.activityInfo == null 3680 || !info.handleAllWebDataURI 3681 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3682 || result.contains(info.activityInfo.packageName)) { 3683 continue; 3684 } 3685 result.add(info.activityInfo.packageName); 3686 } 3687 3688 return result; 3689 } 3690 3691 private boolean packageIsBrowser(String packageName, int userId) { 3692 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3693 PackageManager.MATCH_ALL, userId); 3694 final int N = list.size(); 3695 for (int i = 0; i < N; i++) { 3696 ResolveInfo info = list.get(i); 3697 if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) { 3698 return true; 3699 } 3700 } 3701 return false; 3702 } 3703 3704 private void checkDefaultBrowser() { 3705 final int myUserId = UserHandle.myUserId(); 3706 final String packageName = getDefaultBrowserPackageName(myUserId); 3707 if (packageName != null) { 3708 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3709 if (info == null) { 3710 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3711 synchronized (mPackages) { 3712 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3713 } 3714 } 3715 } 3716 } 3717 3718 @Override 3719 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3720 throws RemoteException { 3721 try { 3722 return super.onTransact(code, data, reply, flags); 3723 } catch (RuntimeException e) { 3724 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3725 Slog.wtf(TAG, "Package Manager Crash", e); 3726 } 3727 throw e; 3728 } 3729 } 3730 3731 static int[] appendInts(int[] cur, int[] add) { 3732 if (add == null) return cur; 3733 if (cur == null) return add; 3734 final int N = add.length; 3735 for (int i=0; i<N; i++) { 3736 cur = appendInt(cur, add[i]); 3737 } 3738 return cur; 3739 } 3740 3741 /** 3742 * Returns whether or not a full application can see an instant application. 3743 * <p> 3744 * Currently, there are three cases in which this can occur: 3745 * <ol> 3746 * <li>The calling application is a "special" process. Special processes 3747 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 3748 * <li>The calling application has the permission 3749 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 3750 * <li>The calling application is the default launcher on the 3751 * system partition.</li> 3752 * </ol> 3753 */ 3754 private boolean canViewInstantApps(int callingUid, int userId) { 3755 if (callingUid < Process.FIRST_APPLICATION_UID) { 3756 return true; 3757 } 3758 if (mContext.checkCallingOrSelfPermission( 3759 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3760 return true; 3761 } 3762 if (mContext.checkCallingOrSelfPermission( 3763 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3764 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3765 if (homeComponent != null 3766 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3767 return true; 3768 } 3769 } 3770 return false; 3771 } 3772 3773 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3774 if (!sUserManager.exists(userId)) return null; 3775 if (ps == null) { 3776 return null; 3777 } 3778 PackageParser.Package p = ps.pkg; 3779 if (p == null) { 3780 return null; 3781 } 3782 final int callingUid = Binder.getCallingUid(); 3783 // Filter out ephemeral app metadata: 3784 // * The system/shell/root can see metadata for any app 3785 // * An installed app can see metadata for 1) other installed apps 3786 // and 2) ephemeral apps that have explicitly interacted with it 3787 // * Ephemeral apps can only see their own data and exposed installed apps 3788 // * Holding a signature permission allows seeing instant apps 3789 if (filterAppAccessLPr(ps, callingUid, userId)) { 3790 return null; 3791 } 3792 3793 final PermissionsState permissionsState = ps.getPermissionsState(); 3794 3795 // Compute GIDs only if requested 3796 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3797 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3798 // Compute granted permissions only if package has requested permissions 3799 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3800 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3801 final PackageUserState state = ps.readUserState(userId); 3802 3803 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3804 && ps.isSystem()) { 3805 flags |= MATCH_ANY_USER; 3806 } 3807 3808 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3809 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3810 3811 if (packageInfo == null) { 3812 return null; 3813 } 3814 3815 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3816 resolveExternalPackageNameLPr(p); 3817 3818 return packageInfo; 3819 } 3820 3821 @Override 3822 public void checkPackageStartable(String packageName, int userId) { 3823 final int callingUid = Binder.getCallingUid(); 3824 if (getInstantAppPackageName(callingUid) != null) { 3825 throw new SecurityException("Instant applications don't have access to this method"); 3826 } 3827 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3828 synchronized (mPackages) { 3829 final PackageSetting ps = mSettings.mPackages.get(packageName); 3830 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 3831 throw new SecurityException("Package " + packageName + " was not found!"); 3832 } 3833 3834 if (!ps.getInstalled(userId)) { 3835 throw new SecurityException( 3836 "Package " + packageName + " was not installed for user " + userId + "!"); 3837 } 3838 3839 if (mSafeMode && !ps.isSystem()) { 3840 throw new SecurityException("Package " + packageName + " not a system app!"); 3841 } 3842 3843 if (mFrozenPackages.contains(packageName)) { 3844 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3845 } 3846 3847 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) { 3848 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3849 } 3850 } 3851 } 3852 3853 @Override 3854 public boolean isPackageAvailable(String packageName, int userId) { 3855 if (!sUserManager.exists(userId)) return false; 3856 final int callingUid = Binder.getCallingUid(); 3857 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 3858 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 3859 synchronized (mPackages) { 3860 PackageParser.Package p = mPackages.get(packageName); 3861 if (p != null) { 3862 final PackageSetting ps = (PackageSetting) p.mExtras; 3863 if (filterAppAccessLPr(ps, callingUid, userId)) { 3864 return false; 3865 } 3866 if (ps != null) { 3867 final PackageUserState state = ps.readUserState(userId); 3868 if (state != null) { 3869 return PackageParser.isAvailable(state); 3870 } 3871 } 3872 } 3873 } 3874 return false; 3875 } 3876 3877 @Override 3878 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3879 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3880 flags, Binder.getCallingUid(), userId); 3881 } 3882 3883 @Override 3884 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3885 int flags, int userId) { 3886 return getPackageInfoInternal(versionedPackage.getPackageName(), 3887 versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId); 3888 } 3889 3890 /** 3891 * Important: The provided filterCallingUid is used exclusively to filter out packages 3892 * that can be seen based on user state. It's typically the original caller uid prior 3893 * to clearing. Because it can only be provided by trusted code, it's value can be 3894 * trusted and will be used as-is; unlike userId which will be validated by this method. 3895 */ 3896 private PackageInfo getPackageInfoInternal(String packageName, long versionCode, 3897 int flags, int filterCallingUid, int userId) { 3898 if (!sUserManager.exists(userId)) return null; 3899 flags = updateFlagsForPackage(flags, userId, packageName); 3900 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 3901 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3902 3903 // reader 3904 synchronized (mPackages) { 3905 // Normalize package name to handle renamed packages and static libs 3906 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3907 3908 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3909 if (matchFactoryOnly) { 3910 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3911 if (ps != null) { 3912 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3913 return null; 3914 } 3915 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3916 return null; 3917 } 3918 return generatePackageInfo(ps, flags, userId); 3919 } 3920 } 3921 3922 PackageParser.Package p = mPackages.get(packageName); 3923 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3924 return null; 3925 } 3926 if (DEBUG_PACKAGE_INFO) 3927 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3928 if (p != null) { 3929 final PackageSetting ps = (PackageSetting) p.mExtras; 3930 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3931 return null; 3932 } 3933 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 3934 return null; 3935 } 3936 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3937 } 3938 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3939 final PackageSetting ps = mSettings.mPackages.get(packageName); 3940 if (ps == null) return null; 3941 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3942 return null; 3943 } 3944 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3945 return null; 3946 } 3947 return generatePackageInfo(ps, flags, userId); 3948 } 3949 } 3950 return null; 3951 } 3952 3953 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 3954 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 3955 return true; 3956 } 3957 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 3958 return true; 3959 } 3960 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 3961 return true; 3962 } 3963 return false; 3964 } 3965 3966 private boolean isComponentVisibleToInstantApp( 3967 @Nullable ComponentName component, @ComponentType int type) { 3968 if (type == TYPE_ACTIVITY) { 3969 final PackageParser.Activity activity = mActivities.mActivities.get(component); 3970 return activity != null 3971 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3972 : false; 3973 } else if (type == TYPE_RECEIVER) { 3974 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 3975 return activity != null 3976 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3977 : false; 3978 } else if (type == TYPE_SERVICE) { 3979 final PackageParser.Service service = mServices.mServices.get(component); 3980 return service != null 3981 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3982 : false; 3983 } else if (type == TYPE_PROVIDER) { 3984 final PackageParser.Provider provider = mProviders.mProviders.get(component); 3985 return provider != null 3986 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3987 : false; 3988 } else if (type == TYPE_UNKNOWN) { 3989 return isComponentVisibleToInstantApp(component); 3990 } 3991 return false; 3992 } 3993 3994 /** 3995 * Returns whether or not access to the application should be filtered. 3996 * <p> 3997 * Access may be limited based upon whether the calling or target applications 3998 * are instant applications. 3999 * 4000 * @see #canAccessInstantApps(int) 4001 */ 4002 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 4003 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 4004 // if we're in an isolated process, get the real calling UID 4005 if (Process.isIsolated(callingUid)) { 4006 callingUid = mIsolatedOwners.get(callingUid); 4007 } 4008 final String instantAppPkgName = getInstantAppPackageName(callingUid); 4009 final boolean callerIsInstantApp = instantAppPkgName != null; 4010 if (ps == null) { 4011 if (callerIsInstantApp) { 4012 // pretend the application exists, but, needs to be filtered 4013 return true; 4014 } 4015 return false; 4016 } 4017 // if the target and caller are the same application, don't filter 4018 if (isCallerSameApp(ps.name, callingUid)) { 4019 return false; 4020 } 4021 if (callerIsInstantApp) { 4022 // request for a specific component; if it hasn't been explicitly exposed, filter 4023 if (component != null) { 4024 return !isComponentVisibleToInstantApp(component, componentType); 4025 } 4026 // request for application; if no components have been explicitly exposed, filter 4027 return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps; 4028 } 4029 if (ps.getInstantApp(userId)) { 4030 // caller can see all components of all instant applications, don't filter 4031 if (canViewInstantApps(callingUid, userId)) { 4032 return false; 4033 } 4034 // request for a specific instant application component, filter 4035 if (component != null) { 4036 return true; 4037 } 4038 // request for an instant application; if the caller hasn't been granted access, filter 4039 return !mInstantAppRegistry.isInstantAccessGranted( 4040 userId, UserHandle.getAppId(callingUid), ps.appId); 4041 } 4042 return false; 4043 } 4044 4045 /** 4046 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 4047 */ 4048 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 4049 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 4050 } 4051 4052 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 4053 int flags) { 4054 // Callers can access only the libs they depend on, otherwise they need to explicitly 4055 // ask for the shared libraries given the caller is allowed to access all static libs. 4056 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 4057 // System/shell/root get to see all static libs 4058 final int appId = UserHandle.getAppId(uid); 4059 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 4060 || appId == Process.ROOT_UID) { 4061 return false; 4062 } 4063 } 4064 4065 // No package means no static lib as it is always on internal storage 4066 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4067 return false; 4068 } 4069 4070 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 4071 ps.pkg.staticSharedLibVersion); 4072 if (libEntry == null) { 4073 return false; 4074 } 4075 4076 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 4077 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 4078 if (uidPackageNames == null) { 4079 return true; 4080 } 4081 4082 for (String uidPackageName : uidPackageNames) { 4083 if (ps.name.equals(uidPackageName)) { 4084 return false; 4085 } 4086 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 4087 if (uidPs != null) { 4088 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 4089 libEntry.info.getName()); 4090 if (index < 0) { 4091 continue; 4092 } 4093 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) { 4094 return false; 4095 } 4096 } 4097 } 4098 return true; 4099 } 4100 4101 @Override 4102 public String[] currentToCanonicalPackageNames(String[] names) { 4103 final int callingUid = Binder.getCallingUid(); 4104 if (getInstantAppPackageName(callingUid) != null) { 4105 return names; 4106 } 4107 final String[] out = new String[names.length]; 4108 // reader 4109 synchronized (mPackages) { 4110 final int callingUserId = UserHandle.getUserId(callingUid); 4111 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4112 for (int i=names.length-1; i>=0; i--) { 4113 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4114 boolean translateName = false; 4115 if (ps != null && ps.realName != null) { 4116 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 4117 translateName = !targetIsInstantApp 4118 || canViewInstantApps 4119 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4120 UserHandle.getAppId(callingUid), ps.appId); 4121 } 4122 out[i] = translateName ? ps.realName : names[i]; 4123 } 4124 } 4125 return out; 4126 } 4127 4128 @Override 4129 public String[] canonicalToCurrentPackageNames(String[] names) { 4130 final int callingUid = Binder.getCallingUid(); 4131 if (getInstantAppPackageName(callingUid) != null) { 4132 return names; 4133 } 4134 final String[] out = new String[names.length]; 4135 // reader 4136 synchronized (mPackages) { 4137 final int callingUserId = UserHandle.getUserId(callingUid); 4138 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4139 for (int i=names.length-1; i>=0; i--) { 4140 final String cur = mSettings.getRenamedPackageLPr(names[i]); 4141 boolean translateName = false; 4142 if (cur != null) { 4143 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4144 final boolean targetIsInstantApp = 4145 ps != null && ps.getInstantApp(callingUserId); 4146 translateName = !targetIsInstantApp 4147 || canViewInstantApps 4148 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4149 UserHandle.getAppId(callingUid), ps.appId); 4150 } 4151 out[i] = translateName ? cur : names[i]; 4152 } 4153 } 4154 return out; 4155 } 4156 4157 @Override 4158 public int getPackageUid(String packageName, int flags, int userId) { 4159 if (!sUserManager.exists(userId)) return -1; 4160 final int callingUid = Binder.getCallingUid(); 4161 flags = updateFlagsForPackage(flags, userId, packageName); 4162 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4163 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 4164 4165 // reader 4166 synchronized (mPackages) { 4167 final PackageParser.Package p = mPackages.get(packageName); 4168 if (p != null && p.isMatch(flags)) { 4169 PackageSetting ps = (PackageSetting) p.mExtras; 4170 if (filterAppAccessLPr(ps, callingUid, userId)) { 4171 return -1; 4172 } 4173 return UserHandle.getUid(userId, p.applicationInfo.uid); 4174 } 4175 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4176 final PackageSetting ps = mSettings.mPackages.get(packageName); 4177 if (ps != null && ps.isMatch(flags) 4178 && !filterAppAccessLPr(ps, callingUid, userId)) { 4179 return UserHandle.getUid(userId, ps.appId); 4180 } 4181 } 4182 } 4183 4184 return -1; 4185 } 4186 4187 @Override 4188 public int[] getPackageGids(String packageName, int flags, int userId) { 4189 if (!sUserManager.exists(userId)) return null; 4190 final int callingUid = Binder.getCallingUid(); 4191 flags = updateFlagsForPackage(flags, userId, packageName); 4192 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4193 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 4194 4195 // reader 4196 synchronized (mPackages) { 4197 final PackageParser.Package p = mPackages.get(packageName); 4198 if (p != null && p.isMatch(flags)) { 4199 PackageSetting ps = (PackageSetting) p.mExtras; 4200 if (filterAppAccessLPr(ps, callingUid, userId)) { 4201 return null; 4202 } 4203 // TODO: Shouldn't this be checking for package installed state for userId and 4204 // return null? 4205 return ps.getPermissionsState().computeGids(userId); 4206 } 4207 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4208 final PackageSetting ps = mSettings.mPackages.get(packageName); 4209 if (ps != null && ps.isMatch(flags) 4210 && !filterAppAccessLPr(ps, callingUid, userId)) { 4211 return ps.getPermissionsState().computeGids(userId); 4212 } 4213 } 4214 } 4215 4216 return null; 4217 } 4218 4219 @Override 4220 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4221 return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid()); 4222 } 4223 4224 @Override 4225 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName, 4226 int flags) { 4227 final List<PermissionInfo> permissionList = 4228 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()); 4229 return (permissionList == null) ? null : new ParceledListSlice<>(permissionList); 4230 } 4231 4232 @Override 4233 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) { 4234 return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid()); 4235 } 4236 4237 @Override 4238 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4239 final List<PermissionGroupInfo> permissionList = 4240 mPermissionManager.getAllPermissionGroups(flags, getCallingUid()); 4241 return (permissionList == null) 4242 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList); 4243 } 4244 4245 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4246 int filterCallingUid, int userId) { 4247 if (!sUserManager.exists(userId)) return null; 4248 PackageSetting ps = mSettings.mPackages.get(packageName); 4249 if (ps != null) { 4250 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4251 return null; 4252 } 4253 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4254 return null; 4255 } 4256 if (ps.pkg == null) { 4257 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4258 if (pInfo != null) { 4259 return pInfo.applicationInfo; 4260 } 4261 return null; 4262 } 4263 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4264 ps.readUserState(userId), userId); 4265 if (ai != null) { 4266 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4267 } 4268 return ai; 4269 } 4270 return null; 4271 } 4272 4273 @Override 4274 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4275 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4276 } 4277 4278 /** 4279 * Important: The provided filterCallingUid is used exclusively to filter out applications 4280 * that can be seen based on user state. It's typically the original caller uid prior 4281 * to clearing. Because it can only be provided by trusted code, it's value can be 4282 * trusted and will be used as-is; unlike userId which will be validated by this method. 4283 */ 4284 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4285 int filterCallingUid, int userId) { 4286 if (!sUserManager.exists(userId)) return null; 4287 flags = updateFlagsForApplication(flags, userId, packageName); 4288 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4289 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4290 4291 // writer 4292 synchronized (mPackages) { 4293 // Normalize package name to handle renamed packages and static libs 4294 packageName = resolveInternalPackageNameLPr(packageName, 4295 PackageManager.VERSION_CODE_HIGHEST); 4296 4297 PackageParser.Package p = mPackages.get(packageName); 4298 if (DEBUG_PACKAGE_INFO) Log.v( 4299 TAG, "getApplicationInfo " + packageName 4300 + ": " + p); 4301 if (p != null) { 4302 PackageSetting ps = mSettings.mPackages.get(packageName); 4303 if (ps == null) return null; 4304 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4305 return null; 4306 } 4307 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4308 return null; 4309 } 4310 // Note: isEnabledLP() does not apply here - always return info 4311 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4312 p, flags, ps.readUserState(userId), userId); 4313 if (ai != null) { 4314 ai.packageName = resolveExternalPackageNameLPr(p); 4315 } 4316 return ai; 4317 } 4318 if ("android".equals(packageName)||"system".equals(packageName)) { 4319 return mAndroidApplication; 4320 } 4321 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4322 // Already generates the external package name 4323 return generateApplicationInfoFromSettingsLPw(packageName, 4324 flags, filterCallingUid, userId); 4325 } 4326 } 4327 return null; 4328 } 4329 4330 private String normalizePackageNameLPr(String packageName) { 4331 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4332 return normalizedPackageName != null ? normalizedPackageName : packageName; 4333 } 4334 4335 @Override 4336 public void deletePreloadsFileCache() { 4337 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4338 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4339 } 4340 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4341 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4342 FileUtils.deleteContents(dir); 4343 } 4344 4345 @Override 4346 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4347 final int storageFlags, final IPackageDataObserver observer) { 4348 mContext.enforceCallingOrSelfPermission( 4349 android.Manifest.permission.CLEAR_APP_CACHE, null); 4350 mHandler.post(() -> { 4351 boolean success = false; 4352 try { 4353 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4354 success = true; 4355 } catch (IOException e) { 4356 Slog.w(TAG, e); 4357 } 4358 if (observer != null) { 4359 try { 4360 observer.onRemoveCompleted(null, success); 4361 } catch (RemoteException e) { 4362 Slog.w(TAG, e); 4363 } 4364 } 4365 }); 4366 } 4367 4368 @Override 4369 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4370 final int storageFlags, final IntentSender pi) { 4371 mContext.enforceCallingOrSelfPermission( 4372 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4373 mHandler.post(() -> { 4374 boolean success = false; 4375 try { 4376 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4377 success = true; 4378 } catch (IOException e) { 4379 Slog.w(TAG, e); 4380 } 4381 if (pi != null) { 4382 try { 4383 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4384 } catch (SendIntentException e) { 4385 Slog.w(TAG, e); 4386 } 4387 } 4388 }); 4389 } 4390 4391 /** 4392 * Blocking call to clear various types of cached data across the system 4393 * until the requested bytes are available. 4394 */ 4395 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4396 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4397 final File file = storage.findPathForUuid(volumeUuid); 4398 if (file.getUsableSpace() >= bytes) return; 4399 4400 if (ENABLE_FREE_CACHE_V2) { 4401 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4402 volumeUuid); 4403 final boolean aggressive = (storageFlags 4404 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4405 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags); 4406 4407 // 1. Pre-flight to determine if we have any chance to succeed 4408 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4409 if (internalVolume && (aggressive || SystemProperties 4410 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4411 deletePreloadsFileCache(); 4412 if (file.getUsableSpace() >= bytes) return; 4413 } 4414 4415 // 3. Consider parsed APK data (aggressive only) 4416 if (internalVolume && aggressive) { 4417 FileUtils.deleteContents(mCacheDir); 4418 if (file.getUsableSpace() >= bytes) return; 4419 } 4420 4421 // 4. Consider cached app data (above quotas) 4422 try { 4423 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4424 Installer.FLAG_FREE_CACHE_V2); 4425 } catch (InstallerException ignored) { 4426 } 4427 if (file.getUsableSpace() >= bytes) return; 4428 4429 // 5. Consider shared libraries with refcount=0 and age>min cache period 4430 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4431 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4432 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4433 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4434 return; 4435 } 4436 4437 // 6. Consider dexopt output (aggressive only) 4438 // TODO: Implement 4439 4440 // 7. Consider installed instant apps unused longer than min cache period 4441 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4442 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4443 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4444 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4445 return; 4446 } 4447 4448 // 8. Consider cached app data (below quotas) 4449 try { 4450 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4451 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4452 } catch (InstallerException ignored) { 4453 } 4454 if (file.getUsableSpace() >= bytes) return; 4455 4456 // 9. Consider DropBox entries 4457 // TODO: Implement 4458 4459 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4460 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4461 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4462 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4463 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4464 return; 4465 } 4466 } else { 4467 try { 4468 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4469 } catch (InstallerException ignored) { 4470 } 4471 if (file.getUsableSpace() >= bytes) return; 4472 } 4473 4474 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4475 } 4476 4477 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4478 throws IOException { 4479 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4480 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4481 4482 List<VersionedPackage> packagesToDelete = null; 4483 final long now = System.currentTimeMillis(); 4484 4485 synchronized (mPackages) { 4486 final int[] allUsers = sUserManager.getUserIds(); 4487 final int libCount = mSharedLibraries.size(); 4488 for (int i = 0; i < libCount; i++) { 4489 final LongSparseArray<SharedLibraryEntry> versionedLib 4490 = mSharedLibraries.valueAt(i); 4491 if (versionedLib == null) { 4492 continue; 4493 } 4494 final int versionCount = versionedLib.size(); 4495 for (int j = 0; j < versionCount; j++) { 4496 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4497 // Skip packages that are not static shared libs. 4498 if (!libInfo.isStatic()) { 4499 break; 4500 } 4501 // Important: We skip static shared libs used for some user since 4502 // in such a case we need to keep the APK on the device. The check for 4503 // a lib being used for any user is performed by the uninstall call. 4504 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4505 // Resolve the package name - we use synthetic package names internally 4506 final String internalPackageName = resolveInternalPackageNameLPr( 4507 declaringPackage.getPackageName(), 4508 declaringPackage.getLongVersionCode()); 4509 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4510 // Skip unused static shared libs cached less than the min period 4511 // to prevent pruning a lib needed by a subsequently installed package. 4512 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4513 continue; 4514 } 4515 if (packagesToDelete == null) { 4516 packagesToDelete = new ArrayList<>(); 4517 } 4518 packagesToDelete.add(new VersionedPackage(internalPackageName, 4519 declaringPackage.getLongVersionCode())); 4520 } 4521 } 4522 } 4523 4524 if (packagesToDelete != null) { 4525 final int packageCount = packagesToDelete.size(); 4526 for (int i = 0; i < packageCount; i++) { 4527 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4528 // Delete the package synchronously (will fail of the lib used for any user). 4529 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(), 4530 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4531 == PackageManager.DELETE_SUCCEEDED) { 4532 if (volume.getUsableSpace() >= neededSpace) { 4533 return true; 4534 } 4535 } 4536 } 4537 } 4538 4539 return false; 4540 } 4541 4542 /** 4543 * Update given flags based on encryption status of current user. 4544 */ 4545 private int updateFlags(int flags, int userId) { 4546 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4547 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4548 // Caller expressed an explicit opinion about what encryption 4549 // aware/unaware components they want to see, so fall through and 4550 // give them what they want 4551 } else { 4552 // Caller expressed no opinion, so match based on user state 4553 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4554 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4555 } else { 4556 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4557 } 4558 } 4559 return flags; 4560 } 4561 4562 private UserManagerInternal getUserManagerInternal() { 4563 if (mUserManagerInternal == null) { 4564 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4565 } 4566 return mUserManagerInternal; 4567 } 4568 4569 private DeviceIdleController.LocalService getDeviceIdleController() { 4570 if (mDeviceIdleController == null) { 4571 mDeviceIdleController = 4572 LocalServices.getService(DeviceIdleController.LocalService.class); 4573 } 4574 return mDeviceIdleController; 4575 } 4576 4577 /** 4578 * Update given flags when being used to request {@link PackageInfo}. 4579 */ 4580 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4581 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4582 boolean triaged = true; 4583 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4584 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4585 // Caller is asking for component details, so they'd better be 4586 // asking for specific encryption matching behavior, or be triaged 4587 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4588 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4589 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4590 triaged = false; 4591 } 4592 } 4593 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4594 | PackageManager.MATCH_SYSTEM_ONLY 4595 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4596 triaged = false; 4597 } 4598 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4599 mPermissionManager.enforceCrossUserPermission( 4600 Binder.getCallingUid(), userId, false, false, 4601 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4602 + Debug.getCallers(5)); 4603 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4604 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4605 // If the caller wants all packages and has a restricted profile associated with it, 4606 // then match all users. This is to make sure that launchers that need to access work 4607 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4608 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4609 flags |= PackageManager.MATCH_ANY_USER; 4610 } 4611 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4612 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4613 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4614 } 4615 return updateFlags(flags, userId); 4616 } 4617 4618 /** 4619 * Update given flags when being used to request {@link ApplicationInfo}. 4620 */ 4621 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4622 return updateFlagsForPackage(flags, userId, cookie); 4623 } 4624 4625 /** 4626 * Update given flags when being used to request {@link ComponentInfo}. 4627 */ 4628 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4629 if (cookie instanceof Intent) { 4630 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4631 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4632 } 4633 } 4634 4635 boolean triaged = true; 4636 // Caller is asking for component details, so they'd better be 4637 // asking for specific encryption matching behavior, or be triaged 4638 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4639 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4640 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4641 triaged = false; 4642 } 4643 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4644 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4645 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4646 } 4647 4648 return updateFlags(flags, userId); 4649 } 4650 4651 /** 4652 * Update given intent when being used to request {@link ResolveInfo}. 4653 */ 4654 private Intent updateIntentForResolve(Intent intent) { 4655 if (intent.getSelector() != null) { 4656 intent = intent.getSelector(); 4657 } 4658 if (DEBUG_PREFERRED) { 4659 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4660 } 4661 return intent; 4662 } 4663 4664 /** 4665 * Update given flags when being used to request {@link ResolveInfo}. 4666 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4667 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4668 * flag set. However, this flag is only honoured in three circumstances: 4669 * <ul> 4670 * <li>when called from a system process</li> 4671 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4672 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4673 * action and a {@code android.intent.category.BROWSABLE} category</li> 4674 * </ul> 4675 */ 4676 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4677 return updateFlagsForResolve(flags, userId, intent, callingUid, 4678 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4679 } 4680 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4681 boolean wantInstantApps) { 4682 return updateFlagsForResolve(flags, userId, intent, callingUid, 4683 wantInstantApps, false /*onlyExposedExplicitly*/); 4684 } 4685 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4686 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4687 // Safe mode means we shouldn't match any third-party components 4688 if (mSafeMode) { 4689 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4690 } 4691 if (getInstantAppPackageName(callingUid) != null) { 4692 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4693 if (onlyExposedExplicitly) { 4694 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4695 } 4696 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4697 flags |= PackageManager.MATCH_INSTANT; 4698 } else { 4699 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 4700 final boolean allowMatchInstant = 4701 (wantInstantApps 4702 && Intent.ACTION_VIEW.equals(intent.getAction()) 4703 && hasWebURI(intent)) 4704 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 4705 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4706 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4707 if (!allowMatchInstant) { 4708 flags &= ~PackageManager.MATCH_INSTANT; 4709 } 4710 } 4711 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4712 } 4713 4714 @Override 4715 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4716 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 4717 } 4718 4719 /** 4720 * Important: The provided filterCallingUid is used exclusively to filter out activities 4721 * that can be seen based on user state. It's typically the original caller uid prior 4722 * to clearing. Because it can only be provided by trusted code, it's value can be 4723 * trusted and will be used as-is; unlike userId which will be validated by this method. 4724 */ 4725 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 4726 int filterCallingUid, int userId) { 4727 if (!sUserManager.exists(userId)) return null; 4728 flags = updateFlagsForComponent(flags, userId, component); 4729 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4730 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4731 synchronized (mPackages) { 4732 PackageParser.Activity a = mActivities.mActivities.get(component); 4733 4734 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4735 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4736 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4737 if (ps == null) return null; 4738 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 4739 return null; 4740 } 4741 return PackageParser.generateActivityInfo( 4742 a, flags, ps.readUserState(userId), userId); 4743 } 4744 if (mResolveComponentName.equals(component)) { 4745 return PackageParser.generateActivityInfo( 4746 mResolveActivity, flags, new PackageUserState(), userId); 4747 } 4748 } 4749 return null; 4750 } 4751 4752 @Override 4753 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4754 String resolvedType) { 4755 synchronized (mPackages) { 4756 if (component.equals(mResolveComponentName)) { 4757 // The resolver supports EVERYTHING! 4758 return true; 4759 } 4760 final int callingUid = Binder.getCallingUid(); 4761 final int callingUserId = UserHandle.getUserId(callingUid); 4762 PackageParser.Activity a = mActivities.mActivities.get(component); 4763 if (a == null) { 4764 return false; 4765 } 4766 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4767 if (ps == null) { 4768 return false; 4769 } 4770 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4771 return false; 4772 } 4773 for (int i=0; i<a.intents.size(); i++) { 4774 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4775 intent.getData(), intent.getCategories(), TAG) >= 0) { 4776 return true; 4777 } 4778 } 4779 return false; 4780 } 4781 } 4782 4783 @Override 4784 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4785 if (!sUserManager.exists(userId)) return null; 4786 final int callingUid = Binder.getCallingUid(); 4787 flags = updateFlagsForComponent(flags, userId, component); 4788 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4789 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4790 synchronized (mPackages) { 4791 PackageParser.Activity a = mReceivers.mActivities.get(component); 4792 if (DEBUG_PACKAGE_INFO) Log.v( 4793 TAG, "getReceiverInfo " + component + ": " + a); 4794 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4795 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4796 if (ps == null) return null; 4797 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4798 return null; 4799 } 4800 return PackageParser.generateActivityInfo( 4801 a, flags, ps.readUserState(userId), userId); 4802 } 4803 } 4804 return null; 4805 } 4806 4807 @Override 4808 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4809 int flags, int userId) { 4810 if (!sUserManager.exists(userId)) return null; 4811 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4812 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4813 return null; 4814 } 4815 4816 flags = updateFlagsForPackage(flags, userId, null); 4817 4818 final boolean canSeeStaticLibraries = 4819 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4820 == PERMISSION_GRANTED 4821 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4822 == PERMISSION_GRANTED 4823 || canRequestPackageInstallsInternal(packageName, 4824 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 4825 false /* throwIfPermNotDeclared*/) 4826 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4827 == PERMISSION_GRANTED; 4828 4829 synchronized (mPackages) { 4830 List<SharedLibraryInfo> result = null; 4831 4832 final int libCount = mSharedLibraries.size(); 4833 for (int i = 0; i < libCount; i++) { 4834 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4835 if (versionedLib == null) { 4836 continue; 4837 } 4838 4839 final int versionCount = versionedLib.size(); 4840 for (int j = 0; j < versionCount; j++) { 4841 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4842 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4843 break; 4844 } 4845 final long identity = Binder.clearCallingIdentity(); 4846 try { 4847 PackageInfo packageInfo = getPackageInfoVersioned( 4848 libInfo.getDeclaringPackage(), flags 4849 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 4850 if (packageInfo == null) { 4851 continue; 4852 } 4853 } finally { 4854 Binder.restoreCallingIdentity(identity); 4855 } 4856 4857 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4858 libInfo.getLongVersion(), libInfo.getType(), 4859 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 4860 flags, userId)); 4861 4862 if (result == null) { 4863 result = new ArrayList<>(); 4864 } 4865 result.add(resLibInfo); 4866 } 4867 } 4868 4869 return result != null ? new ParceledListSlice<>(result) : null; 4870 } 4871 } 4872 4873 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4874 SharedLibraryInfo libInfo, int flags, int userId) { 4875 List<VersionedPackage> versionedPackages = null; 4876 final int packageCount = mSettings.mPackages.size(); 4877 for (int i = 0; i < packageCount; i++) { 4878 PackageSetting ps = mSettings.mPackages.valueAt(i); 4879 4880 if (ps == null) { 4881 continue; 4882 } 4883 4884 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4885 continue; 4886 } 4887 4888 final String libName = libInfo.getName(); 4889 if (libInfo.isStatic()) { 4890 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4891 if (libIdx < 0) { 4892 continue; 4893 } 4894 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) { 4895 continue; 4896 } 4897 if (versionedPackages == null) { 4898 versionedPackages = new ArrayList<>(); 4899 } 4900 // If the dependent is a static shared lib, use the public package name 4901 String dependentPackageName = ps.name; 4902 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4903 dependentPackageName = ps.pkg.manifestPackageName; 4904 } 4905 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4906 } else if (ps.pkg != null) { 4907 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4908 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4909 if (versionedPackages == null) { 4910 versionedPackages = new ArrayList<>(); 4911 } 4912 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4913 } 4914 } 4915 } 4916 4917 return versionedPackages; 4918 } 4919 4920 @Override 4921 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4922 if (!sUserManager.exists(userId)) return null; 4923 final int callingUid = Binder.getCallingUid(); 4924 flags = updateFlagsForComponent(flags, userId, component); 4925 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4926 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4927 synchronized (mPackages) { 4928 PackageParser.Service s = mServices.mServices.get(component); 4929 if (DEBUG_PACKAGE_INFO) Log.v( 4930 TAG, "getServiceInfo " + component + ": " + s); 4931 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4932 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4933 if (ps == null) return null; 4934 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 4935 return null; 4936 } 4937 return PackageParser.generateServiceInfo( 4938 s, flags, ps.readUserState(userId), userId); 4939 } 4940 } 4941 return null; 4942 } 4943 4944 @Override 4945 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4946 if (!sUserManager.exists(userId)) return null; 4947 final int callingUid = Binder.getCallingUid(); 4948 flags = updateFlagsForComponent(flags, userId, component); 4949 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4950 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4951 synchronized (mPackages) { 4952 PackageParser.Provider p = mProviders.mProviders.get(component); 4953 if (DEBUG_PACKAGE_INFO) Log.v( 4954 TAG, "getProviderInfo " + component + ": " + p); 4955 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4956 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4957 if (ps == null) return null; 4958 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 4959 return null; 4960 } 4961 return PackageParser.generateProviderInfo( 4962 p, flags, ps.readUserState(userId), userId); 4963 } 4964 } 4965 return null; 4966 } 4967 4968 @Override 4969 public String[] getSystemSharedLibraryNames() { 4970 // allow instant applications 4971 synchronized (mPackages) { 4972 Set<String> libs = null; 4973 final int libCount = mSharedLibraries.size(); 4974 for (int i = 0; i < libCount; i++) { 4975 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4976 if (versionedLib == null) { 4977 continue; 4978 } 4979 final int versionCount = versionedLib.size(); 4980 for (int j = 0; j < versionCount; j++) { 4981 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4982 if (!libEntry.info.isStatic()) { 4983 if (libs == null) { 4984 libs = new ArraySet<>(); 4985 } 4986 libs.add(libEntry.info.getName()); 4987 break; 4988 } 4989 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4990 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4991 UserHandle.getUserId(Binder.getCallingUid()), 4992 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 4993 if (libs == null) { 4994 libs = new ArraySet<>(); 4995 } 4996 libs.add(libEntry.info.getName()); 4997 break; 4998 } 4999 } 5000 } 5001 5002 if (libs != null) { 5003 String[] libsArray = new String[libs.size()]; 5004 libs.toArray(libsArray); 5005 return libsArray; 5006 } 5007 5008 return null; 5009 } 5010 } 5011 5012 @Override 5013 public @NonNull String getServicesSystemSharedLibraryPackageName() { 5014 // allow instant applications 5015 synchronized (mPackages) { 5016 return mServicesSystemSharedLibraryPackageName; 5017 } 5018 } 5019 5020 @Override 5021 public @NonNull String getSharedSystemSharedLibraryPackageName() { 5022 // allow instant applications 5023 synchronized (mPackages) { 5024 return mSharedSystemSharedLibraryPackageName; 5025 } 5026 } 5027 5028 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 5029 for (int i = userList.length - 1; i >= 0; --i) { 5030 final int userId = userList[i]; 5031 // don't add instant app to the list of updates 5032 if (pkgSetting.getInstantApp(userId)) { 5033 continue; 5034 } 5035 SparseArray<String> changedPackages = mChangedPackages.get(userId); 5036 if (changedPackages == null) { 5037 changedPackages = new SparseArray<>(); 5038 mChangedPackages.put(userId, changedPackages); 5039 } 5040 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 5041 if (sequenceNumbers == null) { 5042 sequenceNumbers = new HashMap<>(); 5043 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 5044 } 5045 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 5046 if (sequenceNumber != null) { 5047 changedPackages.remove(sequenceNumber); 5048 } 5049 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 5050 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 5051 } 5052 mChangedPackagesSequenceNumber++; 5053 } 5054 5055 @Override 5056 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5057 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5058 return null; 5059 } 5060 synchronized (mPackages) { 5061 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 5062 return null; 5063 } 5064 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 5065 if (changedPackages == null) { 5066 return null; 5067 } 5068 final List<String> packageNames = 5069 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 5070 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 5071 final String packageName = changedPackages.get(i); 5072 if (packageName != null) { 5073 packageNames.add(packageName); 5074 } 5075 } 5076 return packageNames.isEmpty() 5077 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 5078 } 5079 } 5080 5081 @Override 5082 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5083 // allow instant applications 5084 ArrayList<FeatureInfo> res; 5085 synchronized (mAvailableFeatures) { 5086 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5087 res.addAll(mAvailableFeatures.values()); 5088 } 5089 final FeatureInfo fi = new FeatureInfo(); 5090 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5091 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5092 res.add(fi); 5093 5094 return new ParceledListSlice<>(res); 5095 } 5096 5097 @Override 5098 public boolean hasSystemFeature(String name, int version) { 5099 // allow instant applications 5100 synchronized (mAvailableFeatures) { 5101 final FeatureInfo feat = mAvailableFeatures.get(name); 5102 if (feat == null) { 5103 return false; 5104 } else { 5105 return feat.version >= version; 5106 } 5107 } 5108 } 5109 5110 @Override 5111 public int checkPermission(String permName, String pkgName, int userId) { 5112 return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId); 5113 } 5114 5115 @Override 5116 public int checkUidPermission(String permName, int uid) { 5117 return mPermissionManager.checkUidPermission(permName, uid, getCallingUid()); 5118 } 5119 5120 @Override 5121 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5122 if (UserHandle.getCallingUserId() != userId) { 5123 mContext.enforceCallingPermission( 5124 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5125 "isPermissionRevokedByPolicy for user " + userId); 5126 } 5127 5128 if (checkPermission(permission, packageName, userId) 5129 == PackageManager.PERMISSION_GRANTED) { 5130 return false; 5131 } 5132 5133 final int callingUid = Binder.getCallingUid(); 5134 if (getInstantAppPackageName(callingUid) != null) { 5135 if (!isCallerSameApp(packageName, callingUid)) { 5136 return false; 5137 } 5138 } else { 5139 if (isInstantApp(packageName, userId)) { 5140 return false; 5141 } 5142 } 5143 5144 final long identity = Binder.clearCallingIdentity(); 5145 try { 5146 final int flags = getPermissionFlags(permission, packageName, userId); 5147 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5148 } finally { 5149 Binder.restoreCallingIdentity(identity); 5150 } 5151 } 5152 5153 @Override 5154 public String getPermissionControllerPackageName() { 5155 synchronized (mPackages) { 5156 return mRequiredInstallerPackage; 5157 } 5158 } 5159 5160 private boolean addDynamicPermission(PermissionInfo info, final boolean async) { 5161 return mPermissionManager.addDynamicPermission( 5162 info, async, getCallingUid(), new PermissionCallback() { 5163 @Override 5164 public void onPermissionChanged() { 5165 if (!async) { 5166 mSettings.writeLPr(); 5167 } else { 5168 scheduleWriteSettingsLocked(); 5169 } 5170 } 5171 }); 5172 } 5173 5174 @Override 5175 public boolean addPermission(PermissionInfo info) { 5176 synchronized (mPackages) { 5177 return addDynamicPermission(info, false); 5178 } 5179 } 5180 5181 @Override 5182 public boolean addPermissionAsync(PermissionInfo info) { 5183 synchronized (mPackages) { 5184 return addDynamicPermission(info, true); 5185 } 5186 } 5187 5188 @Override 5189 public void removePermission(String permName) { 5190 mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback); 5191 } 5192 5193 @Override 5194 public void grantRuntimePermission(String packageName, String permName, final int userId) { 5195 mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/, 5196 getCallingUid(), userId, mPermissionCallback); 5197 } 5198 5199 @Override 5200 public void revokeRuntimePermission(String packageName, String permName, int userId) { 5201 mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/, 5202 getCallingUid(), userId, mPermissionCallback); 5203 } 5204 5205 @Override 5206 public void resetRuntimePermissions() { 5207 mContext.enforceCallingOrSelfPermission( 5208 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5209 "revokeRuntimePermission"); 5210 5211 int callingUid = Binder.getCallingUid(); 5212 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5213 mContext.enforceCallingOrSelfPermission( 5214 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5215 "resetRuntimePermissions"); 5216 } 5217 5218 synchronized (mPackages) { 5219 mPermissionManager.updateAllPermissions( 5220 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 5221 mPermissionCallback); 5222 for (int userId : UserManagerService.getInstance().getUserIds()) { 5223 final int packageCount = mPackages.size(); 5224 for (int i = 0; i < packageCount; i++) { 5225 PackageParser.Package pkg = mPackages.valueAt(i); 5226 if (!(pkg.mExtras instanceof PackageSetting)) { 5227 continue; 5228 } 5229 PackageSetting ps = (PackageSetting) pkg.mExtras; 5230 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5231 } 5232 } 5233 } 5234 } 5235 5236 @Override 5237 public int getPermissionFlags(String permName, String packageName, int userId) { 5238 return mPermissionManager.getPermissionFlags( 5239 permName, packageName, getCallingUid(), userId); 5240 } 5241 5242 @Override 5243 public void updatePermissionFlags(String permName, String packageName, int flagMask, 5244 int flagValues, int userId) { 5245 mPermissionManager.updatePermissionFlags( 5246 permName, packageName, flagMask, flagValues, getCallingUid(), userId, 5247 mPermissionCallback); 5248 } 5249 5250 /** 5251 * Update the permission flags for all packages and runtime permissions of a user in order 5252 * to allow device or profile owner to remove POLICY_FIXED. 5253 */ 5254 @Override 5255 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5256 synchronized (mPackages) { 5257 final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps( 5258 flagMask, flagValues, getCallingUid(), userId, mPackages.values(), 5259 mPermissionCallback); 5260 if (changed) { 5261 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5262 } 5263 } 5264 } 5265 5266 @Override 5267 public boolean shouldShowRequestPermissionRationale(String permissionName, 5268 String packageName, int userId) { 5269 if (UserHandle.getCallingUserId() != userId) { 5270 mContext.enforceCallingPermission( 5271 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5272 "canShowRequestPermissionRationale for user " + userId); 5273 } 5274 5275 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5276 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5277 return false; 5278 } 5279 5280 if (checkPermission(permissionName, packageName, userId) 5281 == PackageManager.PERMISSION_GRANTED) { 5282 return false; 5283 } 5284 5285 final int flags; 5286 5287 final long identity = Binder.clearCallingIdentity(); 5288 try { 5289 flags = getPermissionFlags(permissionName, 5290 packageName, userId); 5291 } finally { 5292 Binder.restoreCallingIdentity(identity); 5293 } 5294 5295 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5296 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5297 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5298 5299 if ((flags & fixedFlags) != 0) { 5300 return false; 5301 } 5302 5303 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5304 } 5305 5306 @Override 5307 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5308 mContext.enforceCallingOrSelfPermission( 5309 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5310 "addOnPermissionsChangeListener"); 5311 5312 synchronized (mPackages) { 5313 mOnPermissionChangeListeners.addListenerLocked(listener); 5314 } 5315 } 5316 5317 @Override 5318 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5319 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5320 throw new SecurityException("Instant applications don't have access to this method"); 5321 } 5322 synchronized (mPackages) { 5323 mOnPermissionChangeListeners.removeListenerLocked(listener); 5324 } 5325 } 5326 5327 @Override 5328 public boolean isProtectedBroadcast(String actionName) { 5329 // allow instant applications 5330 synchronized (mProtectedBroadcasts) { 5331 if (mProtectedBroadcasts.contains(actionName)) { 5332 return true; 5333 } else if (actionName != null) { 5334 // TODO: remove these terrible hacks 5335 if (actionName.startsWith("android.net.netmon.lingerExpired") 5336 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5337 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5338 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5339 return true; 5340 } 5341 } 5342 } 5343 return false; 5344 } 5345 5346 @Override 5347 public int checkSignatures(String pkg1, String pkg2) { 5348 synchronized (mPackages) { 5349 final PackageParser.Package p1 = mPackages.get(pkg1); 5350 final PackageParser.Package p2 = mPackages.get(pkg2); 5351 if (p1 == null || p1.mExtras == null 5352 || p2 == null || p2.mExtras == null) { 5353 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5354 } 5355 final int callingUid = Binder.getCallingUid(); 5356 final int callingUserId = UserHandle.getUserId(callingUid); 5357 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 5358 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 5359 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 5360 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 5361 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5362 } 5363 return compareSignatures(p1.mSignatures, p2.mSignatures); 5364 } 5365 } 5366 5367 @Override 5368 public int checkUidSignatures(int uid1, int uid2) { 5369 final int callingUid = Binder.getCallingUid(); 5370 final int callingUserId = UserHandle.getUserId(callingUid); 5371 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5372 // Map to base uids. 5373 uid1 = UserHandle.getAppId(uid1); 5374 uid2 = UserHandle.getAppId(uid2); 5375 // reader 5376 synchronized (mPackages) { 5377 Signature[] s1; 5378 Signature[] s2; 5379 Object obj = mSettings.getUserIdLPr(uid1); 5380 if (obj != null) { 5381 if (obj instanceof SharedUserSetting) { 5382 if (isCallerInstantApp) { 5383 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5384 } 5385 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5386 } else if (obj instanceof PackageSetting) { 5387 final PackageSetting ps = (PackageSetting) obj; 5388 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5389 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5390 } 5391 s1 = ps.signatures.mSignatures; 5392 } else { 5393 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5394 } 5395 } else { 5396 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5397 } 5398 obj = mSettings.getUserIdLPr(uid2); 5399 if (obj != null) { 5400 if (obj instanceof SharedUserSetting) { 5401 if (isCallerInstantApp) { 5402 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5403 } 5404 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5405 } else if (obj instanceof PackageSetting) { 5406 final PackageSetting ps = (PackageSetting) obj; 5407 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5408 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5409 } 5410 s2 = ps.signatures.mSignatures; 5411 } else { 5412 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5413 } 5414 } else { 5415 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5416 } 5417 return compareSignatures(s1, s2); 5418 } 5419 } 5420 5421 /** 5422 * This method should typically only be used when granting or revoking 5423 * permissions, since the app may immediately restart after this call. 5424 * <p> 5425 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5426 * guard your work against the app being relaunched. 5427 */ 5428 private void killUid(int appId, int userId, String reason) { 5429 final long identity = Binder.clearCallingIdentity(); 5430 try { 5431 IActivityManager am = ActivityManager.getService(); 5432 if (am != null) { 5433 try { 5434 am.killUid(appId, userId, reason); 5435 } catch (RemoteException e) { 5436 /* ignore - same process */ 5437 } 5438 } 5439 } finally { 5440 Binder.restoreCallingIdentity(identity); 5441 } 5442 } 5443 5444 /** 5445 * If the database version for this type of package (internal storage or 5446 * external storage) is less than the version where package signatures 5447 * were updated, return true. 5448 */ 5449 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5450 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5451 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5452 } 5453 5454 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5455 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5456 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5457 } 5458 5459 @Override 5460 public List<String> getAllPackages() { 5461 final int callingUid = Binder.getCallingUid(); 5462 final int callingUserId = UserHandle.getUserId(callingUid); 5463 synchronized (mPackages) { 5464 if (canViewInstantApps(callingUid, callingUserId)) { 5465 return new ArrayList<String>(mPackages.keySet()); 5466 } 5467 final String instantAppPkgName = getInstantAppPackageName(callingUid); 5468 final List<String> result = new ArrayList<>(); 5469 if (instantAppPkgName != null) { 5470 // caller is an instant application; filter unexposed applications 5471 for (PackageParser.Package pkg : mPackages.values()) { 5472 if (!pkg.visibleToInstantApps) { 5473 continue; 5474 } 5475 result.add(pkg.packageName); 5476 } 5477 } else { 5478 // caller is a normal application; filter instant applications 5479 for (PackageParser.Package pkg : mPackages.values()) { 5480 final PackageSetting ps = 5481 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 5482 if (ps != null 5483 && ps.getInstantApp(callingUserId) 5484 && !mInstantAppRegistry.isInstantAccessGranted( 5485 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 5486 continue; 5487 } 5488 result.add(pkg.packageName); 5489 } 5490 } 5491 return result; 5492 } 5493 } 5494 5495 @Override 5496 public String[] getPackagesForUid(int uid) { 5497 final int callingUid = Binder.getCallingUid(); 5498 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5499 final int userId = UserHandle.getUserId(uid); 5500 uid = UserHandle.getAppId(uid); 5501 // reader 5502 synchronized (mPackages) { 5503 Object obj = mSettings.getUserIdLPr(uid); 5504 if (obj instanceof SharedUserSetting) { 5505 if (isCallerInstantApp) { 5506 return null; 5507 } 5508 final SharedUserSetting sus = (SharedUserSetting) obj; 5509 final int N = sus.packages.size(); 5510 String[] res = new String[N]; 5511 final Iterator<PackageSetting> it = sus.packages.iterator(); 5512 int i = 0; 5513 while (it.hasNext()) { 5514 PackageSetting ps = it.next(); 5515 if (ps.getInstalled(userId)) { 5516 res[i++] = ps.name; 5517 } else { 5518 res = ArrayUtils.removeElement(String.class, res, res[i]); 5519 } 5520 } 5521 return res; 5522 } else if (obj instanceof PackageSetting) { 5523 final PackageSetting ps = (PackageSetting) obj; 5524 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 5525 return new String[]{ps.name}; 5526 } 5527 } 5528 } 5529 return null; 5530 } 5531 5532 @Override 5533 public String getNameForUid(int uid) { 5534 final int callingUid = Binder.getCallingUid(); 5535 if (getInstantAppPackageName(callingUid) != null) { 5536 return null; 5537 } 5538 synchronized (mPackages) { 5539 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5540 if (obj instanceof SharedUserSetting) { 5541 final SharedUserSetting sus = (SharedUserSetting) obj; 5542 return sus.name + ":" + sus.userId; 5543 } else if (obj instanceof PackageSetting) { 5544 final PackageSetting ps = (PackageSetting) obj; 5545 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5546 return null; 5547 } 5548 return ps.name; 5549 } 5550 return null; 5551 } 5552 } 5553 5554 @Override 5555 public String[] getNamesForUids(int[] uids) { 5556 if (uids == null || uids.length == 0) { 5557 return null; 5558 } 5559 final int callingUid = Binder.getCallingUid(); 5560 if (getInstantAppPackageName(callingUid) != null) { 5561 return null; 5562 } 5563 final String[] names = new String[uids.length]; 5564 synchronized (mPackages) { 5565 for (int i = uids.length - 1; i >= 0; i--) { 5566 final int uid = uids[i]; 5567 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5568 if (obj instanceof SharedUserSetting) { 5569 final SharedUserSetting sus = (SharedUserSetting) obj; 5570 names[i] = "shared:" + sus.name; 5571 } else if (obj instanceof PackageSetting) { 5572 final PackageSetting ps = (PackageSetting) obj; 5573 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5574 names[i] = null; 5575 } else { 5576 names[i] = ps.name; 5577 } 5578 } else { 5579 names[i] = null; 5580 } 5581 } 5582 } 5583 return names; 5584 } 5585 5586 @Override 5587 public int getUidForSharedUser(String sharedUserName) { 5588 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5589 return -1; 5590 } 5591 if (sharedUserName == null) { 5592 return -1; 5593 } 5594 // reader 5595 synchronized (mPackages) { 5596 SharedUserSetting suid; 5597 try { 5598 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5599 if (suid != null) { 5600 return suid.userId; 5601 } 5602 } catch (PackageManagerException ignore) { 5603 // can't happen, but, still need to catch it 5604 } 5605 return -1; 5606 } 5607 } 5608 5609 @Override 5610 public int getFlagsForUid(int uid) { 5611 final int callingUid = Binder.getCallingUid(); 5612 if (getInstantAppPackageName(callingUid) != null) { 5613 return 0; 5614 } 5615 synchronized (mPackages) { 5616 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5617 if (obj instanceof SharedUserSetting) { 5618 final SharedUserSetting sus = (SharedUserSetting) obj; 5619 return sus.pkgFlags; 5620 } else if (obj instanceof PackageSetting) { 5621 final PackageSetting ps = (PackageSetting) obj; 5622 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5623 return 0; 5624 } 5625 return ps.pkgFlags; 5626 } 5627 } 5628 return 0; 5629 } 5630 5631 @Override 5632 public int getPrivateFlagsForUid(int uid) { 5633 final int callingUid = Binder.getCallingUid(); 5634 if (getInstantAppPackageName(callingUid) != null) { 5635 return 0; 5636 } 5637 synchronized (mPackages) { 5638 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5639 if (obj instanceof SharedUserSetting) { 5640 final SharedUserSetting sus = (SharedUserSetting) obj; 5641 return sus.pkgPrivateFlags; 5642 } else if (obj instanceof PackageSetting) { 5643 final PackageSetting ps = (PackageSetting) obj; 5644 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5645 return 0; 5646 } 5647 return ps.pkgPrivateFlags; 5648 } 5649 } 5650 return 0; 5651 } 5652 5653 @Override 5654 public boolean isUidPrivileged(int uid) { 5655 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5656 return false; 5657 } 5658 uid = UserHandle.getAppId(uid); 5659 // reader 5660 synchronized (mPackages) { 5661 Object obj = mSettings.getUserIdLPr(uid); 5662 if (obj instanceof SharedUserSetting) { 5663 final SharedUserSetting sus = (SharedUserSetting) obj; 5664 final Iterator<PackageSetting> it = sus.packages.iterator(); 5665 while (it.hasNext()) { 5666 if (it.next().isPrivileged()) { 5667 return true; 5668 } 5669 } 5670 } else if (obj instanceof PackageSetting) { 5671 final PackageSetting ps = (PackageSetting) obj; 5672 return ps.isPrivileged(); 5673 } 5674 } 5675 return false; 5676 } 5677 5678 @Override 5679 public String[] getAppOpPermissionPackages(String permName) { 5680 return mPermissionManager.getAppOpPermissionPackages(permName); 5681 } 5682 5683 @Override 5684 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5685 int flags, int userId) { 5686 return resolveIntentInternal( 5687 intent, resolvedType, flags, userId, false /*resolveForStart*/); 5688 } 5689 5690 /** 5691 * Normally instant apps can only be resolved when they're visible to the caller. 5692 * However, if {@code resolveForStart} is {@code true}, all instant apps are visible 5693 * since we need to allow the system to start any installed application. 5694 */ 5695 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5696 int flags, int userId, boolean resolveForStart) { 5697 try { 5698 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5699 5700 if (!sUserManager.exists(userId)) return null; 5701 final int callingUid = Binder.getCallingUid(); 5702 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 5703 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5704 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5705 5706 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5707 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5708 flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/); 5709 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5710 5711 final ResolveInfo bestChoice = 5712 chooseBestActivity(intent, resolvedType, flags, query, userId); 5713 return bestChoice; 5714 } finally { 5715 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5716 } 5717 } 5718 5719 @Override 5720 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5721 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5722 throw new SecurityException( 5723 "findPersistentPreferredActivity can only be run by the system"); 5724 } 5725 if (!sUserManager.exists(userId)) { 5726 return null; 5727 } 5728 final int callingUid = Binder.getCallingUid(); 5729 intent = updateIntentForResolve(intent); 5730 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5731 final int flags = updateFlagsForResolve( 5732 0, userId, intent, callingUid, false /*includeInstantApps*/); 5733 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5734 userId); 5735 synchronized (mPackages) { 5736 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5737 userId); 5738 } 5739 } 5740 5741 @Override 5742 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5743 IntentFilter filter, int match, ComponentName activity) { 5744 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5745 return; 5746 } 5747 final int userId = UserHandle.getCallingUserId(); 5748 if (DEBUG_PREFERRED) { 5749 Log.v(TAG, "setLastChosenActivity intent=" + intent 5750 + " resolvedType=" + resolvedType 5751 + " flags=" + flags 5752 + " filter=" + filter 5753 + " match=" + match 5754 + " activity=" + activity); 5755 filter.dump(new PrintStreamPrinter(System.out), " "); 5756 } 5757 intent.setComponent(null); 5758 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5759 userId); 5760 // Find any earlier preferred or last chosen entries and nuke them 5761 findPreferredActivity(intent, resolvedType, 5762 flags, query, 0, false, true, false, userId); 5763 // Add the new activity as the last chosen for this filter 5764 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5765 "Setting last chosen"); 5766 } 5767 5768 @Override 5769 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5770 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5771 return null; 5772 } 5773 final int userId = UserHandle.getCallingUserId(); 5774 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5775 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5776 userId); 5777 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5778 false, false, false, userId); 5779 } 5780 5781 /** 5782 * Returns whether or not instant apps have been disabled remotely. 5783 */ 5784 private boolean isEphemeralDisabled() { 5785 return mEphemeralAppsDisabled; 5786 } 5787 5788 private boolean isInstantAppAllowed( 5789 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5790 boolean skipPackageCheck) { 5791 if (mInstantAppResolverConnection == null) { 5792 return false; 5793 } 5794 if (mInstantAppInstallerActivity == null) { 5795 return false; 5796 } 5797 if (intent.getComponent() != null) { 5798 return false; 5799 } 5800 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5801 return false; 5802 } 5803 if (!skipPackageCheck && intent.getPackage() != null) { 5804 return false; 5805 } 5806 final boolean isWebUri = hasWebURI(intent); 5807 if (!isWebUri || intent.getData().getHost() == null) { 5808 return false; 5809 } 5810 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5811 // Or if there's already an ephemeral app installed that handles the action 5812 synchronized (mPackages) { 5813 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5814 for (int n = 0; n < count; n++) { 5815 final ResolveInfo info = resolvedActivities.get(n); 5816 final String packageName = info.activityInfo.packageName; 5817 final PackageSetting ps = mSettings.mPackages.get(packageName); 5818 if (ps != null) { 5819 // only check domain verification status if the app is not a browser 5820 if (!info.handleAllWebDataURI) { 5821 // Try to get the status from User settings first 5822 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5823 final int status = (int) (packedStatus >> 32); 5824 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5825 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5826 if (DEBUG_EPHEMERAL) { 5827 Slog.v(TAG, "DENY instant app;" 5828 + " pkg: " + packageName + ", status: " + status); 5829 } 5830 return false; 5831 } 5832 } 5833 if (ps.getInstantApp(userId)) { 5834 if (DEBUG_EPHEMERAL) { 5835 Slog.v(TAG, "DENY instant app installed;" 5836 + " pkg: " + packageName); 5837 } 5838 return false; 5839 } 5840 } 5841 } 5842 } 5843 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5844 return true; 5845 } 5846 5847 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5848 Intent origIntent, String resolvedType, String callingPackage, 5849 Bundle verificationBundle, int userId) { 5850 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5851 new InstantAppRequest(responseObj, origIntent, resolvedType, 5852 callingPackage, userId, verificationBundle, false /*resolveForStart*/)); 5853 mHandler.sendMessage(msg); 5854 } 5855 5856 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5857 int flags, List<ResolveInfo> query, int userId) { 5858 if (query != null) { 5859 final int N = query.size(); 5860 if (N == 1) { 5861 return query.get(0); 5862 } else if (N > 1) { 5863 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5864 // If there is more than one activity with the same priority, 5865 // then let the user decide between them. 5866 ResolveInfo r0 = query.get(0); 5867 ResolveInfo r1 = query.get(1); 5868 if (DEBUG_INTENT_MATCHING || debug) { 5869 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5870 + r1.activityInfo.name + "=" + r1.priority); 5871 } 5872 // If the first activity has a higher priority, or a different 5873 // default, then it is always desirable to pick it. 5874 if (r0.priority != r1.priority 5875 || r0.preferredOrder != r1.preferredOrder 5876 || r0.isDefault != r1.isDefault) { 5877 return query.get(0); 5878 } 5879 // If we have saved a preference for a preferred activity for 5880 // this Intent, use that. 5881 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5882 flags, query, r0.priority, true, false, debug, userId); 5883 if (ri != null) { 5884 return ri; 5885 } 5886 // If we have an ephemeral app, use it 5887 for (int i = 0; i < N; i++) { 5888 ri = query.get(i); 5889 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5890 final String packageName = ri.activityInfo.packageName; 5891 final PackageSetting ps = mSettings.mPackages.get(packageName); 5892 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5893 final int status = (int)(packedStatus >> 32); 5894 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5895 return ri; 5896 } 5897 } 5898 } 5899 ri = new ResolveInfo(mResolveInfo); 5900 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5901 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5902 // If all of the options come from the same package, show the application's 5903 // label and icon instead of the generic resolver's. 5904 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5905 // and then throw away the ResolveInfo itself, meaning that the caller loses 5906 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5907 // a fallback for this case; we only set the target package's resources on 5908 // the ResolveInfo, not the ActivityInfo. 5909 final String intentPackage = intent.getPackage(); 5910 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5911 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5912 ri.resolvePackageName = intentPackage; 5913 if (userNeedsBadging(userId)) { 5914 ri.noResourceId = true; 5915 } else { 5916 ri.icon = appi.icon; 5917 } 5918 ri.iconResourceId = appi.icon; 5919 ri.labelRes = appi.labelRes; 5920 } 5921 ri.activityInfo.applicationInfo = new ApplicationInfo( 5922 ri.activityInfo.applicationInfo); 5923 if (userId != 0) { 5924 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5925 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5926 } 5927 // Make sure that the resolver is displayable in car mode 5928 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5929 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5930 return ri; 5931 } 5932 } 5933 return null; 5934 } 5935 5936 /** 5937 * Return true if the given list is not empty and all of its contents have 5938 * an activityInfo with the given package name. 5939 */ 5940 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5941 if (ArrayUtils.isEmpty(list)) { 5942 return false; 5943 } 5944 for (int i = 0, N = list.size(); i < N; i++) { 5945 final ResolveInfo ri = list.get(i); 5946 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5947 if (ai == null || !packageName.equals(ai.packageName)) { 5948 return false; 5949 } 5950 } 5951 return true; 5952 } 5953 5954 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5955 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5956 final int N = query.size(); 5957 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5958 .get(userId); 5959 // Get the list of persistent preferred activities that handle the intent 5960 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5961 List<PersistentPreferredActivity> pprefs = ppir != null 5962 ? ppir.queryIntent(intent, resolvedType, 5963 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5964 userId) 5965 : null; 5966 if (pprefs != null && pprefs.size() > 0) { 5967 final int M = pprefs.size(); 5968 for (int i=0; i<M; i++) { 5969 final PersistentPreferredActivity ppa = pprefs.get(i); 5970 if (DEBUG_PREFERRED || debug) { 5971 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5972 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5973 + "\n component=" + ppa.mComponent); 5974 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5975 } 5976 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5977 flags | MATCH_DISABLED_COMPONENTS, userId); 5978 if (DEBUG_PREFERRED || debug) { 5979 Slog.v(TAG, "Found persistent preferred activity:"); 5980 if (ai != null) { 5981 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5982 } else { 5983 Slog.v(TAG, " null"); 5984 } 5985 } 5986 if (ai == null) { 5987 // This previously registered persistent preferred activity 5988 // component is no longer known. Ignore it and do NOT remove it. 5989 continue; 5990 } 5991 for (int j=0; j<N; j++) { 5992 final ResolveInfo ri = query.get(j); 5993 if (!ri.activityInfo.applicationInfo.packageName 5994 .equals(ai.applicationInfo.packageName)) { 5995 continue; 5996 } 5997 if (!ri.activityInfo.name.equals(ai.name)) { 5998 continue; 5999 } 6000 // Found a persistent preference that can handle the intent. 6001 if (DEBUG_PREFERRED || debug) { 6002 Slog.v(TAG, "Returning persistent preferred activity: " + 6003 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6004 } 6005 return ri; 6006 } 6007 } 6008 } 6009 return null; 6010 } 6011 6012 // TODO: handle preferred activities missing while user has amnesia 6013 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6014 List<ResolveInfo> query, int priority, boolean always, 6015 boolean removeMatches, boolean debug, int userId) { 6016 if (!sUserManager.exists(userId)) return null; 6017 final int callingUid = Binder.getCallingUid(); 6018 flags = updateFlagsForResolve( 6019 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6020 intent = updateIntentForResolve(intent); 6021 // writer 6022 synchronized (mPackages) { 6023 // Try to find a matching persistent preferred activity. 6024 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6025 debug, userId); 6026 6027 // If a persistent preferred activity matched, use it. 6028 if (pri != null) { 6029 return pri; 6030 } 6031 6032 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6033 // Get the list of preferred activities that handle the intent 6034 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6035 List<PreferredActivity> prefs = pir != null 6036 ? pir.queryIntent(intent, resolvedType, 6037 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6038 userId) 6039 : null; 6040 if (prefs != null && prefs.size() > 0) { 6041 boolean changed = false; 6042 try { 6043 // First figure out how good the original match set is. 6044 // We will only allow preferred activities that came 6045 // from the same match quality. 6046 int match = 0; 6047 6048 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6049 6050 final int N = query.size(); 6051 for (int j=0; j<N; j++) { 6052 final ResolveInfo ri = query.get(j); 6053 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6054 + ": 0x" + Integer.toHexString(match)); 6055 if (ri.match > match) { 6056 match = ri.match; 6057 } 6058 } 6059 6060 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6061 + Integer.toHexString(match)); 6062 6063 match &= IntentFilter.MATCH_CATEGORY_MASK; 6064 final int M = prefs.size(); 6065 for (int i=0; i<M; i++) { 6066 final PreferredActivity pa = prefs.get(i); 6067 if (DEBUG_PREFERRED || debug) { 6068 Slog.v(TAG, "Checking PreferredActivity ds=" 6069 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6070 + "\n component=" + pa.mPref.mComponent); 6071 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6072 } 6073 if (pa.mPref.mMatch != match) { 6074 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6075 + Integer.toHexString(pa.mPref.mMatch)); 6076 continue; 6077 } 6078 // If it's not an "always" type preferred activity and that's what we're 6079 // looking for, skip it. 6080 if (always && !pa.mPref.mAlways) { 6081 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6082 continue; 6083 } 6084 final ActivityInfo ai = getActivityInfo( 6085 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6086 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6087 userId); 6088 if (DEBUG_PREFERRED || debug) { 6089 Slog.v(TAG, "Found preferred activity:"); 6090 if (ai != null) { 6091 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6092 } else { 6093 Slog.v(TAG, " null"); 6094 } 6095 } 6096 if (ai == null) { 6097 // This previously registered preferred activity 6098 // component is no longer known. Most likely an update 6099 // to the app was installed and in the new version this 6100 // component no longer exists. Clean it up by removing 6101 // it from the preferred activities list, and skip it. 6102 Slog.w(TAG, "Removing dangling preferred activity: " 6103 + pa.mPref.mComponent); 6104 pir.removeFilter(pa); 6105 changed = true; 6106 continue; 6107 } 6108 for (int j=0; j<N; j++) { 6109 final ResolveInfo ri = query.get(j); 6110 if (!ri.activityInfo.applicationInfo.packageName 6111 .equals(ai.applicationInfo.packageName)) { 6112 continue; 6113 } 6114 if (!ri.activityInfo.name.equals(ai.name)) { 6115 continue; 6116 } 6117 6118 if (removeMatches) { 6119 pir.removeFilter(pa); 6120 changed = true; 6121 if (DEBUG_PREFERRED) { 6122 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6123 } 6124 break; 6125 } 6126 6127 // Okay we found a previously set preferred or last chosen app. 6128 // If the result set is different from when this 6129 // was created, and is not a subset of the preferred set, we need to 6130 // clear it and re-ask the user their preference, if we're looking for 6131 // an "always" type entry. 6132 if (always && !pa.mPref.sameSet(query)) { 6133 if (pa.mPref.isSuperset(query)) { 6134 // some components of the set are no longer present in 6135 // the query, but the preferred activity can still be reused 6136 if (DEBUG_PREFERRED) { 6137 Slog.i(TAG, "Result set changed, but PreferredActivity is" 6138 + " still valid as only non-preferred components" 6139 + " were removed for " + intent + " type " 6140 + resolvedType); 6141 } 6142 // remove obsolete components and re-add the up-to-date filter 6143 PreferredActivity freshPa = new PreferredActivity(pa, 6144 pa.mPref.mMatch, 6145 pa.mPref.discardObsoleteComponents(query), 6146 pa.mPref.mComponent, 6147 pa.mPref.mAlways); 6148 pir.removeFilter(pa); 6149 pir.addFilter(freshPa); 6150 changed = true; 6151 } else { 6152 Slog.i(TAG, 6153 "Result set changed, dropping preferred activity for " 6154 + intent + " type " + resolvedType); 6155 if (DEBUG_PREFERRED) { 6156 Slog.v(TAG, "Removing preferred activity since set changed " 6157 + pa.mPref.mComponent); 6158 } 6159 pir.removeFilter(pa); 6160 // Re-add the filter as a "last chosen" entry (!always) 6161 PreferredActivity lastChosen = new PreferredActivity( 6162 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6163 pir.addFilter(lastChosen); 6164 changed = true; 6165 return null; 6166 } 6167 } 6168 6169 // Yay! Either the set matched or we're looking for the last chosen 6170 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6171 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6172 return ri; 6173 } 6174 } 6175 } finally { 6176 if (changed) { 6177 if (DEBUG_PREFERRED) { 6178 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6179 } 6180 scheduleWritePackageRestrictionsLocked(userId); 6181 } 6182 } 6183 } 6184 } 6185 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6186 return null; 6187 } 6188 6189 /* 6190 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6191 */ 6192 @Override 6193 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6194 int targetUserId) { 6195 mContext.enforceCallingOrSelfPermission( 6196 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6197 List<CrossProfileIntentFilter> matches = 6198 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6199 if (matches != null) { 6200 int size = matches.size(); 6201 for (int i = 0; i < size; i++) { 6202 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6203 } 6204 } 6205 if (hasWebURI(intent)) { 6206 // cross-profile app linking works only towards the parent. 6207 final int callingUid = Binder.getCallingUid(); 6208 final UserInfo parent = getProfileParent(sourceUserId); 6209 synchronized(mPackages) { 6210 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6211 false /*includeInstantApps*/); 6212 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6213 intent, resolvedType, flags, sourceUserId, parent.id); 6214 return xpDomainInfo != null; 6215 } 6216 } 6217 return false; 6218 } 6219 6220 private UserInfo getProfileParent(int userId) { 6221 final long identity = Binder.clearCallingIdentity(); 6222 try { 6223 return sUserManager.getProfileParent(userId); 6224 } finally { 6225 Binder.restoreCallingIdentity(identity); 6226 } 6227 } 6228 6229 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6230 String resolvedType, int userId) { 6231 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6232 if (resolver != null) { 6233 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6234 } 6235 return null; 6236 } 6237 6238 @Override 6239 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6240 String resolvedType, int flags, int userId) { 6241 try { 6242 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6243 6244 return new ParceledListSlice<>( 6245 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6246 } finally { 6247 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6248 } 6249 } 6250 6251 /** 6252 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6253 * instant, returns {@code null}. 6254 */ 6255 private String getInstantAppPackageName(int callingUid) { 6256 synchronized (mPackages) { 6257 // If the caller is an isolated app use the owner's uid for the lookup. 6258 if (Process.isIsolated(callingUid)) { 6259 callingUid = mIsolatedOwners.get(callingUid); 6260 } 6261 final int appId = UserHandle.getAppId(callingUid); 6262 final Object obj = mSettings.getUserIdLPr(appId); 6263 if (obj instanceof PackageSetting) { 6264 final PackageSetting ps = (PackageSetting) obj; 6265 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6266 return isInstantApp ? ps.pkg.packageName : null; 6267 } 6268 } 6269 return null; 6270 } 6271 6272 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6273 String resolvedType, int flags, int userId) { 6274 return queryIntentActivitiesInternal( 6275 intent, resolvedType, flags, Binder.getCallingUid(), userId, 6276 false /*resolveForStart*/, true /*allowDynamicSplits*/); 6277 } 6278 6279 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6280 String resolvedType, int flags, int filterCallingUid, int userId, 6281 boolean resolveForStart, boolean allowDynamicSplits) { 6282 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6283 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 6284 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 6285 false /* requireFullPermission */, false /* checkShell */, 6286 "query intent activities"); 6287 final String pkgName = intent.getPackage(); 6288 ComponentName comp = intent.getComponent(); 6289 if (comp == null) { 6290 if (intent.getSelector() != null) { 6291 intent = intent.getSelector(); 6292 comp = intent.getComponent(); 6293 } 6294 } 6295 6296 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 6297 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6298 if (comp != null) { 6299 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6300 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6301 if (ai != null) { 6302 // When specifying an explicit component, we prevent the activity from being 6303 // used when either 1) the calling package is normal and the activity is within 6304 // an ephemeral application or 2) the calling package is ephemeral and the 6305 // activity is not visible to ephemeral applications. 6306 final boolean matchInstantApp = 6307 (flags & PackageManager.MATCH_INSTANT) != 0; 6308 final boolean matchVisibleToInstantAppOnly = 6309 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6310 final boolean matchExplicitlyVisibleOnly = 6311 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6312 final boolean isCallerInstantApp = 6313 instantAppPkgName != null; 6314 final boolean isTargetSameInstantApp = 6315 comp.getPackageName().equals(instantAppPkgName); 6316 final boolean isTargetInstantApp = 6317 (ai.applicationInfo.privateFlags 6318 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6319 final boolean isTargetVisibleToInstantApp = 6320 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6321 final boolean isTargetExplicitlyVisibleToInstantApp = 6322 isTargetVisibleToInstantApp 6323 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6324 final boolean isTargetHiddenFromInstantApp = 6325 !isTargetVisibleToInstantApp 6326 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6327 final boolean blockResolution = 6328 !isTargetSameInstantApp 6329 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6330 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6331 && isTargetHiddenFromInstantApp)); 6332 if (!blockResolution) { 6333 final ResolveInfo ri = new ResolveInfo(); 6334 ri.activityInfo = ai; 6335 list.add(ri); 6336 } 6337 } 6338 return applyPostResolutionFilter( 6339 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6340 } 6341 6342 // reader 6343 boolean sortResult = false; 6344 boolean addEphemeral = false; 6345 List<ResolveInfo> result; 6346 final boolean ephemeralDisabled = isEphemeralDisabled(); 6347 synchronized (mPackages) { 6348 if (pkgName == null) { 6349 List<CrossProfileIntentFilter> matchingFilters = 6350 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6351 // Check for results that need to skip the current profile. 6352 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6353 resolvedType, flags, userId); 6354 if (xpResolveInfo != null) { 6355 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6356 xpResult.add(xpResolveInfo); 6357 return applyPostResolutionFilter( 6358 filterIfNotSystemUser(xpResult, userId), instantAppPkgName, 6359 allowDynamicSplits, filterCallingUid, userId); 6360 } 6361 6362 // Check for results in the current profile. 6363 result = filterIfNotSystemUser(mActivities.queryIntent( 6364 intent, resolvedType, flags, userId), userId); 6365 addEphemeral = !ephemeralDisabled 6366 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/); 6367 // Check for cross profile results. 6368 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6369 xpResolveInfo = queryCrossProfileIntents( 6370 matchingFilters, intent, resolvedType, flags, userId, 6371 hasNonNegativePriorityResult); 6372 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6373 boolean isVisibleToUser = filterIfNotSystemUser( 6374 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6375 if (isVisibleToUser) { 6376 result.add(xpResolveInfo); 6377 sortResult = true; 6378 } 6379 } 6380 if (hasWebURI(intent)) { 6381 CrossProfileDomainInfo xpDomainInfo = null; 6382 final UserInfo parent = getProfileParent(userId); 6383 if (parent != null) { 6384 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6385 flags, userId, parent.id); 6386 } 6387 if (xpDomainInfo != null) { 6388 if (xpResolveInfo != null) { 6389 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6390 // in the result. 6391 result.remove(xpResolveInfo); 6392 } 6393 if (result.size() == 0 && !addEphemeral) { 6394 // No result in current profile, but found candidate in parent user. 6395 // And we are not going to add emphemeral app, so we can return the 6396 // result straight away. 6397 result.add(xpDomainInfo.resolveInfo); 6398 return applyPostResolutionFilter(result, instantAppPkgName, 6399 allowDynamicSplits, filterCallingUid, userId); 6400 } 6401 } else if (result.size() <= 1 && !addEphemeral) { 6402 // No result in parent user and <= 1 result in current profile, and we 6403 // are not going to add emphemeral app, so we can return the result without 6404 // further processing. 6405 return applyPostResolutionFilter(result, instantAppPkgName, 6406 allowDynamicSplits, filterCallingUid, userId); 6407 } 6408 // We have more than one candidate (combining results from current and parent 6409 // profile), so we need filtering and sorting. 6410 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6411 intent, flags, result, xpDomainInfo, userId); 6412 sortResult = true; 6413 } 6414 } else { 6415 final PackageParser.Package pkg = mPackages.get(pkgName); 6416 result = null; 6417 if (pkg != null) { 6418 result = filterIfNotSystemUser( 6419 mActivities.queryIntentForPackage( 6420 intent, resolvedType, flags, pkg.activities, userId), 6421 userId); 6422 } 6423 if (result == null || result.size() == 0) { 6424 // the caller wants to resolve for a particular package; however, there 6425 // were no installed results, so, try to find an ephemeral result 6426 addEphemeral = !ephemeralDisabled 6427 && isInstantAppAllowed( 6428 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6429 if (result == null) { 6430 result = new ArrayList<>(); 6431 } 6432 } 6433 } 6434 } 6435 if (addEphemeral) { 6436 result = maybeAddInstantAppInstaller( 6437 result, intent, resolvedType, flags, userId, resolveForStart); 6438 } 6439 if (sortResult) { 6440 Collections.sort(result, mResolvePrioritySorter); 6441 } 6442 return applyPostResolutionFilter( 6443 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6444 } 6445 6446 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 6447 String resolvedType, int flags, int userId, boolean resolveForStart) { 6448 // first, check to see if we've got an instant app already installed 6449 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 6450 ResolveInfo localInstantApp = null; 6451 boolean blockResolution = false; 6452 if (!alreadyResolvedLocally) { 6453 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 6454 flags 6455 | PackageManager.GET_RESOLVED_FILTER 6456 | PackageManager.MATCH_INSTANT 6457 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 6458 userId); 6459 for (int i = instantApps.size() - 1; i >= 0; --i) { 6460 final ResolveInfo info = instantApps.get(i); 6461 final String packageName = info.activityInfo.packageName; 6462 final PackageSetting ps = mSettings.mPackages.get(packageName); 6463 if (ps.getInstantApp(userId)) { 6464 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6465 final int status = (int)(packedStatus >> 32); 6466 final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6467 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6468 // there's a local instant application installed, but, the user has 6469 // chosen to never use it; skip resolution and don't acknowledge 6470 // an instant application is even available 6471 if (DEBUG_EPHEMERAL) { 6472 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 6473 } 6474 blockResolution = true; 6475 break; 6476 } else { 6477 // we have a locally installed instant application; skip resolution 6478 // but acknowledge there's an instant application available 6479 if (DEBUG_EPHEMERAL) { 6480 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 6481 } 6482 localInstantApp = info; 6483 break; 6484 } 6485 } 6486 } 6487 } 6488 // no app installed, let's see if one's available 6489 AuxiliaryResolveInfo auxiliaryResponse = null; 6490 if (!blockResolution) { 6491 if (localInstantApp == null) { 6492 // we don't have an instant app locally, resolve externally 6493 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6494 final InstantAppRequest requestObject = new InstantAppRequest( 6495 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6496 null /*callingPackage*/, userId, null /*verificationBundle*/, 6497 resolveForStart); 6498 auxiliaryResponse = 6499 InstantAppResolver.doInstantAppResolutionPhaseOne( 6500 mContext, mInstantAppResolverConnection, requestObject); 6501 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6502 } else { 6503 // we have an instant application locally, but, we can't admit that since 6504 // callers shouldn't be able to determine prior browsing. create a dummy 6505 // auxiliary response so the downstream code behaves as if there's an 6506 // instant application available externally. when it comes time to start 6507 // the instant application, we'll do the right thing. 6508 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 6509 auxiliaryResponse = new AuxiliaryResolveInfo( 6510 ai.packageName, null /*splitName*/, null /*failureActivity*/, 6511 ai.versionCode, null /*failureIntent*/); 6512 } 6513 } 6514 if (auxiliaryResponse != null) { 6515 if (DEBUG_EPHEMERAL) { 6516 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6517 } 6518 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6519 final PackageSetting ps = 6520 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6521 if (ps != null) { 6522 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6523 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6524 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6525 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6526 // make sure this resolver is the default 6527 ephemeralInstaller.isDefault = true; 6528 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6529 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6530 // add a non-generic filter 6531 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6532 ephemeralInstaller.filter.addDataPath( 6533 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6534 ephemeralInstaller.isInstantAppAvailable = true; 6535 result.add(ephemeralInstaller); 6536 } 6537 } 6538 return result; 6539 } 6540 6541 private static class CrossProfileDomainInfo { 6542 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6543 ResolveInfo resolveInfo; 6544 /* Best domain verification status of the activities found in the other profile */ 6545 int bestDomainVerificationStatus; 6546 } 6547 6548 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6549 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6550 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6551 sourceUserId)) { 6552 return null; 6553 } 6554 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6555 resolvedType, flags, parentUserId); 6556 6557 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6558 return null; 6559 } 6560 CrossProfileDomainInfo result = null; 6561 int size = resultTargetUser.size(); 6562 for (int i = 0; i < size; i++) { 6563 ResolveInfo riTargetUser = resultTargetUser.get(i); 6564 // Intent filter verification is only for filters that specify a host. So don't return 6565 // those that handle all web uris. 6566 if (riTargetUser.handleAllWebDataURI) { 6567 continue; 6568 } 6569 String packageName = riTargetUser.activityInfo.packageName; 6570 PackageSetting ps = mSettings.mPackages.get(packageName); 6571 if (ps == null) { 6572 continue; 6573 } 6574 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6575 int status = (int)(verificationState >> 32); 6576 if (result == null) { 6577 result = new CrossProfileDomainInfo(); 6578 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6579 sourceUserId, parentUserId); 6580 result.bestDomainVerificationStatus = status; 6581 } else { 6582 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6583 result.bestDomainVerificationStatus); 6584 } 6585 } 6586 // Don't consider matches with status NEVER across profiles. 6587 if (result != null && result.bestDomainVerificationStatus 6588 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6589 return null; 6590 } 6591 return result; 6592 } 6593 6594 /** 6595 * Verification statuses are ordered from the worse to the best, except for 6596 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6597 */ 6598 private int bestDomainVerificationStatus(int status1, int status2) { 6599 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6600 return status2; 6601 } 6602 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6603 return status1; 6604 } 6605 return (int) MathUtils.max(status1, status2); 6606 } 6607 6608 private boolean isUserEnabled(int userId) { 6609 long callingId = Binder.clearCallingIdentity(); 6610 try { 6611 UserInfo userInfo = sUserManager.getUserInfo(userId); 6612 return userInfo != null && userInfo.isEnabled(); 6613 } finally { 6614 Binder.restoreCallingIdentity(callingId); 6615 } 6616 } 6617 6618 /** 6619 * Filter out activities with systemUserOnly flag set, when current user is not System. 6620 * 6621 * @return filtered list 6622 */ 6623 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6624 if (userId == UserHandle.USER_SYSTEM) { 6625 return resolveInfos; 6626 } 6627 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6628 ResolveInfo info = resolveInfos.get(i); 6629 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6630 resolveInfos.remove(i); 6631 } 6632 } 6633 return resolveInfos; 6634 } 6635 6636 /** 6637 * Filters out ephemeral activities. 6638 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6639 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6640 * 6641 * @param resolveInfos The pre-filtered list of resolved activities 6642 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6643 * is performed. 6644 * @return A filtered list of resolved activities. 6645 */ 6646 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6647 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) { 6648 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6649 final ResolveInfo info = resolveInfos.get(i); 6650 // allow activities that are defined in the provided package 6651 if (allowDynamicSplits 6652 && info.activityInfo.splitName != null 6653 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6654 info.activityInfo.splitName)) { 6655 if (mInstantAppInstallerInfo == null) { 6656 if (DEBUG_INSTALL) { 6657 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 6658 } 6659 resolveInfos.remove(i); 6660 continue; 6661 } 6662 // requested activity is defined in a split that hasn't been installed yet. 6663 // add the installer to the resolve list 6664 if (DEBUG_INSTALL) { 6665 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 6666 } 6667 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6668 final ComponentName installFailureActivity = findInstallFailureActivity( 6669 info.activityInfo.packageName, filterCallingUid, userId); 6670 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6671 info.activityInfo.packageName, info.activityInfo.splitName, 6672 installFailureActivity, 6673 info.activityInfo.applicationInfo.versionCode, 6674 null /*failureIntent*/); 6675 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6676 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6677 // add a non-generic filter 6678 installerInfo.filter = new IntentFilter(); 6679 6680 // This resolve info may appear in the chooser UI, so let us make it 6681 // look as the one it replaces as far as the user is concerned which 6682 // requires loading the correct label and icon for the resolve info. 6683 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6684 installerInfo.labelRes = info.resolveLabelResId(); 6685 installerInfo.icon = info.resolveIconResId(); 6686 6687 // propagate priority/preferred order/default 6688 installerInfo.priority = info.priority; 6689 installerInfo.preferredOrder = info.preferredOrder; 6690 installerInfo.isDefault = info.isDefault; 6691 resolveInfos.set(i, installerInfo); 6692 continue; 6693 } 6694 // caller is a full app, don't need to apply any other filtering 6695 if (ephemeralPkgName == null) { 6696 continue; 6697 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 6698 // caller is same app; don't need to apply any other filtering 6699 continue; 6700 } 6701 // allow activities that have been explicitly exposed to ephemeral apps 6702 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6703 if (!isEphemeralApp 6704 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 6705 continue; 6706 } 6707 resolveInfos.remove(i); 6708 } 6709 return resolveInfos; 6710 } 6711 6712 /** 6713 * Returns the activity component that can handle install failures. 6714 * <p>By default, the instant application installer handles failures. However, an 6715 * application may want to handle failures on its own. Applications do this by 6716 * creating an activity with an intent filter that handles the action 6717 * {@link Intent#ACTION_INSTALL_FAILURE}. 6718 */ 6719 private @Nullable ComponentName findInstallFailureActivity( 6720 String packageName, int filterCallingUid, int userId) { 6721 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 6722 failureActivityIntent.setPackage(packageName); 6723 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 6724 final List<ResolveInfo> result = queryIntentActivitiesInternal( 6725 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId, 6726 false /*resolveForStart*/, false /*allowDynamicSplits*/); 6727 final int NR = result.size(); 6728 if (NR > 0) { 6729 for (int i = 0; i < NR; i++) { 6730 final ResolveInfo info = result.get(i); 6731 if (info.activityInfo.splitName != null) { 6732 continue; 6733 } 6734 return new ComponentName(packageName, info.activityInfo.name); 6735 } 6736 } 6737 return null; 6738 } 6739 6740 /** 6741 * @param resolveInfos list of resolve infos in descending priority order 6742 * @return if the list contains a resolve info with non-negative priority 6743 */ 6744 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6745 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6746 } 6747 6748 private static boolean hasWebURI(Intent intent) { 6749 if (intent.getData() == null) { 6750 return false; 6751 } 6752 final String scheme = intent.getScheme(); 6753 if (TextUtils.isEmpty(scheme)) { 6754 return false; 6755 } 6756 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6757 } 6758 6759 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6760 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6761 int userId) { 6762 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6763 6764 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6765 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6766 candidates.size()); 6767 } 6768 6769 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6770 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6771 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6772 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6773 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6774 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6775 6776 synchronized (mPackages) { 6777 final int count = candidates.size(); 6778 // First, try to use linked apps. Partition the candidates into four lists: 6779 // one for the final results, one for the "do not use ever", one for "undefined status" 6780 // and finally one for "browser app type". 6781 for (int n=0; n<count; n++) { 6782 ResolveInfo info = candidates.get(n); 6783 String packageName = info.activityInfo.packageName; 6784 PackageSetting ps = mSettings.mPackages.get(packageName); 6785 if (ps != null) { 6786 // Add to the special match all list (Browser use case) 6787 if (info.handleAllWebDataURI) { 6788 matchAllList.add(info); 6789 continue; 6790 } 6791 // Try to get the status from User settings first 6792 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6793 int status = (int)(packedStatus >> 32); 6794 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6795 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6796 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6797 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6798 + " : linkgen=" + linkGeneration); 6799 } 6800 // Use link-enabled generation as preferredOrder, i.e. 6801 // prefer newly-enabled over earlier-enabled. 6802 info.preferredOrder = linkGeneration; 6803 alwaysList.add(info); 6804 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6805 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6806 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6807 } 6808 neverList.add(info); 6809 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6810 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6811 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6812 } 6813 alwaysAskList.add(info); 6814 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6815 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6816 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6817 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6818 } 6819 undefinedList.add(info); 6820 } 6821 } 6822 } 6823 6824 // We'll want to include browser possibilities in a few cases 6825 boolean includeBrowser = false; 6826 6827 // First try to add the "always" resolution(s) for the current user, if any 6828 if (alwaysList.size() > 0) { 6829 result.addAll(alwaysList); 6830 } else { 6831 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6832 result.addAll(undefinedList); 6833 // Maybe add one for the other profile. 6834 if (xpDomainInfo != null && ( 6835 xpDomainInfo.bestDomainVerificationStatus 6836 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6837 result.add(xpDomainInfo.resolveInfo); 6838 } 6839 includeBrowser = true; 6840 } 6841 6842 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6843 // If there were 'always' entries their preferred order has been set, so we also 6844 // back that off to make the alternatives equivalent 6845 if (alwaysAskList.size() > 0) { 6846 for (ResolveInfo i : result) { 6847 i.preferredOrder = 0; 6848 } 6849 result.addAll(alwaysAskList); 6850 includeBrowser = true; 6851 } 6852 6853 if (includeBrowser) { 6854 // Also add browsers (all of them or only the default one) 6855 if (DEBUG_DOMAIN_VERIFICATION) { 6856 Slog.v(TAG, " ...including browsers in candidate set"); 6857 } 6858 if ((matchFlags & MATCH_ALL) != 0) { 6859 result.addAll(matchAllList); 6860 } else { 6861 // Browser/generic handling case. If there's a default browser, go straight 6862 // to that (but only if there is no other higher-priority match). 6863 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6864 int maxMatchPrio = 0; 6865 ResolveInfo defaultBrowserMatch = null; 6866 final int numCandidates = matchAllList.size(); 6867 for (int n = 0; n < numCandidates; n++) { 6868 ResolveInfo info = matchAllList.get(n); 6869 // track the highest overall match priority... 6870 if (info.priority > maxMatchPrio) { 6871 maxMatchPrio = info.priority; 6872 } 6873 // ...and the highest-priority default browser match 6874 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6875 if (defaultBrowserMatch == null 6876 || (defaultBrowserMatch.priority < info.priority)) { 6877 if (debug) { 6878 Slog.v(TAG, "Considering default browser match " + info); 6879 } 6880 defaultBrowserMatch = info; 6881 } 6882 } 6883 } 6884 if (defaultBrowserMatch != null 6885 && defaultBrowserMatch.priority >= maxMatchPrio 6886 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6887 { 6888 if (debug) { 6889 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6890 } 6891 result.add(defaultBrowserMatch); 6892 } else { 6893 result.addAll(matchAllList); 6894 } 6895 } 6896 6897 // If there is nothing selected, add all candidates and remove the ones that the user 6898 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6899 if (result.size() == 0) { 6900 result.addAll(candidates); 6901 result.removeAll(neverList); 6902 } 6903 } 6904 } 6905 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6906 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6907 result.size()); 6908 for (ResolveInfo info : result) { 6909 Slog.v(TAG, " + " + info.activityInfo); 6910 } 6911 } 6912 return result; 6913 } 6914 6915 // Returns a packed value as a long: 6916 // 6917 // high 'int'-sized word: link status: undefined/ask/never/always. 6918 // low 'int'-sized word: relative priority among 'always' results. 6919 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6920 long result = ps.getDomainVerificationStatusForUser(userId); 6921 // if none available, get the master status 6922 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6923 if (ps.getIntentFilterVerificationInfo() != null) { 6924 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6925 } 6926 } 6927 return result; 6928 } 6929 6930 private ResolveInfo querySkipCurrentProfileIntents( 6931 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6932 int flags, int sourceUserId) { 6933 if (matchingFilters != null) { 6934 int size = matchingFilters.size(); 6935 for (int i = 0; i < size; i ++) { 6936 CrossProfileIntentFilter filter = matchingFilters.get(i); 6937 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6938 // Checking if there are activities in the target user that can handle the 6939 // intent. 6940 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6941 resolvedType, flags, sourceUserId); 6942 if (resolveInfo != null) { 6943 return resolveInfo; 6944 } 6945 } 6946 } 6947 } 6948 return null; 6949 } 6950 6951 // Return matching ResolveInfo in target user if any. 6952 private ResolveInfo queryCrossProfileIntents( 6953 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6954 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6955 if (matchingFilters != null) { 6956 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6957 // match the same intent. For performance reasons, it is better not to 6958 // run queryIntent twice for the same userId 6959 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6960 int size = matchingFilters.size(); 6961 for (int i = 0; i < size; i++) { 6962 CrossProfileIntentFilter filter = matchingFilters.get(i); 6963 int targetUserId = filter.getTargetUserId(); 6964 boolean skipCurrentProfile = 6965 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6966 boolean skipCurrentProfileIfNoMatchFound = 6967 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6968 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6969 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6970 // Checking if there are activities in the target user that can handle the 6971 // intent. 6972 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6973 resolvedType, flags, sourceUserId); 6974 if (resolveInfo != null) return resolveInfo; 6975 alreadyTriedUserIds.put(targetUserId, true); 6976 } 6977 } 6978 } 6979 return null; 6980 } 6981 6982 /** 6983 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6984 * will forward the intent to the filter's target user. 6985 * Otherwise, returns null. 6986 */ 6987 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6988 String resolvedType, int flags, int sourceUserId) { 6989 int targetUserId = filter.getTargetUserId(); 6990 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6991 resolvedType, flags, targetUserId); 6992 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6993 // If all the matches in the target profile are suspended, return null. 6994 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6995 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6996 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6997 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6998 targetUserId); 6999 } 7000 } 7001 } 7002 return null; 7003 } 7004 7005 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7006 int sourceUserId, int targetUserId) { 7007 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7008 long ident = Binder.clearCallingIdentity(); 7009 boolean targetIsProfile; 7010 try { 7011 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7012 } finally { 7013 Binder.restoreCallingIdentity(ident); 7014 } 7015 String className; 7016 if (targetIsProfile) { 7017 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7018 } else { 7019 className = FORWARD_INTENT_TO_PARENT; 7020 } 7021 ComponentName forwardingActivityComponentName = new ComponentName( 7022 mAndroidApplication.packageName, className); 7023 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7024 sourceUserId); 7025 if (!targetIsProfile) { 7026 forwardingActivityInfo.showUserIcon = targetUserId; 7027 forwardingResolveInfo.noResourceId = true; 7028 } 7029 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7030 forwardingResolveInfo.priority = 0; 7031 forwardingResolveInfo.preferredOrder = 0; 7032 forwardingResolveInfo.match = 0; 7033 forwardingResolveInfo.isDefault = true; 7034 forwardingResolveInfo.filter = filter; 7035 forwardingResolveInfo.targetUserId = targetUserId; 7036 return forwardingResolveInfo; 7037 } 7038 7039 @Override 7040 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7041 Intent[] specifics, String[] specificTypes, Intent intent, 7042 String resolvedType, int flags, int userId) { 7043 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7044 specificTypes, intent, resolvedType, flags, userId)); 7045 } 7046 7047 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7048 Intent[] specifics, String[] specificTypes, Intent intent, 7049 String resolvedType, int flags, int userId) { 7050 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7051 final int callingUid = Binder.getCallingUid(); 7052 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7053 false /*includeInstantApps*/); 7054 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7055 false /*requireFullPermission*/, false /*checkShell*/, 7056 "query intent activity options"); 7057 final String resultsAction = intent.getAction(); 7058 7059 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7060 | PackageManager.GET_RESOLVED_FILTER, userId); 7061 7062 if (DEBUG_INTENT_MATCHING) { 7063 Log.v(TAG, "Query " + intent + ": " + results); 7064 } 7065 7066 int specificsPos = 0; 7067 int N; 7068 7069 // todo: note that the algorithm used here is O(N^2). This 7070 // isn't a problem in our current environment, but if we start running 7071 // into situations where we have more than 5 or 10 matches then this 7072 // should probably be changed to something smarter... 7073 7074 // First we go through and resolve each of the specific items 7075 // that were supplied, taking care of removing any corresponding 7076 // duplicate items in the generic resolve list. 7077 if (specifics != null) { 7078 for (int i=0; i<specifics.length; i++) { 7079 final Intent sintent = specifics[i]; 7080 if (sintent == null) { 7081 continue; 7082 } 7083 7084 if (DEBUG_INTENT_MATCHING) { 7085 Log.v(TAG, "Specific #" + i + ": " + sintent); 7086 } 7087 7088 String action = sintent.getAction(); 7089 if (resultsAction != null && resultsAction.equals(action)) { 7090 // If this action was explicitly requested, then don't 7091 // remove things that have it. 7092 action = null; 7093 } 7094 7095 ResolveInfo ri = null; 7096 ActivityInfo ai = null; 7097 7098 ComponentName comp = sintent.getComponent(); 7099 if (comp == null) { 7100 ri = resolveIntent( 7101 sintent, 7102 specificTypes != null ? specificTypes[i] : null, 7103 flags, userId); 7104 if (ri == null) { 7105 continue; 7106 } 7107 if (ri == mResolveInfo) { 7108 // ACK! Must do something better with this. 7109 } 7110 ai = ri.activityInfo; 7111 comp = new ComponentName(ai.applicationInfo.packageName, 7112 ai.name); 7113 } else { 7114 ai = getActivityInfo(comp, flags, userId); 7115 if (ai == null) { 7116 continue; 7117 } 7118 } 7119 7120 // Look for any generic query activities that are duplicates 7121 // of this specific one, and remove them from the results. 7122 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7123 N = results.size(); 7124 int j; 7125 for (j=specificsPos; j<N; j++) { 7126 ResolveInfo sri = results.get(j); 7127 if ((sri.activityInfo.name.equals(comp.getClassName()) 7128 && sri.activityInfo.applicationInfo.packageName.equals( 7129 comp.getPackageName())) 7130 || (action != null && sri.filter.matchAction(action))) { 7131 results.remove(j); 7132 if (DEBUG_INTENT_MATCHING) Log.v( 7133 TAG, "Removing duplicate item from " + j 7134 + " due to specific " + specificsPos); 7135 if (ri == null) { 7136 ri = sri; 7137 } 7138 j--; 7139 N--; 7140 } 7141 } 7142 7143 // Add this specific item to its proper place. 7144 if (ri == null) { 7145 ri = new ResolveInfo(); 7146 ri.activityInfo = ai; 7147 } 7148 results.add(specificsPos, ri); 7149 ri.specificIndex = i; 7150 specificsPos++; 7151 } 7152 } 7153 7154 // Now we go through the remaining generic results and remove any 7155 // duplicate actions that are found here. 7156 N = results.size(); 7157 for (int i=specificsPos; i<N-1; i++) { 7158 final ResolveInfo rii = results.get(i); 7159 if (rii.filter == null) { 7160 continue; 7161 } 7162 7163 // Iterate over all of the actions of this result's intent 7164 // filter... typically this should be just one. 7165 final Iterator<String> it = rii.filter.actionsIterator(); 7166 if (it == null) { 7167 continue; 7168 } 7169 while (it.hasNext()) { 7170 final String action = it.next(); 7171 if (resultsAction != null && resultsAction.equals(action)) { 7172 // If this action was explicitly requested, then don't 7173 // remove things that have it. 7174 continue; 7175 } 7176 for (int j=i+1; j<N; j++) { 7177 final ResolveInfo rij = results.get(j); 7178 if (rij.filter != null && rij.filter.hasAction(action)) { 7179 results.remove(j); 7180 if (DEBUG_INTENT_MATCHING) Log.v( 7181 TAG, "Removing duplicate item from " + j 7182 + " due to action " + action + " at " + i); 7183 j--; 7184 N--; 7185 } 7186 } 7187 } 7188 7189 // If the caller didn't request filter information, drop it now 7190 // so we don't have to marshall/unmarshall it. 7191 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7192 rii.filter = null; 7193 } 7194 } 7195 7196 // Filter out the caller activity if so requested. 7197 if (caller != null) { 7198 N = results.size(); 7199 for (int i=0; i<N; i++) { 7200 ActivityInfo ainfo = results.get(i).activityInfo; 7201 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7202 && caller.getClassName().equals(ainfo.name)) { 7203 results.remove(i); 7204 break; 7205 } 7206 } 7207 } 7208 7209 // If the caller didn't request filter information, 7210 // drop them now so we don't have to 7211 // marshall/unmarshall it. 7212 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7213 N = results.size(); 7214 for (int i=0; i<N; i++) { 7215 results.get(i).filter = null; 7216 } 7217 } 7218 7219 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7220 return results; 7221 } 7222 7223 @Override 7224 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7225 String resolvedType, int flags, int userId) { 7226 return new ParceledListSlice<>( 7227 queryIntentReceiversInternal(intent, resolvedType, flags, userId, 7228 false /*allowDynamicSplits*/)); 7229 } 7230 7231 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7232 String resolvedType, int flags, int userId, boolean allowDynamicSplits) { 7233 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7234 final int callingUid = Binder.getCallingUid(); 7235 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7236 false /*requireFullPermission*/, false /*checkShell*/, 7237 "query intent receivers"); 7238 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7239 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7240 false /*includeInstantApps*/); 7241 ComponentName comp = intent.getComponent(); 7242 if (comp == null) { 7243 if (intent.getSelector() != null) { 7244 intent = intent.getSelector(); 7245 comp = intent.getComponent(); 7246 } 7247 } 7248 if (comp != null) { 7249 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7250 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7251 if (ai != null) { 7252 // When specifying an explicit component, we prevent the activity from being 7253 // used when either 1) the calling package is normal and the activity is within 7254 // an instant application or 2) the calling package is ephemeral and the 7255 // activity is not visible to instant applications. 7256 final boolean matchInstantApp = 7257 (flags & PackageManager.MATCH_INSTANT) != 0; 7258 final boolean matchVisibleToInstantAppOnly = 7259 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7260 final boolean matchExplicitlyVisibleOnly = 7261 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7262 final boolean isCallerInstantApp = 7263 instantAppPkgName != null; 7264 final boolean isTargetSameInstantApp = 7265 comp.getPackageName().equals(instantAppPkgName); 7266 final boolean isTargetInstantApp = 7267 (ai.applicationInfo.privateFlags 7268 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7269 final boolean isTargetVisibleToInstantApp = 7270 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7271 final boolean isTargetExplicitlyVisibleToInstantApp = 7272 isTargetVisibleToInstantApp 7273 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7274 final boolean isTargetHiddenFromInstantApp = 7275 !isTargetVisibleToInstantApp 7276 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7277 final boolean blockResolution = 7278 !isTargetSameInstantApp 7279 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7280 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7281 && isTargetHiddenFromInstantApp)); 7282 if (!blockResolution) { 7283 ResolveInfo ri = new ResolveInfo(); 7284 ri.activityInfo = ai; 7285 list.add(ri); 7286 } 7287 } 7288 return applyPostResolutionFilter( 7289 list, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7290 } 7291 7292 // reader 7293 synchronized (mPackages) { 7294 String pkgName = intent.getPackage(); 7295 if (pkgName == null) { 7296 final List<ResolveInfo> result = 7297 mReceivers.queryIntent(intent, resolvedType, flags, userId); 7298 return applyPostResolutionFilter( 7299 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7300 } 7301 final PackageParser.Package pkg = mPackages.get(pkgName); 7302 if (pkg != null) { 7303 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 7304 intent, resolvedType, flags, pkg.receivers, userId); 7305 return applyPostResolutionFilter( 7306 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7307 } 7308 return Collections.emptyList(); 7309 } 7310 } 7311 7312 @Override 7313 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7314 final int callingUid = Binder.getCallingUid(); 7315 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7316 } 7317 7318 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7319 int userId, int callingUid) { 7320 if (!sUserManager.exists(userId)) return null; 7321 flags = updateFlagsForResolve( 7322 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7323 List<ResolveInfo> query = queryIntentServicesInternal( 7324 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7325 if (query != null) { 7326 if (query.size() >= 1) { 7327 // If there is more than one service with the same priority, 7328 // just arbitrarily pick the first one. 7329 return query.get(0); 7330 } 7331 } 7332 return null; 7333 } 7334 7335 @Override 7336 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7337 String resolvedType, int flags, int userId) { 7338 final int callingUid = Binder.getCallingUid(); 7339 return new ParceledListSlice<>(queryIntentServicesInternal( 7340 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7341 } 7342 7343 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7344 String resolvedType, int flags, int userId, int callingUid, 7345 boolean includeInstantApps) { 7346 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7347 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7348 false /*requireFullPermission*/, false /*checkShell*/, 7349 "query intent receivers"); 7350 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7351 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7352 ComponentName comp = intent.getComponent(); 7353 if (comp == null) { 7354 if (intent.getSelector() != null) { 7355 intent = intent.getSelector(); 7356 comp = intent.getComponent(); 7357 } 7358 } 7359 if (comp != null) { 7360 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7361 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7362 if (si != null) { 7363 // When specifying an explicit component, we prevent the service from being 7364 // used when either 1) the service is in an instant application and the 7365 // caller is not the same instant application or 2) the calling package is 7366 // ephemeral and the activity is not visible to ephemeral applications. 7367 final boolean matchInstantApp = 7368 (flags & PackageManager.MATCH_INSTANT) != 0; 7369 final boolean matchVisibleToInstantAppOnly = 7370 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7371 final boolean isCallerInstantApp = 7372 instantAppPkgName != null; 7373 final boolean isTargetSameInstantApp = 7374 comp.getPackageName().equals(instantAppPkgName); 7375 final boolean isTargetInstantApp = 7376 (si.applicationInfo.privateFlags 7377 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7378 final boolean isTargetHiddenFromInstantApp = 7379 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7380 final boolean blockResolution = 7381 !isTargetSameInstantApp 7382 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7383 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7384 && isTargetHiddenFromInstantApp)); 7385 if (!blockResolution) { 7386 final ResolveInfo ri = new ResolveInfo(); 7387 ri.serviceInfo = si; 7388 list.add(ri); 7389 } 7390 } 7391 return list; 7392 } 7393 7394 // reader 7395 synchronized (mPackages) { 7396 String pkgName = intent.getPackage(); 7397 if (pkgName == null) { 7398 return applyPostServiceResolutionFilter( 7399 mServices.queryIntent(intent, resolvedType, flags, userId), 7400 instantAppPkgName); 7401 } 7402 final PackageParser.Package pkg = mPackages.get(pkgName); 7403 if (pkg != null) { 7404 return applyPostServiceResolutionFilter( 7405 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7406 userId), 7407 instantAppPkgName); 7408 } 7409 return Collections.emptyList(); 7410 } 7411 } 7412 7413 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7414 String instantAppPkgName) { 7415 if (instantAppPkgName == null) { 7416 return resolveInfos; 7417 } 7418 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7419 final ResolveInfo info = resolveInfos.get(i); 7420 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7421 // allow services that are defined in the provided package 7422 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7423 if (info.serviceInfo.splitName != null 7424 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7425 info.serviceInfo.splitName)) { 7426 // requested service is defined in a split that hasn't been installed yet. 7427 // add the installer to the resolve list 7428 if (DEBUG_EPHEMERAL) { 7429 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7430 } 7431 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7432 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7433 info.serviceInfo.packageName, info.serviceInfo.splitName, 7434 null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode, 7435 null /*failureIntent*/); 7436 // make sure this resolver is the default 7437 installerInfo.isDefault = true; 7438 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7439 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7440 // add a non-generic filter 7441 installerInfo.filter = new IntentFilter(); 7442 // load resources from the correct package 7443 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7444 resolveInfos.set(i, installerInfo); 7445 } 7446 continue; 7447 } 7448 // allow services that have been explicitly exposed to ephemeral apps 7449 if (!isEphemeralApp 7450 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7451 continue; 7452 } 7453 resolveInfos.remove(i); 7454 } 7455 return resolveInfos; 7456 } 7457 7458 @Override 7459 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7460 String resolvedType, int flags, int userId) { 7461 return new ParceledListSlice<>( 7462 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7463 } 7464 7465 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7466 Intent intent, String resolvedType, int flags, int userId) { 7467 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7468 final int callingUid = Binder.getCallingUid(); 7469 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7470 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7471 false /*includeInstantApps*/); 7472 ComponentName comp = intent.getComponent(); 7473 if (comp == null) { 7474 if (intent.getSelector() != null) { 7475 intent = intent.getSelector(); 7476 comp = intent.getComponent(); 7477 } 7478 } 7479 if (comp != null) { 7480 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7481 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7482 if (pi != null) { 7483 // When specifying an explicit component, we prevent the provider from being 7484 // used when either 1) the provider is in an instant application and the 7485 // caller is not the same instant application or 2) the calling package is an 7486 // instant application and the provider is not visible to instant applications. 7487 final boolean matchInstantApp = 7488 (flags & PackageManager.MATCH_INSTANT) != 0; 7489 final boolean matchVisibleToInstantAppOnly = 7490 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7491 final boolean isCallerInstantApp = 7492 instantAppPkgName != null; 7493 final boolean isTargetSameInstantApp = 7494 comp.getPackageName().equals(instantAppPkgName); 7495 final boolean isTargetInstantApp = 7496 (pi.applicationInfo.privateFlags 7497 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7498 final boolean isTargetHiddenFromInstantApp = 7499 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7500 final boolean blockResolution = 7501 !isTargetSameInstantApp 7502 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7503 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7504 && isTargetHiddenFromInstantApp)); 7505 if (!blockResolution) { 7506 final ResolveInfo ri = new ResolveInfo(); 7507 ri.providerInfo = pi; 7508 list.add(ri); 7509 } 7510 } 7511 return list; 7512 } 7513 7514 // reader 7515 synchronized (mPackages) { 7516 String pkgName = intent.getPackage(); 7517 if (pkgName == null) { 7518 return applyPostContentProviderResolutionFilter( 7519 mProviders.queryIntent(intent, resolvedType, flags, userId), 7520 instantAppPkgName); 7521 } 7522 final PackageParser.Package pkg = mPackages.get(pkgName); 7523 if (pkg != null) { 7524 return applyPostContentProviderResolutionFilter( 7525 mProviders.queryIntentForPackage( 7526 intent, resolvedType, flags, pkg.providers, userId), 7527 instantAppPkgName); 7528 } 7529 return Collections.emptyList(); 7530 } 7531 } 7532 7533 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7534 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7535 if (instantAppPkgName == null) { 7536 return resolveInfos; 7537 } 7538 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7539 final ResolveInfo info = resolveInfos.get(i); 7540 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7541 // allow providers that are defined in the provided package 7542 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7543 if (info.providerInfo.splitName != null 7544 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7545 info.providerInfo.splitName)) { 7546 // requested provider is defined in a split that hasn't been installed yet. 7547 // add the installer to the resolve list 7548 if (DEBUG_EPHEMERAL) { 7549 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7550 } 7551 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7552 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7553 info.providerInfo.packageName, info.providerInfo.splitName, 7554 null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode, 7555 null /*failureIntent*/); 7556 // make sure this resolver is the default 7557 installerInfo.isDefault = true; 7558 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7559 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7560 // add a non-generic filter 7561 installerInfo.filter = new IntentFilter(); 7562 // load resources from the correct package 7563 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7564 resolveInfos.set(i, installerInfo); 7565 } 7566 continue; 7567 } 7568 // allow providers that have been explicitly exposed to instant applications 7569 if (!isEphemeralApp 7570 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7571 continue; 7572 } 7573 resolveInfos.remove(i); 7574 } 7575 return resolveInfos; 7576 } 7577 7578 @Override 7579 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7580 final int callingUid = Binder.getCallingUid(); 7581 if (getInstantAppPackageName(callingUid) != null) { 7582 return ParceledListSlice.emptyList(); 7583 } 7584 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7585 flags = updateFlagsForPackage(flags, userId, null); 7586 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7587 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7588 true /* requireFullPermission */, false /* checkShell */, 7589 "get installed packages"); 7590 7591 // writer 7592 synchronized (mPackages) { 7593 ArrayList<PackageInfo> list; 7594 if (listUninstalled) { 7595 list = new ArrayList<>(mSettings.mPackages.size()); 7596 for (PackageSetting ps : mSettings.mPackages.values()) { 7597 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7598 continue; 7599 } 7600 if (filterAppAccessLPr(ps, callingUid, userId)) { 7601 continue; 7602 } 7603 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7604 if (pi != null) { 7605 list.add(pi); 7606 } 7607 } 7608 } else { 7609 list = new ArrayList<>(mPackages.size()); 7610 for (PackageParser.Package p : mPackages.values()) { 7611 final PackageSetting ps = (PackageSetting) p.mExtras; 7612 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7613 continue; 7614 } 7615 if (filterAppAccessLPr(ps, callingUid, userId)) { 7616 continue; 7617 } 7618 final PackageInfo pi = generatePackageInfo((PackageSetting) 7619 p.mExtras, flags, userId); 7620 if (pi != null) { 7621 list.add(pi); 7622 } 7623 } 7624 } 7625 7626 return new ParceledListSlice<>(list); 7627 } 7628 } 7629 7630 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7631 String[] permissions, boolean[] tmp, int flags, int userId) { 7632 int numMatch = 0; 7633 final PermissionsState permissionsState = ps.getPermissionsState(); 7634 for (int i=0; i<permissions.length; i++) { 7635 final String permission = permissions[i]; 7636 if (permissionsState.hasPermission(permission, userId)) { 7637 tmp[i] = true; 7638 numMatch++; 7639 } else { 7640 tmp[i] = false; 7641 } 7642 } 7643 if (numMatch == 0) { 7644 return; 7645 } 7646 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7647 7648 // The above might return null in cases of uninstalled apps or install-state 7649 // skew across users/profiles. 7650 if (pi != null) { 7651 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7652 if (numMatch == permissions.length) { 7653 pi.requestedPermissions = permissions; 7654 } else { 7655 pi.requestedPermissions = new String[numMatch]; 7656 numMatch = 0; 7657 for (int i=0; i<permissions.length; i++) { 7658 if (tmp[i]) { 7659 pi.requestedPermissions[numMatch] = permissions[i]; 7660 numMatch++; 7661 } 7662 } 7663 } 7664 } 7665 list.add(pi); 7666 } 7667 } 7668 7669 @Override 7670 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7671 String[] permissions, int flags, int userId) { 7672 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7673 flags = updateFlagsForPackage(flags, userId, permissions); 7674 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7675 true /* requireFullPermission */, false /* checkShell */, 7676 "get packages holding permissions"); 7677 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7678 7679 // writer 7680 synchronized (mPackages) { 7681 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7682 boolean[] tmpBools = new boolean[permissions.length]; 7683 if (listUninstalled) { 7684 for (PackageSetting ps : mSettings.mPackages.values()) { 7685 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7686 userId); 7687 } 7688 } else { 7689 for (PackageParser.Package pkg : mPackages.values()) { 7690 PackageSetting ps = (PackageSetting)pkg.mExtras; 7691 if (ps != null) { 7692 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7693 userId); 7694 } 7695 } 7696 } 7697 7698 return new ParceledListSlice<PackageInfo>(list); 7699 } 7700 } 7701 7702 @Override 7703 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7704 final int callingUid = Binder.getCallingUid(); 7705 if (getInstantAppPackageName(callingUid) != null) { 7706 return ParceledListSlice.emptyList(); 7707 } 7708 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7709 flags = updateFlagsForApplication(flags, userId, null); 7710 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7711 7712 // writer 7713 synchronized (mPackages) { 7714 ArrayList<ApplicationInfo> list; 7715 if (listUninstalled) { 7716 list = new ArrayList<>(mSettings.mPackages.size()); 7717 for (PackageSetting ps : mSettings.mPackages.values()) { 7718 ApplicationInfo ai; 7719 int effectiveFlags = flags; 7720 if (ps.isSystem()) { 7721 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7722 } 7723 if (ps.pkg != null) { 7724 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7725 continue; 7726 } 7727 if (filterAppAccessLPr(ps, callingUid, userId)) { 7728 continue; 7729 } 7730 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7731 ps.readUserState(userId), userId); 7732 if (ai != null) { 7733 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7734 } 7735 } else { 7736 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7737 // and already converts to externally visible package name 7738 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7739 callingUid, effectiveFlags, userId); 7740 } 7741 if (ai != null) { 7742 list.add(ai); 7743 } 7744 } 7745 } else { 7746 list = new ArrayList<>(mPackages.size()); 7747 for (PackageParser.Package p : mPackages.values()) { 7748 if (p.mExtras != null) { 7749 PackageSetting ps = (PackageSetting) p.mExtras; 7750 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 7751 continue; 7752 } 7753 if (filterAppAccessLPr(ps, callingUid, userId)) { 7754 continue; 7755 } 7756 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7757 ps.readUserState(userId), userId); 7758 if (ai != null) { 7759 ai.packageName = resolveExternalPackageNameLPr(p); 7760 list.add(ai); 7761 } 7762 } 7763 } 7764 } 7765 7766 return new ParceledListSlice<>(list); 7767 } 7768 } 7769 7770 @Override 7771 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7772 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7773 return null; 7774 } 7775 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 7776 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7777 "getEphemeralApplications"); 7778 } 7779 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7780 true /* requireFullPermission */, false /* checkShell */, 7781 "getEphemeralApplications"); 7782 synchronized (mPackages) { 7783 List<InstantAppInfo> instantApps = mInstantAppRegistry 7784 .getInstantAppsLPr(userId); 7785 if (instantApps != null) { 7786 return new ParceledListSlice<>(instantApps); 7787 } 7788 } 7789 return null; 7790 } 7791 7792 @Override 7793 public boolean isInstantApp(String packageName, int userId) { 7794 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7795 true /* requireFullPermission */, false /* checkShell */, 7796 "isInstantApp"); 7797 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7798 return false; 7799 } 7800 7801 synchronized (mPackages) { 7802 int callingUid = Binder.getCallingUid(); 7803 if (Process.isIsolated(callingUid)) { 7804 callingUid = mIsolatedOwners.get(callingUid); 7805 } 7806 final PackageSetting ps = mSettings.mPackages.get(packageName); 7807 PackageParser.Package pkg = mPackages.get(packageName); 7808 final boolean returnAllowed = 7809 ps != null 7810 && (isCallerSameApp(packageName, callingUid) 7811 || canViewInstantApps(callingUid, userId) 7812 || mInstantAppRegistry.isInstantAccessGranted( 7813 userId, UserHandle.getAppId(callingUid), ps.appId)); 7814 if (returnAllowed) { 7815 return ps.getInstantApp(userId); 7816 } 7817 } 7818 return false; 7819 } 7820 7821 @Override 7822 public byte[] getInstantAppCookie(String packageName, int userId) { 7823 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7824 return null; 7825 } 7826 7827 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7828 true /* requireFullPermission */, false /* checkShell */, 7829 "getInstantAppCookie"); 7830 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7831 return null; 7832 } 7833 synchronized (mPackages) { 7834 return mInstantAppRegistry.getInstantAppCookieLPw( 7835 packageName, userId); 7836 } 7837 } 7838 7839 @Override 7840 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7841 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7842 return true; 7843 } 7844 7845 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7846 true /* requireFullPermission */, true /* checkShell */, 7847 "setInstantAppCookie"); 7848 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7849 return false; 7850 } 7851 synchronized (mPackages) { 7852 return mInstantAppRegistry.setInstantAppCookieLPw( 7853 packageName, cookie, userId); 7854 } 7855 } 7856 7857 @Override 7858 public Bitmap getInstantAppIcon(String packageName, int userId) { 7859 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7860 return null; 7861 } 7862 7863 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 7864 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7865 "getInstantAppIcon"); 7866 } 7867 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7868 true /* requireFullPermission */, false /* checkShell */, 7869 "getInstantAppIcon"); 7870 7871 synchronized (mPackages) { 7872 return mInstantAppRegistry.getInstantAppIconLPw( 7873 packageName, userId); 7874 } 7875 } 7876 7877 private boolean isCallerSameApp(String packageName, int uid) { 7878 PackageParser.Package pkg = mPackages.get(packageName); 7879 return pkg != null 7880 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 7881 } 7882 7883 @Override 7884 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7885 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 7886 return ParceledListSlice.emptyList(); 7887 } 7888 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7889 } 7890 7891 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7892 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7893 7894 // reader 7895 synchronized (mPackages) { 7896 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7897 final int userId = UserHandle.getCallingUserId(); 7898 while (i.hasNext()) { 7899 final PackageParser.Package p = i.next(); 7900 if (p.applicationInfo == null) continue; 7901 7902 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7903 && !p.applicationInfo.isDirectBootAware(); 7904 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7905 && p.applicationInfo.isDirectBootAware(); 7906 7907 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7908 && (!mSafeMode || isSystemApp(p)) 7909 && (matchesUnaware || matchesAware)) { 7910 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7911 if (ps != null) { 7912 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7913 ps.readUserState(userId), userId); 7914 if (ai != null) { 7915 finalList.add(ai); 7916 } 7917 } 7918 } 7919 } 7920 } 7921 7922 return finalList; 7923 } 7924 7925 @Override 7926 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7927 return resolveContentProviderInternal(name, flags, userId); 7928 } 7929 7930 private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) { 7931 if (!sUserManager.exists(userId)) return null; 7932 flags = updateFlagsForComponent(flags, userId, name); 7933 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 7934 // reader 7935 synchronized (mPackages) { 7936 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7937 PackageSetting ps = provider != null 7938 ? mSettings.mPackages.get(provider.owner.packageName) 7939 : null; 7940 if (ps != null) { 7941 final boolean isInstantApp = ps.getInstantApp(userId); 7942 // normal application; filter out instant application provider 7943 if (instantAppPkgName == null && isInstantApp) { 7944 return null; 7945 } 7946 // instant application; filter out other instant applications 7947 if (instantAppPkgName != null 7948 && isInstantApp 7949 && !provider.owner.packageName.equals(instantAppPkgName)) { 7950 return null; 7951 } 7952 // instant application; filter out non-exposed provider 7953 if (instantAppPkgName != null 7954 && !isInstantApp 7955 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 7956 return null; 7957 } 7958 // provider not enabled 7959 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 7960 return null; 7961 } 7962 return PackageParser.generateProviderInfo( 7963 provider, flags, ps.readUserState(userId), userId); 7964 } 7965 return null; 7966 } 7967 } 7968 7969 /** 7970 * @deprecated 7971 */ 7972 @Deprecated 7973 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7974 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 7975 return; 7976 } 7977 // reader 7978 synchronized (mPackages) { 7979 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7980 .entrySet().iterator(); 7981 final int userId = UserHandle.getCallingUserId(); 7982 while (i.hasNext()) { 7983 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7984 PackageParser.Provider p = entry.getValue(); 7985 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7986 7987 if (ps != null && p.syncable 7988 && (!mSafeMode || (p.info.applicationInfo.flags 7989 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7990 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7991 ps.readUserState(userId), userId); 7992 if (info != null) { 7993 outNames.add(entry.getKey()); 7994 outInfo.add(info); 7995 } 7996 } 7997 } 7998 } 7999 } 8000 8001 @Override 8002 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8003 int uid, int flags, String metaDataKey) { 8004 final int callingUid = Binder.getCallingUid(); 8005 final int userId = processName != null ? UserHandle.getUserId(uid) 8006 : UserHandle.getCallingUserId(); 8007 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8008 flags = updateFlagsForComponent(flags, userId, processName); 8009 ArrayList<ProviderInfo> finalList = null; 8010 // reader 8011 synchronized (mPackages) { 8012 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 8013 while (i.hasNext()) { 8014 final PackageParser.Provider p = i.next(); 8015 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8016 if (ps != null && p.info.authority != null 8017 && (processName == null 8018 || (p.info.processName.equals(processName) 8019 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 8020 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 8021 8022 // See PM.queryContentProviders()'s javadoc for why we have the metaData 8023 // parameter. 8024 if (metaDataKey != null 8025 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 8026 continue; 8027 } 8028 final ComponentName component = 8029 new ComponentName(p.info.packageName, p.info.name); 8030 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8031 continue; 8032 } 8033 if (finalList == null) { 8034 finalList = new ArrayList<ProviderInfo>(3); 8035 } 8036 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8037 ps.readUserState(userId), userId); 8038 if (info != null) { 8039 finalList.add(info); 8040 } 8041 } 8042 } 8043 } 8044 8045 if (finalList != null) { 8046 Collections.sort(finalList, mProviderInitOrderSorter); 8047 return new ParceledListSlice<ProviderInfo>(finalList); 8048 } 8049 8050 return ParceledListSlice.emptyList(); 8051 } 8052 8053 @Override 8054 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8055 // reader 8056 synchronized (mPackages) { 8057 final int callingUid = Binder.getCallingUid(); 8058 final int callingUserId = UserHandle.getUserId(callingUid); 8059 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8060 if (ps == null) return null; 8061 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8062 return null; 8063 } 8064 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8065 return PackageParser.generateInstrumentationInfo(i, flags); 8066 } 8067 } 8068 8069 @Override 8070 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8071 String targetPackage, int flags) { 8072 final int callingUid = Binder.getCallingUid(); 8073 final int callingUserId = UserHandle.getUserId(callingUid); 8074 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8075 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8076 return ParceledListSlice.emptyList(); 8077 } 8078 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8079 } 8080 8081 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8082 int flags) { 8083 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 8084 8085 // reader 8086 synchronized (mPackages) { 8087 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8088 while (i.hasNext()) { 8089 final PackageParser.Instrumentation p = i.next(); 8090 if (targetPackage == null 8091 || targetPackage.equals(p.info.targetPackage)) { 8092 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8093 flags); 8094 if (ii != null) { 8095 finalList.add(ii); 8096 } 8097 } 8098 } 8099 } 8100 8101 return finalList; 8102 } 8103 8104 private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) { 8105 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]"); 8106 try { 8107 scanDirLI(scanDir, parseFlags, scanFlags, currentTime); 8108 } finally { 8109 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8110 } 8111 } 8112 8113 private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) { 8114 final File[] files = scanDir.listFiles(); 8115 if (ArrayUtils.isEmpty(files)) { 8116 Log.d(TAG, "No files in app dir " + scanDir); 8117 return; 8118 } 8119 8120 if (DEBUG_PACKAGE_SCANNING) { 8121 Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags 8122 + " flags=0x" + Integer.toHexString(parseFlags)); 8123 } 8124 try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8125 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8126 mParallelPackageParserCallback)) { 8127 // Submit files for parsing in parallel 8128 int fileCount = 0; 8129 for (File file : files) { 8130 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8131 && !PackageInstallerService.isStageName(file.getName()); 8132 if (!isPackage) { 8133 // Ignore entries which are not packages 8134 continue; 8135 } 8136 parallelPackageParser.submit(file, parseFlags); 8137 fileCount++; 8138 } 8139 8140 // Process results one by one 8141 for (; fileCount > 0; fileCount--) { 8142 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8143 Throwable throwable = parseResult.throwable; 8144 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8145 8146 if (throwable == null) { 8147 // TODO(toddke): move lower in the scan chain 8148 // Static shared libraries have synthetic package names 8149 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8150 renameStaticSharedLibraryPackage(parseResult.pkg); 8151 } 8152 try { 8153 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8154 scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags, 8155 currentTime, null); 8156 } 8157 } catch (PackageManagerException e) { 8158 errorCode = e.error; 8159 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8160 } 8161 } else if (throwable instanceof PackageParser.PackageParserException) { 8162 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8163 throwable; 8164 errorCode = e.error; 8165 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8166 } else { 8167 throw new IllegalStateException("Unexpected exception occurred while parsing " 8168 + parseResult.scanFile, throwable); 8169 } 8170 8171 // Delete invalid userdata apps 8172 if ((scanFlags & SCAN_AS_SYSTEM) == 0 && 8173 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8174 logCriticalInfo(Log.WARN, 8175 "Deleting invalid package at " + parseResult.scanFile); 8176 removeCodePathLI(parseResult.scanFile); 8177 } 8178 } 8179 } 8180 } 8181 8182 public static void reportSettingsProblem(int priority, String msg) { 8183 logCriticalInfo(priority, msg); 8184 } 8185 8186 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, 8187 final @ParseFlags int parseFlags) throws PackageManagerException { 8188 // When upgrading from pre-N MR1, verify the package time stamp using the package 8189 // directory and not the APK file. 8190 final long lastModifiedTime = mIsPreNMR1Upgrade 8191 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg); 8192 if (ps != null 8193 && ps.codePathString.equals(pkg.codePath) 8194 && ps.timeStamp == lastModifiedTime 8195 && !isCompatSignatureUpdateNeeded(pkg) 8196 && !isRecoverSignatureUpdateNeeded(pkg)) { 8197 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 8198 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 8199 ArraySet<PublicKey> signingKs; 8200 synchronized (mPackages) { 8201 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 8202 } 8203 if (ps.signatures.mSignatures != null 8204 && ps.signatures.mSignatures.length != 0 8205 && signingKs != null) { 8206 // Optimization: reuse the existing cached certificates 8207 // if the package appears to be unchanged. 8208 pkg.mSignatures = ps.signatures.mSignatures; 8209 pkg.mSigningKeys = signingKs; 8210 return; 8211 } 8212 8213 Slog.w(TAG, "PackageSetting for " + ps.name 8214 + " is missing signatures. Collecting certs again to recover them."); 8215 } else { 8216 Slog.i(TAG, toString() + " changed; collecting certs"); 8217 } 8218 8219 try { 8220 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8221 PackageParser.collectCertificates(pkg, parseFlags); 8222 } catch (PackageParserException e) { 8223 throw PackageManagerException.from(e); 8224 } finally { 8225 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8226 } 8227 } 8228 8229 /** 8230 * Traces a package scan. 8231 * @see #scanPackageLI(File, int, int, long, UserHandle) 8232 */ 8233 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8234 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8235 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8236 try { 8237 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8238 } finally { 8239 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8240 } 8241 } 8242 8243 /** 8244 * Scans a package and returns the newly parsed package. 8245 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8246 */ 8247 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8248 long currentTime, UserHandle user) throws PackageManagerException { 8249 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8250 PackageParser pp = new PackageParser(); 8251 pp.setSeparateProcesses(mSeparateProcesses); 8252 pp.setOnlyCoreApps(mOnlyCore); 8253 pp.setDisplayMetrics(mMetrics); 8254 pp.setCallback(mPackageParserCallback); 8255 8256 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8257 final PackageParser.Package pkg; 8258 try { 8259 pkg = pp.parsePackage(scanFile, parseFlags); 8260 } catch (PackageParserException e) { 8261 throw PackageManagerException.from(e); 8262 } finally { 8263 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8264 } 8265 8266 // Static shared libraries have synthetic package names 8267 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8268 renameStaticSharedLibraryPackage(pkg); 8269 } 8270 8271 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8272 } 8273 8274 /** 8275 * Scans a package and returns the newly parsed package. 8276 * @throws PackageManagerException on a parse error. 8277 */ 8278 private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg, 8279 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8280 @Nullable UserHandle user) 8281 throws PackageManagerException { 8282 // If the package has children and this is the first dive in the function 8283 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8284 // packages (parent and children) would be successfully scanned before the 8285 // actual scan since scanning mutates internal state and we want to atomically 8286 // install the package and its children. 8287 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8288 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8289 scanFlags |= SCAN_CHECK_ONLY; 8290 } 8291 } else { 8292 scanFlags &= ~SCAN_CHECK_ONLY; 8293 } 8294 8295 // Scan the parent 8296 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, parseFlags, 8297 scanFlags, currentTime, user); 8298 8299 // Scan the children 8300 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8301 for (int i = 0; i < childCount; i++) { 8302 PackageParser.Package childPackage = pkg.childPackages.get(i); 8303 scanPackageInternalLI(childPackage, parseFlags, scanFlags, 8304 currentTime, user); 8305 } 8306 8307 8308 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8309 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8310 } 8311 8312 return scannedPkg; 8313 } 8314 8315 /** 8316 * Scans a package and returns the newly parsed package. 8317 * @throws PackageManagerException on a parse error. 8318 */ 8319 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, 8320 @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8321 @Nullable UserHandle user) 8322 throws PackageManagerException { 8323 PackageSetting ps = null; 8324 PackageSetting updatedPs; 8325 // reader 8326 synchronized (mPackages) { 8327 // Look to see if we already know about this package. 8328 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 8329 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 8330 // This package has been renamed to its original name. Let's 8331 // use that. 8332 ps = mSettings.getPackageLPr(oldName); 8333 } 8334 // If there was no original package, see one for the real package name. 8335 if (ps == null) { 8336 ps = mSettings.getPackageLPr(pkg.packageName); 8337 } 8338 // Check to see if this package could be hiding/updating a system 8339 // package. Must look for it either under the original or real 8340 // package name depending on our state. 8341 updatedPs = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 8342 if (DEBUG_INSTALL && updatedPs != null) Slog.d(TAG, "updatedPkg = " + updatedPs); 8343 8344 // If this is a package we don't know about on the system partition, we 8345 // may need to remove disabled child packages on the system partition 8346 // or may need to not add child packages if the parent apk is updated 8347 // on the data partition and no longer defines this child package. 8348 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 8349 // If this is a parent package for an updated system app and this system 8350 // app got an OTA update which no longer defines some of the child packages 8351 // we have to prune them from the disabled system packages. 8352 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8353 if (disabledPs != null) { 8354 final int scannedChildCount = (pkg.childPackages != null) 8355 ? pkg.childPackages.size() : 0; 8356 final int disabledChildCount = disabledPs.childPackageNames != null 8357 ? disabledPs.childPackageNames.size() : 0; 8358 for (int i = 0; i < disabledChildCount; i++) { 8359 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 8360 boolean disabledPackageAvailable = false; 8361 for (int j = 0; j < scannedChildCount; j++) { 8362 PackageParser.Package childPkg = pkg.childPackages.get(j); 8363 if (childPkg.packageName.equals(disabledChildPackageName)) { 8364 disabledPackageAvailable = true; 8365 break; 8366 } 8367 } 8368 if (!disabledPackageAvailable) { 8369 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8370 } 8371 } 8372 } 8373 } 8374 } 8375 8376 final boolean isUpdatedPkg = updatedPs != null; 8377 final boolean isUpdatedSystemPkg = isUpdatedPkg && (scanFlags & SCAN_AS_SYSTEM) != 0; 8378 boolean isUpdatedPkgBetter = false; 8379 // First check if this is a system package that may involve an update 8380 if (isUpdatedSystemPkg) { 8381 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 8382 // it needs to drop FLAG_PRIVILEGED. 8383 if (locationIsPrivileged(pkg.codePath)) { 8384 updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8385 } else { 8386 updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8387 } 8388 // If new package is not located in "/oem" (e.g. due to an OTA), 8389 // it needs to drop FLAG_OEM. 8390 if (locationIsOem(pkg.codePath)) { 8391 updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 8392 } else { 8393 updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM; 8394 } 8395 // If new package is not located in "/vendor" (e.g. due to an OTA), 8396 // it needs to drop FLAG_VENDOR. 8397 if (locationIsVendor(pkg.codePath)) { 8398 updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR; 8399 } else { 8400 updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_VENDOR; 8401 } 8402 8403 if (ps != null && !ps.codePathString.equals(pkg.codePath)) { 8404 // The path has changed from what was last scanned... check the 8405 // version of the new path against what we have stored to determine 8406 // what to do. 8407 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 8408 if (pkg.getLongVersionCode() <= ps.versionCode) { 8409 // The system package has been updated and the code path does not match 8410 // Ignore entry. Skip it. 8411 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + pkg.codePath 8412 + " ignored: updated version " + ps.versionCode 8413 + " better than this " + pkg.getLongVersionCode()); 8414 if (!updatedPs.codePathString.equals(pkg.codePath)) { 8415 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 8416 + ps.name + " changing from " + updatedPs.codePathString 8417 + " to " + pkg.codePath); 8418 final File codePath = new File(pkg.codePath); 8419 updatedPs.codePath = codePath; 8420 updatedPs.codePathString = pkg.codePath; 8421 updatedPs.resourcePath = codePath; 8422 updatedPs.resourcePathString = pkg.codePath; 8423 } 8424 updatedPs.pkg = pkg; 8425 updatedPs.versionCode = pkg.getLongVersionCode(); 8426 8427 // Update the disabled system child packages to point to the package too. 8428 final int childCount = updatedPs.childPackageNames != null 8429 ? updatedPs.childPackageNames.size() : 0; 8430 for (int i = 0; i < childCount; i++) { 8431 String childPackageName = updatedPs.childPackageNames.get(i); 8432 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 8433 childPackageName); 8434 if (updatedChildPkg != null) { 8435 updatedChildPkg.pkg = pkg; 8436 updatedChildPkg.versionCode = pkg.getLongVersionCode(); 8437 } 8438 } 8439 } else { 8440 // The current app on the system partition is better than 8441 // what we have updated to on the data partition; switch 8442 // back to the system partition version. 8443 // At this point, its safely assumed that package installation for 8444 // apps in system partition will go through. If not there won't be a working 8445 // version of the app 8446 // writer 8447 synchronized (mPackages) { 8448 // Just remove the loaded entries from package lists. 8449 mPackages.remove(ps.name); 8450 } 8451 8452 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + pkg.codePath 8453 + " reverting from " + ps.codePathString 8454 + ": new version " + pkg.getLongVersionCode() 8455 + " better than installed " + ps.versionCode); 8456 8457 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8458 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8459 synchronized (mInstallLock) { 8460 args.cleanUpResourcesLI(); 8461 } 8462 synchronized (mPackages) { 8463 mSettings.enableSystemPackageLPw(ps.name); 8464 } 8465 isUpdatedPkgBetter = true; 8466 } 8467 } 8468 } 8469 8470 String resourcePath = null; 8471 String baseResourcePath = null; 8472 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) { 8473 if (ps != null && ps.resourcePathString != null) { 8474 resourcePath = ps.resourcePathString; 8475 baseResourcePath = ps.resourcePathString; 8476 } else { 8477 // Should not happen at all. Just log an error. 8478 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8479 } 8480 } else { 8481 resourcePath = pkg.codePath; 8482 baseResourcePath = pkg.baseCodePath; 8483 } 8484 8485 // Set application objects path explicitly. 8486 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8487 pkg.setApplicationInfoCodePath(pkg.codePath); 8488 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8489 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8490 pkg.setApplicationInfoResourcePath(resourcePath); 8491 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8492 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8493 8494 // throw an exception if we have an update to a system application, but, it's not more 8495 // recent than the package we've already scanned 8496 if (isUpdatedSystemPkg && !isUpdatedPkgBetter) { 8497 // Set CPU Abis to application info. 8498 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 8499 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPs); 8500 derivePackageAbi(pkg, cpuAbiOverride, false); 8501 } else { 8502 pkg.applicationInfo.primaryCpuAbi = updatedPs.primaryCpuAbiString; 8503 pkg.applicationInfo.secondaryCpuAbi = updatedPs.secondaryCpuAbiString; 8504 } 8505 pkg.mExtras = updatedPs; 8506 8507 throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at " 8508 + pkg.codePath + " ignored: updated version " + updatedPs.versionCode 8509 + " better than this " + pkg.getLongVersionCode()); 8510 } 8511 8512 if (isUpdatedPkg) { 8513 // updated system applications don't initially have the SCAN_AS_SYSTEM flag set 8514 scanFlags |= SCAN_AS_SYSTEM; 8515 8516 // An updated privileged application will not have the PARSE_IS_PRIVILEGED 8517 // flag set initially 8518 if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 8519 scanFlags |= SCAN_AS_PRIVILEGED; 8520 } 8521 8522 // An updated OEM app will not have the SCAN_AS_OEM 8523 // flag set initially 8524 if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) { 8525 scanFlags |= SCAN_AS_OEM; 8526 } 8527 8528 // An updated vendor app will not have the SCAN_AS_VENDOR 8529 // flag set initially 8530 if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) { 8531 scanFlags |= SCAN_AS_VENDOR; 8532 } 8533 } 8534 8535 // Verify certificates against what was last scanned 8536 collectCertificatesLI(ps, pkg, parseFlags); 8537 8538 /* 8539 * A new system app appeared, but we already had a non-system one of the 8540 * same name installed earlier. 8541 */ 8542 boolean shouldHideSystemApp = false; 8543 if (!isUpdatedPkg && ps != null 8544 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 8545 /* 8546 * Check to make sure the signatures match first. If they don't, 8547 * wipe the installed application and its data. 8548 */ 8549 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 8550 != PackageManager.SIGNATURE_MATCH) { 8551 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 8552 + " signatures don't match existing userdata copy; removing"); 8553 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8554 "scanPackageInternalLI")) { 8555 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8556 } 8557 ps = null; 8558 } else { 8559 /* 8560 * If the newly-added system app is an older version than the 8561 * already installed version, hide it. It will be scanned later 8562 * and re-added like an update. 8563 */ 8564 if (pkg.getLongVersionCode() <= ps.versionCode) { 8565 shouldHideSystemApp = true; 8566 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + pkg.codePath 8567 + " but new version " + pkg.getLongVersionCode() 8568 + " better than installed " + ps.versionCode + "; hiding system"); 8569 } else { 8570 /* 8571 * The newly found system app is a newer version that the 8572 * one previously installed. Simply remove the 8573 * already-installed application and replace it with our own 8574 * while keeping the application data. 8575 */ 8576 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + pkg.codePath 8577 + " reverting from " + ps.codePathString + ": new version " 8578 + pkg.getLongVersionCode() + " better than installed " 8579 + ps.versionCode); 8580 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8581 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8582 synchronized (mInstallLock) { 8583 args.cleanUpResourcesLI(); 8584 } 8585 } 8586 } 8587 } 8588 8589 // The apk is forward locked (not public) if its code and resources 8590 // are kept in different files. (except for app in either system or 8591 // vendor path). 8592 // TODO grab this value from PackageSettings 8593 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8594 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8595 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 8596 } 8597 } 8598 8599 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8600 if (ps != null && ps.getInstantApp(userId)) { 8601 scanFlags |= SCAN_AS_INSTANT_APP; 8602 } 8603 if (ps != null && ps.getVirtulalPreload(userId)) { 8604 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 8605 } 8606 8607 // Note that we invoke the following method only if we are about to unpack an application 8608 PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags 8609 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8610 8611 /* 8612 * If the system app should be overridden by a previously installed 8613 * data, hide the system app now and let the /data/app scan pick it up 8614 * again. 8615 */ 8616 if (shouldHideSystemApp) { 8617 synchronized (mPackages) { 8618 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8619 } 8620 } 8621 8622 return scannedPkg; 8623 } 8624 8625 private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8626 // Derive the new package synthetic package name 8627 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8628 + pkg.staticSharedLibVersion); 8629 } 8630 8631 private static String fixProcessName(String defProcessName, 8632 String processName) { 8633 if (processName == null) { 8634 return defProcessName; 8635 } 8636 return processName; 8637 } 8638 8639 /** 8640 * Enforces that only the system UID or root's UID can call a method exposed 8641 * via Binder. 8642 * 8643 * @param message used as message if SecurityException is thrown 8644 * @throws SecurityException if the caller is not system or root 8645 */ 8646 private static final void enforceSystemOrRoot(String message) { 8647 final int uid = Binder.getCallingUid(); 8648 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 8649 throw new SecurityException(message); 8650 } 8651 } 8652 8653 @Override 8654 public void performFstrimIfNeeded() { 8655 enforceSystemOrRoot("Only the system can request fstrim"); 8656 8657 // Before everything else, see whether we need to fstrim. 8658 try { 8659 IStorageManager sm = PackageHelper.getStorageManager(); 8660 if (sm != null) { 8661 boolean doTrim = false; 8662 final long interval = android.provider.Settings.Global.getLong( 8663 mContext.getContentResolver(), 8664 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8665 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8666 if (interval > 0) { 8667 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8668 if (timeSinceLast > interval) { 8669 doTrim = true; 8670 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8671 + "; running immediately"); 8672 } 8673 } 8674 if (doTrim) { 8675 final boolean dexOptDialogShown; 8676 synchronized (mPackages) { 8677 dexOptDialogShown = mDexOptDialogShown; 8678 } 8679 if (!isFirstBoot() && dexOptDialogShown) { 8680 try { 8681 ActivityManager.getService().showBootMessage( 8682 mContext.getResources().getString( 8683 R.string.android_upgrading_fstrim), true); 8684 } catch (RemoteException e) { 8685 } 8686 } 8687 sm.runMaintenance(); 8688 } 8689 } else { 8690 Slog.e(TAG, "storageManager service unavailable!"); 8691 } 8692 } catch (RemoteException e) { 8693 // Can't happen; StorageManagerService is local 8694 } 8695 } 8696 8697 @Override 8698 public void updatePackagesIfNeeded() { 8699 enforceSystemOrRoot("Only the system can request package update"); 8700 8701 // We need to re-extract after an OTA. 8702 boolean causeUpgrade = isUpgrade(); 8703 8704 // First boot or factory reset. 8705 // Note: we also handle devices that are upgrading to N right now as if it is their 8706 // first boot, as they do not have profile data. 8707 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8708 8709 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8710 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8711 8712 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8713 return; 8714 } 8715 8716 List<PackageParser.Package> pkgs; 8717 synchronized (mPackages) { 8718 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8719 } 8720 8721 final long startTime = System.nanoTime(); 8722 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8723 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 8724 false /* bootComplete */); 8725 8726 final int elapsedTimeSeconds = 8727 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8728 8729 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8730 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8731 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8732 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8733 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8734 } 8735 8736 /* 8737 * Return the prebuilt profile path given a package base code path. 8738 */ 8739 private static String getPrebuildProfilePath(PackageParser.Package pkg) { 8740 return pkg.baseCodePath + ".prof"; 8741 } 8742 8743 /** 8744 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8745 * containing statistics about the invocation. The array consists of three elements, 8746 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8747 * and {@code numberOfPackagesFailed}. 8748 */ 8749 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8750 final String compilerFilter, boolean bootComplete) { 8751 8752 int numberOfPackagesVisited = 0; 8753 int numberOfPackagesOptimized = 0; 8754 int numberOfPackagesSkipped = 0; 8755 int numberOfPackagesFailed = 0; 8756 final int numberOfPackagesToDexopt = pkgs.size(); 8757 8758 for (PackageParser.Package pkg : pkgs) { 8759 numberOfPackagesVisited++; 8760 8761 boolean useProfileForDexopt = false; 8762 8763 if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) { 8764 // Copy over initial preopt profiles since we won't get any JIT samples for methods 8765 // that are already compiled. 8766 File profileFile = new File(getPrebuildProfilePath(pkg)); 8767 // Copy profile if it exists. 8768 if (profileFile.exists()) { 8769 try { 8770 // We could also do this lazily before calling dexopt in 8771 // PackageDexOptimizer to prevent this happening on first boot. The issue 8772 // is that we don't have a good way to say "do this only once". 8773 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8774 pkg.applicationInfo.uid, pkg.packageName)) { 8775 Log.e(TAG, "Installer failed to copy system profile!"); 8776 } else { 8777 // Disabled as this causes speed-profile compilation during first boot 8778 // even if things are already compiled. 8779 // useProfileForDexopt = true; 8780 } 8781 } catch (Exception e) { 8782 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", 8783 e); 8784 } 8785 } else { 8786 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8787 // Handle compressed APKs in this path. Only do this for stubs with profiles to 8788 // minimize the number off apps being speed-profile compiled during first boot. 8789 // The other paths will not change the filter. 8790 if (disabledPs != null && disabledPs.pkg.isStub) { 8791 // The package is the stub one, remove the stub suffix to get the normal 8792 // package and APK names. 8793 String systemProfilePath = 8794 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, ""); 8795 profileFile = new File(systemProfilePath); 8796 // If we have a profile for a compressed APK, copy it to the reference 8797 // location. 8798 // Note that copying the profile here will cause it to override the 8799 // reference profile every OTA even though the existing reference profile 8800 // may have more data. We can't copy during decompression since the 8801 // directories are not set up at that point. 8802 if (profileFile.exists()) { 8803 try { 8804 // We could also do this lazily before calling dexopt in 8805 // PackageDexOptimizer to prevent this happening on first boot. The 8806 // issue is that we don't have a good way to say "do this only 8807 // once". 8808 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8809 pkg.applicationInfo.uid, pkg.packageName)) { 8810 Log.e(TAG, "Failed to copy system profile for stub package!"); 8811 } else { 8812 useProfileForDexopt = true; 8813 } 8814 } catch (Exception e) { 8815 Log.e(TAG, "Failed to copy profile " + 8816 profileFile.getAbsolutePath() + " ", e); 8817 } 8818 } 8819 } 8820 } 8821 } 8822 8823 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8824 if (DEBUG_DEXOPT) { 8825 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8826 } 8827 numberOfPackagesSkipped++; 8828 continue; 8829 } 8830 8831 if (DEBUG_DEXOPT) { 8832 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8833 numberOfPackagesToDexopt + ": " + pkg.packageName); 8834 } 8835 8836 if (showDialog) { 8837 try { 8838 ActivityManager.getService().showBootMessage( 8839 mContext.getResources().getString(R.string.android_upgrading_apk, 8840 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8841 } catch (RemoteException e) { 8842 } 8843 synchronized (mPackages) { 8844 mDexOptDialogShown = true; 8845 } 8846 } 8847 8848 String pkgCompilerFilter = compilerFilter; 8849 if (useProfileForDexopt) { 8850 // Use background dexopt mode to try and use the profile. Note that this does not 8851 // guarantee usage of the profile. 8852 pkgCompilerFilter = 8853 PackageManagerServiceCompilerMapping.getCompilerFilterForReason( 8854 PackageManagerService.REASON_BACKGROUND_DEXOPT); 8855 } 8856 8857 // checkProfiles is false to avoid merging profiles during boot which 8858 // might interfere with background compilation (b/28612421). 8859 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8860 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8861 // trade-off worth doing to save boot time work. 8862 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0; 8863 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions( 8864 pkg.packageName, 8865 pkgCompilerFilter, 8866 dexoptFlags)); 8867 8868 switch (primaryDexOptStaus) { 8869 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8870 numberOfPackagesOptimized++; 8871 break; 8872 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8873 numberOfPackagesSkipped++; 8874 break; 8875 case PackageDexOptimizer.DEX_OPT_FAILED: 8876 numberOfPackagesFailed++; 8877 break; 8878 default: 8879 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus); 8880 break; 8881 } 8882 } 8883 8884 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8885 numberOfPackagesFailed }; 8886 } 8887 8888 @Override 8889 public void notifyPackageUse(String packageName, int reason) { 8890 synchronized (mPackages) { 8891 final int callingUid = Binder.getCallingUid(); 8892 final int callingUserId = UserHandle.getUserId(callingUid); 8893 if (getInstantAppPackageName(callingUid) != null) { 8894 if (!isCallerSameApp(packageName, callingUid)) { 8895 return; 8896 } 8897 } else { 8898 if (isInstantApp(packageName, callingUserId)) { 8899 return; 8900 } 8901 } 8902 notifyPackageUseLocked(packageName, reason); 8903 } 8904 } 8905 8906 private void notifyPackageUseLocked(String packageName, int reason) { 8907 final PackageParser.Package p = mPackages.get(packageName); 8908 if (p == null) { 8909 return; 8910 } 8911 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8912 } 8913 8914 @Override 8915 public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames, 8916 List<String> classPaths, String loaderIsa) { 8917 int userId = UserHandle.getCallingUserId(); 8918 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8919 if (ai == null) { 8920 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8921 + loadingPackageName + ", user=" + userId); 8922 return; 8923 } 8924 mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId); 8925 } 8926 8927 @Override 8928 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule, 8929 IDexModuleRegisterCallback callback) { 8930 int userId = UserHandle.getCallingUserId(); 8931 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId); 8932 DexManager.RegisterDexModuleResult result; 8933 if (ai == null) { 8934 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" + 8935 " calling user. package=" + packageName + ", user=" + userId); 8936 result = new DexManager.RegisterDexModuleResult(false, "Package not installed"); 8937 } else { 8938 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId); 8939 } 8940 8941 if (callback != null) { 8942 mHandler.post(() -> { 8943 try { 8944 callback.onDexModuleRegistered(dexModulePath, result.success, result.message); 8945 } catch (RemoteException e) { 8946 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e); 8947 } 8948 }); 8949 } 8950 } 8951 8952 /** 8953 * Ask the package manager to perform a dex-opt with the given compiler filter. 8954 * 8955 * Note: exposed only for the shell command to allow moving packages explicitly to a 8956 * definite state. 8957 */ 8958 @Override 8959 public boolean performDexOptMode(String packageName, 8960 boolean checkProfiles, String targetCompilerFilter, boolean force, 8961 boolean bootComplete, String splitName) { 8962 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) | 8963 (force ? DexoptOptions.DEXOPT_FORCE : 0) | 8964 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0); 8965 return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter, 8966 splitName, flags)); 8967 } 8968 8969 /** 8970 * Ask the package manager to perform a dex-opt with the given compiler filter on the 8971 * secondary dex files belonging to the given package. 8972 * 8973 * Note: exposed only for the shell command to allow moving packages explicitly to a 8974 * definite state. 8975 */ 8976 @Override 8977 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8978 boolean force) { 8979 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX | 8980 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES | 8981 DexoptOptions.DEXOPT_BOOT_COMPLETE | 8982 (force ? DexoptOptions.DEXOPT_FORCE : 0); 8983 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags)); 8984 } 8985 8986 /*package*/ boolean performDexOpt(DexoptOptions options) { 8987 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8988 return false; 8989 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) { 8990 return false; 8991 } 8992 8993 if (options.isDexoptOnlySecondaryDex()) { 8994 return mDexManager.dexoptSecondaryDex(options); 8995 } else { 8996 int dexoptStatus = performDexOptWithStatus(options); 8997 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8998 } 8999 } 9000 9001 /** 9002 * Perform dexopt on the given package and return one of following result: 9003 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9004 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9005 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9006 */ 9007 /* package */ int performDexOptWithStatus(DexoptOptions options) { 9008 return performDexOptTraced(options); 9009 } 9010 9011 private int performDexOptTraced(DexoptOptions options) { 9012 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9013 try { 9014 return performDexOptInternal(options); 9015 } finally { 9016 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9017 } 9018 } 9019 9020 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9021 // if the package can now be considered up to date for the given filter. 9022 private int performDexOptInternal(DexoptOptions options) { 9023 PackageParser.Package p; 9024 synchronized (mPackages) { 9025 p = mPackages.get(options.getPackageName()); 9026 if (p == null) { 9027 // Package could not be found. Report failure. 9028 return PackageDexOptimizer.DEX_OPT_FAILED; 9029 } 9030 mPackageUsage.maybeWriteAsync(mPackages); 9031 mCompilerStats.maybeWriteAsync(); 9032 } 9033 long callingId = Binder.clearCallingIdentity(); 9034 try { 9035 synchronized (mInstallLock) { 9036 return performDexOptInternalWithDependenciesLI(p, options); 9037 } 9038 } finally { 9039 Binder.restoreCallingIdentity(callingId); 9040 } 9041 } 9042 9043 public ArraySet<String> getOptimizablePackages() { 9044 ArraySet<String> pkgs = new ArraySet<String>(); 9045 synchronized (mPackages) { 9046 for (PackageParser.Package p : mPackages.values()) { 9047 if (PackageDexOptimizer.canOptimizePackage(p)) { 9048 pkgs.add(p.packageName); 9049 } 9050 } 9051 } 9052 return pkgs; 9053 } 9054 9055 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9056 DexoptOptions options) { 9057 // Select the dex optimizer based on the force parameter. 9058 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9059 // allocate an object here. 9060 PackageDexOptimizer pdo = options.isForce() 9061 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9062 : mPackageDexOptimizer; 9063 9064 // Dexopt all dependencies first. Note: we ignore the return value and march on 9065 // on errors. 9066 // Note that we are going to call performDexOpt on those libraries as many times as 9067 // they are referenced in packages. When we do a batch of performDexOpt (for example 9068 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9069 // and the first package that uses the library will dexopt it. The 9070 // others will see that the compiled code for the library is up to date. 9071 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 9072 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9073 if (!deps.isEmpty()) { 9074 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(), 9075 options.getCompilerFilter(), options.getSplitName(), 9076 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY); 9077 for (PackageParser.Package depPackage : deps) { 9078 // TODO: Analyze and investigate if we (should) profile libraries. 9079 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 9080 getOrCreateCompilerPackageStats(depPackage), 9081 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions); 9082 } 9083 } 9084 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, 9085 getOrCreateCompilerPackageStats(p), 9086 mDexManager.getPackageUseInfoOrDefault(p.packageName), options); 9087 } 9088 9089 /** 9090 * Reconcile the information we have about the secondary dex files belonging to 9091 * {@code packagName} and the actual dex files. For all dex files that were 9092 * deleted, update the internal records and delete the generated oat files. 9093 */ 9094 @Override 9095 public void reconcileSecondaryDexFiles(String packageName) { 9096 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9097 return; 9098 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9099 return; 9100 } 9101 mDexManager.reconcileSecondaryDexFiles(packageName); 9102 } 9103 9104 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 9105 // a reference there. 9106 /*package*/ DexManager getDexManager() { 9107 return mDexManager; 9108 } 9109 9110 /** 9111 * Execute the background dexopt job immediately. 9112 */ 9113 @Override 9114 public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) { 9115 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9116 return false; 9117 } 9118 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames); 9119 } 9120 9121 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 9122 if (p.usesLibraries != null || p.usesOptionalLibraries != null 9123 || p.usesStaticLibraries != null) { 9124 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 9125 Set<String> collectedNames = new HashSet<>(); 9126 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 9127 9128 retValue.remove(p); 9129 9130 return retValue; 9131 } else { 9132 return Collections.emptyList(); 9133 } 9134 } 9135 9136 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 9137 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9138 if (!collectedNames.contains(p.packageName)) { 9139 collectedNames.add(p.packageName); 9140 collected.add(p); 9141 9142 if (p.usesLibraries != null) { 9143 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 9144 null, collected, collectedNames); 9145 } 9146 if (p.usesOptionalLibraries != null) { 9147 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 9148 null, collected, collectedNames); 9149 } 9150 if (p.usesStaticLibraries != null) { 9151 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 9152 p.usesStaticLibrariesVersions, collected, collectedNames); 9153 } 9154 } 9155 } 9156 9157 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions, 9158 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9159 final int libNameCount = libs.size(); 9160 for (int i = 0; i < libNameCount; i++) { 9161 String libName = libs.get(i); 9162 long version = (versions != null && versions.length == libNameCount) 9163 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 9164 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 9165 if (libPkg != null) { 9166 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 9167 } 9168 } 9169 } 9170 9171 private PackageParser.Package findSharedNonSystemLibrary(String name, long version) { 9172 synchronized (mPackages) { 9173 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 9174 if (libEntry != null) { 9175 return mPackages.get(libEntry.apk); 9176 } 9177 return null; 9178 } 9179 } 9180 9181 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) { 9182 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9183 if (versionedLib == null) { 9184 return null; 9185 } 9186 return versionedLib.get(version); 9187 } 9188 9189 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9190 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9191 pkg.staticSharedLibName); 9192 if (versionedLib == null) { 9193 return null; 9194 } 9195 long previousLibVersion = -1; 9196 final int versionCount = versionedLib.size(); 9197 for (int i = 0; i < versionCount; i++) { 9198 final long libVersion = versionedLib.keyAt(i); 9199 if (libVersion < pkg.staticSharedLibVersion) { 9200 previousLibVersion = Math.max(previousLibVersion, libVersion); 9201 } 9202 } 9203 if (previousLibVersion >= 0) { 9204 return versionedLib.get(previousLibVersion); 9205 } 9206 return null; 9207 } 9208 9209 public void shutdown() { 9210 mPackageUsage.writeNow(mPackages); 9211 mCompilerStats.writeNow(); 9212 mDexManager.writePackageDexUsageNow(); 9213 } 9214 9215 @Override 9216 public void dumpProfiles(String packageName) { 9217 PackageParser.Package pkg; 9218 synchronized (mPackages) { 9219 pkg = mPackages.get(packageName); 9220 if (pkg == null) { 9221 throw new IllegalArgumentException("Unknown package: " + packageName); 9222 } 9223 } 9224 /* Only the shell, root, or the app user should be able to dump profiles. */ 9225 int callingUid = Binder.getCallingUid(); 9226 if (callingUid != Process.SHELL_UID && 9227 callingUid != Process.ROOT_UID && 9228 callingUid != pkg.applicationInfo.uid) { 9229 throw new SecurityException("dumpProfiles"); 9230 } 9231 9232 synchronized (mInstallLock) { 9233 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9234 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 9235 try { 9236 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 9237 String codePaths = TextUtils.join(";", allCodePaths); 9238 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 9239 } catch (InstallerException e) { 9240 Slog.w(TAG, "Failed to dump profiles", e); 9241 } 9242 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9243 } 9244 } 9245 9246 @Override 9247 public void forceDexOpt(String packageName) { 9248 enforceSystemOrRoot("forceDexOpt"); 9249 9250 PackageParser.Package pkg; 9251 synchronized (mPackages) { 9252 pkg = mPackages.get(packageName); 9253 if (pkg == null) { 9254 throw new IllegalArgumentException("Unknown package: " + packageName); 9255 } 9256 } 9257 9258 synchronized (mInstallLock) { 9259 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9260 9261 // Whoever is calling forceDexOpt wants a compiled package. 9262 // Don't use profiles since that may cause compilation to be skipped. 9263 final int res = performDexOptInternalWithDependenciesLI( 9264 pkg, 9265 new DexoptOptions(packageName, 9266 getDefaultCompilerFilter(), 9267 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE)); 9268 9269 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9270 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9271 throw new IllegalStateException("Failed to dexopt: " + res); 9272 } 9273 } 9274 } 9275 9276 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9277 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9278 Slog.w(TAG, "Unable to update from " + oldPkg.name 9279 + " to " + newPkg.packageName 9280 + ": old package not in system partition"); 9281 return false; 9282 } else if (mPackages.get(oldPkg.name) != null) { 9283 Slog.w(TAG, "Unable to update from " + oldPkg.name 9284 + " to " + newPkg.packageName 9285 + ": old package still exists"); 9286 return false; 9287 } 9288 return true; 9289 } 9290 9291 void removeCodePathLI(File codePath) { 9292 if (codePath.isDirectory()) { 9293 try { 9294 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9295 } catch (InstallerException e) { 9296 Slog.w(TAG, "Failed to remove code path", e); 9297 } 9298 } else { 9299 codePath.delete(); 9300 } 9301 } 9302 9303 private int[] resolveUserIds(int userId) { 9304 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9305 } 9306 9307 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9308 if (pkg == null) { 9309 Slog.wtf(TAG, "Package was null!", new Throwable()); 9310 return; 9311 } 9312 clearAppDataLeafLIF(pkg, userId, flags); 9313 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9314 for (int i = 0; i < childCount; i++) { 9315 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9316 } 9317 } 9318 9319 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9320 final PackageSetting ps; 9321 synchronized (mPackages) { 9322 ps = mSettings.mPackages.get(pkg.packageName); 9323 } 9324 for (int realUserId : resolveUserIds(userId)) { 9325 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9326 try { 9327 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9328 ceDataInode); 9329 } catch (InstallerException e) { 9330 Slog.w(TAG, String.valueOf(e)); 9331 } 9332 } 9333 } 9334 9335 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9336 if (pkg == null) { 9337 Slog.wtf(TAG, "Package was null!", new Throwable()); 9338 return; 9339 } 9340 destroyAppDataLeafLIF(pkg, userId, flags); 9341 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9342 for (int i = 0; i < childCount; i++) { 9343 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9344 } 9345 } 9346 9347 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9348 final PackageSetting ps; 9349 synchronized (mPackages) { 9350 ps = mSettings.mPackages.get(pkg.packageName); 9351 } 9352 for (int realUserId : resolveUserIds(userId)) { 9353 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9354 try { 9355 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9356 ceDataInode); 9357 } catch (InstallerException e) { 9358 Slog.w(TAG, String.valueOf(e)); 9359 } 9360 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9361 } 9362 } 9363 9364 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9365 if (pkg == null) { 9366 Slog.wtf(TAG, "Package was null!", new Throwable()); 9367 return; 9368 } 9369 destroyAppProfilesLeafLIF(pkg); 9370 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9371 for (int i = 0; i < childCount; i++) { 9372 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9373 } 9374 } 9375 9376 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9377 try { 9378 mInstaller.destroyAppProfiles(pkg.packageName); 9379 } catch (InstallerException e) { 9380 Slog.w(TAG, String.valueOf(e)); 9381 } 9382 } 9383 9384 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9385 if (pkg == null) { 9386 Slog.wtf(TAG, "Package was null!", new Throwable()); 9387 return; 9388 } 9389 clearAppProfilesLeafLIF(pkg); 9390 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9391 for (int i = 0; i < childCount; i++) { 9392 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 9393 } 9394 } 9395 9396 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 9397 try { 9398 mInstaller.clearAppProfiles(pkg.packageName); 9399 } catch (InstallerException e) { 9400 Slog.w(TAG, String.valueOf(e)); 9401 } 9402 } 9403 9404 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9405 long lastUpdateTime) { 9406 // Set parent install/update time 9407 PackageSetting ps = (PackageSetting) pkg.mExtras; 9408 if (ps != null) { 9409 ps.firstInstallTime = firstInstallTime; 9410 ps.lastUpdateTime = lastUpdateTime; 9411 } 9412 // Set children install/update time 9413 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9414 for (int i = 0; i < childCount; i++) { 9415 PackageParser.Package childPkg = pkg.childPackages.get(i); 9416 ps = (PackageSetting) childPkg.mExtras; 9417 if (ps != null) { 9418 ps.firstInstallTime = firstInstallTime; 9419 ps.lastUpdateTime = lastUpdateTime; 9420 } 9421 } 9422 } 9423 9424 private void addSharedLibraryLPr(Set<String> usesLibraryFiles, 9425 SharedLibraryEntry file, 9426 PackageParser.Package changingLib) { 9427 if (file.path != null) { 9428 usesLibraryFiles.add(file.path); 9429 return; 9430 } 9431 PackageParser.Package p = mPackages.get(file.apk); 9432 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9433 // If we are doing this while in the middle of updating a library apk, 9434 // then we need to make sure to use that new apk for determining the 9435 // dependencies here. (We haven't yet finished committing the new apk 9436 // to the package manager state.) 9437 if (p == null || p.packageName.equals(changingLib.packageName)) { 9438 p = changingLib; 9439 } 9440 } 9441 if (p != null) { 9442 usesLibraryFiles.addAll(p.getAllCodePaths()); 9443 if (p.usesLibraryFiles != null) { 9444 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 9445 } 9446 } 9447 } 9448 9449 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9450 PackageParser.Package changingLib) throws PackageManagerException { 9451 if (pkg == null) { 9452 return; 9453 } 9454 // The collection used here must maintain the order of addition (so 9455 // that libraries are searched in the correct order) and must have no 9456 // duplicates. 9457 Set<String> usesLibraryFiles = null; 9458 if (pkg.usesLibraries != null) { 9459 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9460 null, null, pkg.packageName, changingLib, true, 9461 pkg.applicationInfo.targetSdkVersion, null); 9462 } 9463 if (pkg.usesStaticLibraries != null) { 9464 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9465 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9466 pkg.packageName, changingLib, true, 9467 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9468 } 9469 if (pkg.usesOptionalLibraries != null) { 9470 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9471 null, null, pkg.packageName, changingLib, false, 9472 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9473 } 9474 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9475 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9476 } else { 9477 pkg.usesLibraryFiles = null; 9478 } 9479 } 9480 9481 private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9482 @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests, 9483 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9484 boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries) 9485 throws PackageManagerException { 9486 final int libCount = requestedLibraries.size(); 9487 for (int i = 0; i < libCount; i++) { 9488 final String libName = requestedLibraries.get(i); 9489 final long libVersion = requiredVersions != null ? requiredVersions[i] 9490 : SharedLibraryInfo.VERSION_UNDEFINED; 9491 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9492 if (libEntry == null) { 9493 if (required) { 9494 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9495 "Package " + packageName + " requires unavailable shared library " 9496 + libName + "; failing!"); 9497 } else if (DEBUG_SHARED_LIBRARIES) { 9498 Slog.i(TAG, "Package " + packageName 9499 + " desires unavailable shared library " 9500 + libName + "; ignoring!"); 9501 } 9502 } else { 9503 if (requiredVersions != null && requiredCertDigests != null) { 9504 if (libEntry.info.getLongVersion() != requiredVersions[i]) { 9505 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9506 "Package " + packageName + " requires unavailable static shared" 9507 + " library " + libName + " version " 9508 + libEntry.info.getLongVersion() + "; failing!"); 9509 } 9510 9511 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9512 if (libPkg == null) { 9513 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9514 "Package " + packageName + " requires unavailable static shared" 9515 + " library; failing!"); 9516 } 9517 9518 final String[] expectedCertDigests = requiredCertDigests[i]; 9519 // For apps targeting O MR1 we require explicit enumeration of all certs. 9520 final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O) 9521 ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures) 9522 : PackageUtils.computeSignaturesSha256Digests( 9523 new Signature[]{libPkg.mSignatures[0]}); 9524 9525 // Take a shortcut if sizes don't match. Note that if an app doesn't 9526 // target O we don't parse the "additional-certificate" tags similarly 9527 // how we only consider all certs only for apps targeting O (see above). 9528 // Therefore, the size check is safe to make. 9529 if (expectedCertDigests.length != libCertDigests.length) { 9530 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9531 "Package " + packageName + " requires differently signed" + 9532 " static shared library; failing!"); 9533 } 9534 9535 // Use a predictable order as signature order may vary 9536 Arrays.sort(libCertDigests); 9537 Arrays.sort(expectedCertDigests); 9538 9539 final int certCount = libCertDigests.length; 9540 for (int j = 0; j < certCount; j++) { 9541 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) { 9542 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9543 "Package " + packageName + " requires differently signed" + 9544 " static shared library; failing!"); 9545 } 9546 } 9547 } 9548 9549 if (outUsedLibraries == null) { 9550 // Use LinkedHashSet to preserve the order of files added to 9551 // usesLibraryFiles while eliminating duplicates. 9552 outUsedLibraries = new LinkedHashSet<>(); 9553 } 9554 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9555 } 9556 } 9557 return outUsedLibraries; 9558 } 9559 9560 private static boolean hasString(List<String> list, List<String> which) { 9561 if (list == null) { 9562 return false; 9563 } 9564 for (int i=list.size()-1; i>=0; i--) { 9565 for (int j=which.size()-1; j>=0; j--) { 9566 if (which.get(j).equals(list.get(i))) { 9567 return true; 9568 } 9569 } 9570 } 9571 return false; 9572 } 9573 9574 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9575 PackageParser.Package changingPkg) { 9576 ArrayList<PackageParser.Package> res = null; 9577 for (PackageParser.Package pkg : mPackages.values()) { 9578 if (changingPkg != null 9579 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9580 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9581 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9582 changingPkg.staticSharedLibName)) { 9583 return null; 9584 } 9585 if (res == null) { 9586 res = new ArrayList<>(); 9587 } 9588 res.add(pkg); 9589 try { 9590 updateSharedLibrariesLPr(pkg, changingPkg); 9591 } catch (PackageManagerException e) { 9592 // If a system app update or an app and a required lib missing we 9593 // delete the package and for updated system apps keep the data as 9594 // it is better for the user to reinstall than to be in an limbo 9595 // state. Also libs disappearing under an app should never happen 9596 // - just in case. 9597 if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) { 9598 final int flags = pkg.isUpdatedSystemApp() 9599 ? PackageManager.DELETE_KEEP_DATA : 0; 9600 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9601 flags , null, true, null); 9602 } 9603 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9604 } 9605 } 9606 return res; 9607 } 9608 9609 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9610 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9611 @Nullable UserHandle user) throws PackageManagerException { 9612 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9613 // If the package has children and this is the first dive in the function 9614 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9615 // whether all packages (parent and children) would be successfully scanned 9616 // before the actual scan since scanning mutates internal state and we want 9617 // to atomically install the package and its children. 9618 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9619 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9620 scanFlags |= SCAN_CHECK_ONLY; 9621 } 9622 } else { 9623 scanFlags &= ~SCAN_CHECK_ONLY; 9624 } 9625 9626 final PackageParser.Package scannedPkg; 9627 try { 9628 // Scan the parent 9629 scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user); 9630 // Scan the children 9631 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9632 for (int i = 0; i < childCount; i++) { 9633 PackageParser.Package childPkg = pkg.childPackages.get(i); 9634 scanPackageNewLI(childPkg, parseFlags, 9635 scanFlags, currentTime, user); 9636 } 9637 } finally { 9638 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9639 } 9640 9641 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9642 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 9643 } 9644 9645 return scannedPkg; 9646 } 9647 9648 /** The result of a package scan. */ 9649 private static class ScanResult { 9650 /** Whether or not the package scan was successful */ 9651 public final boolean success; 9652 /** 9653 * The final package settings. This may be the same object passed in 9654 * the {@link ScanRequest}, but, with modified values. 9655 */ 9656 @Nullable public final PackageSetting pkgSetting; 9657 /** ABI code paths that have changed in the package scan */ 9658 @Nullable public final List<String> changedAbiCodePath; 9659 public ScanResult( 9660 boolean success, 9661 @Nullable PackageSetting pkgSetting, 9662 @Nullable List<String> changedAbiCodePath) { 9663 this.success = success; 9664 this.pkgSetting = pkgSetting; 9665 this.changedAbiCodePath = changedAbiCodePath; 9666 } 9667 } 9668 9669 /** A package to be scanned */ 9670 private static class ScanRequest { 9671 /** The parsed package */ 9672 @NonNull public final PackageParser.Package pkg; 9673 /** Shared user settings, if the package has a shared user */ 9674 @Nullable public final SharedUserSetting sharedUserSetting; 9675 /** 9676 * Package settings of the currently installed version. 9677 * <p><em>IMPORTANT:</em> The contents of this object may be modified 9678 * during scan. 9679 */ 9680 @Nullable public final PackageSetting pkgSetting; 9681 /** A copy of the settings for the currently installed version */ 9682 @Nullable public final PackageSetting oldPkgSetting; 9683 /** Package settings for the disabled version on the /system partition */ 9684 @Nullable public final PackageSetting disabledPkgSetting; 9685 /** Package settings for the installed version under its original package name */ 9686 @Nullable public final PackageSetting originalPkgSetting; 9687 /** The real package name of a renamed application */ 9688 @Nullable public final String realPkgName; 9689 public final @ParseFlags int parseFlags; 9690 public final @ScanFlags int scanFlags; 9691 /** The user for which the package is being scanned */ 9692 @Nullable public final UserHandle user; 9693 /** Whether or not the platform package is being scanned */ 9694 public final boolean isPlatformPackage; 9695 public ScanRequest( 9696 @NonNull PackageParser.Package pkg, 9697 @Nullable SharedUserSetting sharedUserSetting, 9698 @Nullable PackageSetting pkgSetting, 9699 @Nullable PackageSetting disabledPkgSetting, 9700 @Nullable PackageSetting originalPkgSetting, 9701 @Nullable String realPkgName, 9702 @ParseFlags int parseFlags, 9703 @ScanFlags int scanFlags, 9704 boolean isPlatformPackage, 9705 @Nullable UserHandle user) { 9706 this.pkg = pkg; 9707 this.pkgSetting = pkgSetting; 9708 this.sharedUserSetting = sharedUserSetting; 9709 this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting); 9710 this.disabledPkgSetting = disabledPkgSetting; 9711 this.originalPkgSetting = originalPkgSetting; 9712 this.realPkgName = realPkgName; 9713 this.parseFlags = parseFlags; 9714 this.scanFlags = scanFlags; 9715 this.isPlatformPackage = isPlatformPackage; 9716 this.user = user; 9717 } 9718 } 9719 9720 @GuardedBy("mInstallLock") 9721 private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg, 9722 final @ParseFlags int parseFlags, final @ScanFlags int scanFlags, long currentTime, 9723 @Nullable UserHandle user) throws PackageManagerException { 9724 9725 final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9726 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 9727 if (realPkgName != null) { 9728 ensurePackageRenamed(pkg, renamedPkgName); 9729 } 9730 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 9731 final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9732 final PackageSetting disabledPkgSetting = 9733 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9734 9735 if (mTransferedPackages.contains(pkg.packageName)) { 9736 Slog.w(TAG, "Package " + pkg.packageName 9737 + " was transferred to another, but its .apk remains"); 9738 } 9739 9740 synchronized (mPackages) { 9741 applyPolicy(pkg, parseFlags, scanFlags); 9742 assertPackageIsValid(pkg, parseFlags, scanFlags); 9743 9744 SharedUserSetting sharedUserSetting = null; 9745 if (pkg.mSharedUserId != null) { 9746 // SIDE EFFECTS; may potentially allocate a new shared user 9747 sharedUserSetting = mSettings.getSharedUserLPw( 9748 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9749 if (DEBUG_PACKAGE_SCANNING) { 9750 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 9751 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 9752 + " (uid=" + sharedUserSetting.userId + "):" 9753 + " packages=" + sharedUserSetting.packages); 9754 } 9755 } 9756 9757 boolean scanSucceeded = false; 9758 try { 9759 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting, 9760 disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags, 9761 (pkg == mPlatformPackage), user); 9762 final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime); 9763 if (result.success) { 9764 commitScanResultsLocked(request, result); 9765 } 9766 scanSucceeded = true; 9767 } finally { 9768 if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9769 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9770 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9771 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9772 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9773 } 9774 } 9775 } 9776 return pkg; 9777 } 9778 9779 /** 9780 * Commits the package scan and modifies system state. 9781 * <p><em>WARNING:</em> The method may throw an excpetion in the middle 9782 * of committing the package, leaving the system in an inconsistent state. 9783 * This needs to be fixed so, once we get to this point, no errors are 9784 * possible and the system is not left in an inconsistent state. 9785 */ 9786 @GuardedBy("mPackages") 9787 private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result) 9788 throws PackageManagerException { 9789 final PackageParser.Package pkg = request.pkg; 9790 final @ParseFlags int parseFlags = request.parseFlags; 9791 final @ScanFlags int scanFlags = request.scanFlags; 9792 final PackageSetting oldPkgSetting = request.oldPkgSetting; 9793 final PackageSetting originalPkgSetting = request.originalPkgSetting; 9794 final UserHandle user = request.user; 9795 final String realPkgName = request.realPkgName; 9796 final PackageSetting pkgSetting = result.pkgSetting; 9797 final List<String> changedAbiCodePath = result.changedAbiCodePath; 9798 final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting); 9799 9800 if (newPkgSettingCreated) { 9801 if (originalPkgSetting != null) { 9802 mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name); 9803 } 9804 // THROWS: when we can't allocate a user id. add call to check if there's 9805 // enough space to ensure we won't throw; otherwise, don't modify state 9806 mSettings.addUserToSettingLPw(pkgSetting); 9807 9808 if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) { 9809 mTransferedPackages.add(originalPkgSetting.name); 9810 } 9811 } 9812 // TODO(toddke): Consider a method specifically for modifying the Package object 9813 // post scan; or, moving this stuff out of the Package object since it has nothing 9814 // to do with the package on disk. 9815 // We need to have this here because addUserToSettingLPw() is sometimes responsible 9816 // for creating the application ID. If we did this earlier, we would be saving the 9817 // correct ID. 9818 pkg.applicationInfo.uid = pkgSetting.appId; 9819 9820 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9821 9822 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) { 9823 mTransferedPackages.add(pkg.packageName); 9824 } 9825 9826 // THROWS: when requested libraries that can't be found. it only changes 9827 // the state of the passed in pkg object, so, move to the top of the method 9828 // and allow it to abort 9829 if ((scanFlags & SCAN_BOOTING) == 0 9830 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9831 // Check all shared libraries and map to their actual file path. 9832 // We only do this here for apps not on a system dir, because those 9833 // are the only ones that can fail an install due to this. We 9834 // will take care of the system apps by updating all of their 9835 // library paths after the scan is done. Also during the initial 9836 // scan don't update any libs as we do this wholesale after all 9837 // apps are scanned to avoid dependency based scanning. 9838 updateSharedLibrariesLPr(pkg, null); 9839 } 9840 9841 // All versions of a static shared library are referenced with the same 9842 // package name. Internally, we use a synthetic package name to allow 9843 // multiple versions of the same shared library to be installed. So, 9844 // we need to generate the synthetic package name of the latest shared 9845 // library in order to compare signatures. 9846 PackageSetting signatureCheckPs = pkgSetting; 9847 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9848 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9849 if (libraryEntry != null) { 9850 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9851 } 9852 } 9853 9854 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 9855 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 9856 if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 9857 // We just determined the app is signed correctly, so bring 9858 // over the latest parsed certs. 9859 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9860 } else { 9861 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9862 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9863 "Package " + pkg.packageName + " upgrade keys do not match the " 9864 + "previously installed version"); 9865 } else { 9866 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9867 String msg = "System package " + pkg.packageName 9868 + " signature changed; retaining data."; 9869 reportSettingsProblem(Log.WARN, msg); 9870 } 9871 } 9872 } else { 9873 try { 9874 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 9875 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 9876 final boolean compatMatch = verifySignatures(signatureCheckPs, pkg.mSignatures, 9877 compareCompat, compareRecover); 9878 // The new KeySets will be re-added later in the scanning process. 9879 if (compatMatch) { 9880 synchronized (mPackages) { 9881 ksms.removeAppKeySetDataLPw(pkg.packageName); 9882 } 9883 } 9884 // We just determined the app is signed correctly, so bring 9885 // over the latest parsed certs. 9886 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9887 } catch (PackageManagerException e) { 9888 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9889 throw e; 9890 } 9891 // The signature has changed, but this package is in the system 9892 // image... let's recover! 9893 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9894 // However... if this package is part of a shared user, but it 9895 // doesn't match the signature of the shared user, let's fail. 9896 // What this means is that you can't change the signatures 9897 // associated with an overall shared user, which doesn't seem all 9898 // that unreasonable. 9899 if (signatureCheckPs.sharedUser != null) { 9900 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9901 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9902 throw new PackageManagerException( 9903 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9904 "Signature mismatch for shared user: " 9905 + pkgSetting.sharedUser); 9906 } 9907 } 9908 // File a report about this. 9909 String msg = "System package " + pkg.packageName 9910 + " signature changed; retaining data."; 9911 reportSettingsProblem(Log.WARN, msg); 9912 } 9913 } 9914 9915 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9916 // This package wants to adopt ownership of permissions from 9917 // another package. 9918 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9919 final String origName = pkg.mAdoptPermissions.get(i); 9920 final PackageSetting orig = mSettings.getPackageLPr(origName); 9921 if (orig != null) { 9922 if (verifyPackageUpdateLPr(orig, pkg)) { 9923 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9924 + pkg.packageName); 9925 mSettings.mPermissions.transferPermissions(origName, pkg.packageName); 9926 } 9927 } 9928 } 9929 } 9930 9931 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 9932 for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) { 9933 final String codePathString = changedAbiCodePath.get(i); 9934 try { 9935 mInstaller.rmdex(codePathString, 9936 getDexCodeInstructionSet(getPreferredInstructionSet())); 9937 } catch (InstallerException ignored) { 9938 } 9939 } 9940 } 9941 9942 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9943 if (oldPkgSetting != null) { 9944 synchronized (mPackages) { 9945 mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting); 9946 } 9947 } 9948 } else { 9949 final int userId = user == null ? 0 : user.getIdentifier(); 9950 // Modify state for the given package setting 9951 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9952 (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9953 if (pkgSetting.getInstantApp(userId)) { 9954 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9955 } 9956 } 9957 } 9958 9959 /** 9960 * Returns the "real" name of the package. 9961 * <p>This may differ from the package's actual name if the application has already 9962 * been installed under one of this package's original names. 9963 */ 9964 private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg, 9965 @Nullable String renamedPkgName) { 9966 if (pkg.mOriginalPackages == null || !pkg.mOriginalPackages.contains(renamedPkgName)) { 9967 return null; 9968 } 9969 return pkg.mRealPackage; 9970 } 9971 9972 /** 9973 * Returns the original package setting. 9974 * <p>A package can migrate its name during an update. In this scenario, a package 9975 * designates a set of names that it considers as one of its original names. 9976 * <p>An original package must be signed identically and it must have the same 9977 * shared user [if any]. 9978 */ 9979 @GuardedBy("mPackages") 9980 private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg, 9981 @Nullable String renamedPkgName) { 9982 if (pkg.mOriginalPackages == null || pkg.mOriginalPackages.contains(renamedPkgName)) { 9983 return null; 9984 } 9985 for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) { 9986 final PackageSetting originalPs = 9987 mSettings.getPackageLPr(pkg.mOriginalPackages.get(i)); 9988 if (originalPs != null) { 9989 // the package is already installed under its original name... 9990 // but, should we use it? 9991 if (!verifyPackageUpdateLPr(originalPs, pkg)) { 9992 // the new package is incompatible with the original 9993 continue; 9994 } else if (originalPs.sharedUser != null) { 9995 if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) { 9996 // the shared user id is incompatible with the original 9997 Slog.w(TAG, "Unable to migrate data from " + originalPs.name 9998 + " to " + pkg.packageName + ": old uid " 9999 + originalPs.sharedUser.name 10000 + " differs from " + pkg.mSharedUserId); 10001 continue; 10002 } 10003 // TODO: Add case when shared user id is added [b/28144775] 10004 } else { 10005 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 10006 + pkg.packageName + " to old name " + originalPs.name); 10007 } 10008 return originalPs; 10009 } 10010 } 10011 return null; 10012 } 10013 10014 /** 10015 * Renames the package if it was installed under a different name. 10016 * <p>When we've already installed the package under an original name, update 10017 * the new package so we can continue to have the old name. 10018 */ 10019 private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg, 10020 @NonNull String renamedPackageName) { 10021 if (pkg.mOriginalPackages == null 10022 || !pkg.mOriginalPackages.contains(renamedPackageName) 10023 || pkg.packageName.equals(renamedPackageName)) { 10024 return; 10025 } 10026 pkg.setPackageName(renamedPackageName); 10027 } 10028 10029 /** 10030 * Just scans the package without any side effects. 10031 * <p>Not entirely true at the moment. There is still one side effect -- this 10032 * method potentially modifies a live {@link PackageSetting} object representing 10033 * the package being scanned. This will be resolved in the future. 10034 * 10035 * @param request Information about the package to be scanned 10036 * @param isUnderFactoryTest Whether or not the device is under factory test 10037 * @param currentTime The current time, in millis 10038 * @return The results of the scan 10039 */ 10040 @GuardedBy("mInstallLock") 10041 private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request, 10042 boolean isUnderFactoryTest, long currentTime) 10043 throws PackageManagerException { 10044 final PackageParser.Package pkg = request.pkg; 10045 PackageSetting pkgSetting = request.pkgSetting; 10046 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10047 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10048 final @ParseFlags int parseFlags = request.parseFlags; 10049 final @ScanFlags int scanFlags = request.scanFlags; 10050 final String realPkgName = request.realPkgName; 10051 final SharedUserSetting sharedUserSetting = request.sharedUserSetting; 10052 final UserHandle user = request.user; 10053 final boolean isPlatformPackage = request.isPlatformPackage; 10054 10055 List<String> changedAbiCodePath = null; 10056 10057 if (DEBUG_PACKAGE_SCANNING) { 10058 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10059 Log.d(TAG, "Scanning package " + pkg.packageName); 10060 } 10061 10062 if (Build.IS_DEBUGGABLE && 10063 pkg.isPrivileged() && 10064 !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) { 10065 PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg); 10066 } 10067 10068 // Initialize package source and resource directories 10069 final File scanFile = new File(pkg.codePath); 10070 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 10071 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 10072 10073 // We keep references to the derived CPU Abis from settings in oder to reuse 10074 // them in the case where we're not upgrading or booting for the first time. 10075 String primaryCpuAbiFromSettings = null; 10076 String secondaryCpuAbiFromSettings = null; 10077 boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0; 10078 10079 if (!needToDeriveAbi) { 10080 if (pkgSetting != null) { 10081 primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString; 10082 secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString; 10083 } else { 10084 // Re-scanning a system package after uninstalling updates; need to derive ABI 10085 needToDeriveAbi = true; 10086 } 10087 } 10088 10089 if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) { 10090 PackageManagerService.reportSettingsProblem(Log.WARN, 10091 "Package " + pkg.packageName + " shared user changed from " 10092 + (pkgSetting.sharedUser != null 10093 ? pkgSetting.sharedUser.name : "<nothing>") 10094 + " to " 10095 + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>") 10096 + "; replacing with new"); 10097 pkgSetting = null; 10098 } 10099 10100 String[] usesStaticLibraries = null; 10101 if (pkg.usesStaticLibraries != null) { 10102 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 10103 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 10104 } 10105 10106 final boolean createNewPackage = (pkgSetting == null); 10107 if (createNewPackage) { 10108 final String parentPackageName = (pkg.parentPackage != null) 10109 ? pkg.parentPackage.packageName : null; 10110 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10111 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0; 10112 // REMOVE SharedUserSetting from method; update in a separate call 10113 pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting, 10114 disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile, 10115 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 10116 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10117 pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10118 user, true /*allowInstall*/, instantApp, virtualPreload, 10119 parentPackageName, pkg.getChildPackageNames(), 10120 UserManagerService.getInstance(), usesStaticLibraries, 10121 pkg.usesStaticLibrariesVersions); 10122 } else { 10123 // REMOVE SharedUserSetting from method; update in a separate call. 10124 // 10125 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 10126 // secondaryCpuAbi are not known at this point so we always update them 10127 // to null here, only to reset them at a later point. 10128 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting, 10129 destCodeFile, pkg.applicationInfo.nativeLibraryDir, 10130 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10131 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10132 pkg.getChildPackageNames(), UserManagerService.getInstance(), 10133 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 10134 } 10135 if (createNewPackage && originalPkgSetting != null) { 10136 // If we are first transitioning from an original package, 10137 // fix up the new package's name now. We need to do this after 10138 // looking up the package under its new name, so getPackageLP 10139 // can take care of fiddling things correctly. 10140 pkg.setPackageName(originalPkgSetting.name); 10141 10142 // File a report about this. 10143 String msg = "New package " + pkgSetting.realName 10144 + " renamed to replace old package " + pkgSetting.name; 10145 reportSettingsProblem(Log.WARN, msg); 10146 } 10147 10148 if (disabledPkgSetting != null) { 10149 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10150 } 10151 10152 SELinuxMMAC.assignSeInfoValue(pkg); 10153 10154 pkg.mExtras = pkgSetting; 10155 pkg.applicationInfo.processName = fixProcessName( 10156 pkg.applicationInfo.packageName, 10157 pkg.applicationInfo.processName); 10158 10159 if (!isPlatformPackage) { 10160 // Get all of our default paths setup 10161 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 10162 } 10163 10164 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 10165 10166 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 10167 if (needToDeriveAbi) { 10168 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 10169 final boolean extractNativeLibs = !pkg.isLibrary(); 10170 derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs); 10171 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10172 10173 // Some system apps still use directory structure for native libraries 10174 // in which case we might end up not detecting abi solely based on apk 10175 // structure. Try to detect abi based on directory structure. 10176 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 10177 pkg.applicationInfo.primaryCpuAbi == null) { 10178 setBundledAppAbisAndRoots(pkg, pkgSetting); 10179 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10180 } 10181 } else { 10182 // This is not a first boot or an upgrade, don't bother deriving the 10183 // ABI during the scan. Instead, trust the value that was stored in the 10184 // package setting. 10185 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 10186 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 10187 10188 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10189 10190 if (DEBUG_ABI_SELECTION) { 10191 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 10192 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 10193 pkg.applicationInfo.secondaryCpuAbi); 10194 } 10195 } 10196 } else { 10197 if ((scanFlags & SCAN_MOVE) != 0) { 10198 // We haven't run dex-opt for this move (since we've moved the compiled output too) 10199 // but we already have this packages package info in the PackageSetting. We just 10200 // use that and derive the native library path based on the new codepath. 10201 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 10202 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 10203 } 10204 10205 // Set native library paths again. For moves, the path will be updated based on the 10206 // ABIs we've determined above. For non-moves, the path will be updated based on the 10207 // ABIs we determined during compilation, but the path will depend on the final 10208 // package path (after the rename away from the stage path). 10209 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10210 } 10211 10212 // This is a special case for the "system" package, where the ABI is 10213 // dictated by the zygote configuration (and init.rc). We should keep track 10214 // of this ABI so that we can deal with "normal" applications that run under 10215 // the same UID correctly. 10216 if (isPlatformPackage) { 10217 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 10218 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 10219 } 10220 10221 // If there's a mismatch between the abi-override in the package setting 10222 // and the abiOverride specified for the install. Warn about this because we 10223 // would've already compiled the app without taking the package setting into 10224 // account. 10225 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 10226 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 10227 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 10228 " for package " + pkg.packageName); 10229 } 10230 } 10231 10232 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10233 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10234 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 10235 10236 // Copy the derived override back to the parsed package, so that we can 10237 // update the package settings accordingly. 10238 pkg.cpuAbiOverride = cpuAbiOverride; 10239 10240 if (DEBUG_ABI_SELECTION) { 10241 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 10242 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 10243 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 10244 } 10245 10246 // Push the derived path down into PackageSettings so we know what to 10247 // clean up at uninstall time. 10248 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 10249 10250 if (DEBUG_ABI_SELECTION) { 10251 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 10252 " primary=" + pkg.applicationInfo.primaryCpuAbi + 10253 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 10254 } 10255 10256 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 10257 // We don't do this here during boot because we can do it all 10258 // at once after scanning all existing packages. 10259 // 10260 // We also do this *before* we perform dexopt on this package, so that 10261 // we can avoid redundant dexopts, and also to make sure we've got the 10262 // code and package path correct. 10263 changedAbiCodePath = 10264 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 10265 } 10266 10267 if (isUnderFactoryTest && pkg.requestedPermissions.contains( 10268 android.Manifest.permission.FACTORY_TEST)) { 10269 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 10270 } 10271 10272 if (isSystemApp(pkg)) { 10273 pkgSetting.isOrphaned = true; 10274 } 10275 10276 // Take care of first install / last update times. 10277 final long scanFileTime = getLastModifiedTime(pkg); 10278 if (currentTime != 0) { 10279 if (pkgSetting.firstInstallTime == 0) { 10280 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 10281 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 10282 pkgSetting.lastUpdateTime = currentTime; 10283 } 10284 } else if (pkgSetting.firstInstallTime == 0) { 10285 // We need *something*. Take time time stamp of the file. 10286 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 10287 } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 10288 if (scanFileTime != pkgSetting.timeStamp) { 10289 // A package on the system image has changed; consider this 10290 // to be an update. 10291 pkgSetting.lastUpdateTime = scanFileTime; 10292 } 10293 } 10294 pkgSetting.setTimeStamp(scanFileTime); 10295 10296 return new ScanResult(true, pkgSetting, changedAbiCodePath); 10297 } 10298 10299 /** 10300 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 10301 */ 10302 private static boolean apkHasCode(String fileName) { 10303 StrictJarFile jarFile = null; 10304 try { 10305 jarFile = new StrictJarFile(fileName, 10306 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 10307 return jarFile.findEntry("classes.dex") != null; 10308 } catch (IOException ignore) { 10309 } finally { 10310 try { 10311 if (jarFile != null) { 10312 jarFile.close(); 10313 } 10314 } catch (IOException ignore) {} 10315 } 10316 return false; 10317 } 10318 10319 /** 10320 * Enforces code policy for the package. This ensures that if an APK has 10321 * declared hasCode="true" in its manifest that the APK actually contains 10322 * code. 10323 * 10324 * @throws PackageManagerException If bytecode could not be found when it should exist 10325 */ 10326 private static void assertCodePolicy(PackageParser.Package pkg) 10327 throws PackageManagerException { 10328 final boolean shouldHaveCode = 10329 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 10330 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 10331 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10332 "Package " + pkg.baseCodePath + " code is missing"); 10333 } 10334 10335 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 10336 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 10337 final boolean splitShouldHaveCode = 10338 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 10339 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 10340 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10341 "Package " + pkg.splitCodePaths[i] + " code is missing"); 10342 } 10343 } 10344 } 10345 } 10346 10347 /** 10348 * Applies policy to the parsed package based upon the given policy flags. 10349 * Ensures the package is in a good state. 10350 * <p> 10351 * Implementation detail: This method must NOT have any side effect. It would 10352 * ideally be static, but, it requires locks to read system state. 10353 */ 10354 private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10355 final @ScanFlags int scanFlags) { 10356 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 10357 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 10358 if (pkg.applicationInfo.isDirectBootAware()) { 10359 // we're direct boot aware; set for all components 10360 for (PackageParser.Service s : pkg.services) { 10361 s.info.encryptionAware = s.info.directBootAware = true; 10362 } 10363 for (PackageParser.Provider p : pkg.providers) { 10364 p.info.encryptionAware = p.info.directBootAware = true; 10365 } 10366 for (PackageParser.Activity a : pkg.activities) { 10367 a.info.encryptionAware = a.info.directBootAware = true; 10368 } 10369 for (PackageParser.Activity r : pkg.receivers) { 10370 r.info.encryptionAware = r.info.directBootAware = true; 10371 } 10372 } 10373 if (compressedFileExists(pkg.codePath)) { 10374 pkg.isStub = true; 10375 } 10376 } else { 10377 // non system apps can't be flagged as core 10378 pkg.coreApp = false; 10379 // clear flags not applicable to regular apps 10380 pkg.applicationInfo.flags &= 10381 ~ApplicationInfo.FLAG_PERSISTENT; 10382 pkg.applicationInfo.privateFlags &= 10383 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10384 pkg.applicationInfo.privateFlags &= 10385 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10386 // clear protected broadcasts 10387 pkg.protectedBroadcasts = null; 10388 // cap permission priorities 10389 if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) { 10390 for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) { 10391 pkg.permissionGroups.get(i).info.priority = 0; 10392 } 10393 } 10394 } 10395 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10396 // ignore export request for single user receivers 10397 if (pkg.receivers != null) { 10398 for (int i = pkg.receivers.size() - 1; i >= 0; --i) { 10399 final PackageParser.Activity receiver = pkg.receivers.get(i); 10400 if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 10401 receiver.info.exported = false; 10402 } 10403 } 10404 } 10405 // ignore export request for single user services 10406 if (pkg.services != null) { 10407 for (int i = pkg.services.size() - 1; i >= 0; --i) { 10408 final PackageParser.Service service = pkg.services.get(i); 10409 if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 10410 service.info.exported = false; 10411 } 10412 } 10413 } 10414 // ignore export request for single user providers 10415 if (pkg.providers != null) { 10416 for (int i = pkg.providers.size() - 1; i >= 0; --i) { 10417 final PackageParser.Provider provider = pkg.providers.get(i); 10418 if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) { 10419 provider.info.exported = false; 10420 } 10421 } 10422 } 10423 } 10424 pkg.mTrustedOverlay = (scanFlags & SCAN_TRUSTED_OVERLAY) != 0; 10425 10426 if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) { 10427 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10428 } 10429 10430 if ((scanFlags & SCAN_AS_OEM) != 0) { 10431 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 10432 } 10433 10434 if ((scanFlags & SCAN_AS_VENDOR) != 0) { 10435 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR; 10436 } 10437 10438 if (!isSystemApp(pkg)) { 10439 // Only system apps can use these features. 10440 pkg.mOriginalPackages = null; 10441 pkg.mRealPackage = null; 10442 pkg.mAdoptPermissions = null; 10443 } 10444 } 10445 10446 /** 10447 * Asserts the parsed package is valid according to the given policy. If the 10448 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10449 * <p> 10450 * Implementation detail: This method must NOT have any side effects. It would 10451 * ideally be static, but, it requires locks to read system state. 10452 * 10453 * @throws PackageManagerException If the package fails any of the validation checks 10454 */ 10455 private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10456 final @ScanFlags int scanFlags) 10457 throws PackageManagerException { 10458 if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10459 assertCodePolicy(pkg); 10460 } 10461 10462 if (pkg.applicationInfo.getCodePath() == null || 10463 pkg.applicationInfo.getResourcePath() == null) { 10464 // Bail out. The resource and code paths haven't been set. 10465 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10466 "Code and resource paths haven't been set correctly"); 10467 } 10468 10469 // Make sure we're not adding any bogus keyset info 10470 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10471 ksms.assertScannedPackageValid(pkg); 10472 10473 synchronized (mPackages) { 10474 // The special "android" package can only be defined once 10475 if (pkg.packageName.equals("android")) { 10476 if (mAndroidApplication != null) { 10477 Slog.w(TAG, "*************************************************"); 10478 Slog.w(TAG, "Core android package being redefined. Skipping."); 10479 Slog.w(TAG, " codePath=" + pkg.codePath); 10480 Slog.w(TAG, "*************************************************"); 10481 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10482 "Core android package being redefined. Skipping."); 10483 } 10484 } 10485 10486 // A package name must be unique; don't allow duplicates 10487 if (mPackages.containsKey(pkg.packageName)) { 10488 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10489 "Application package " + pkg.packageName 10490 + " already installed. Skipping duplicate."); 10491 } 10492 10493 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10494 // Static libs have a synthetic package name containing the version 10495 // but we still want the base name to be unique. 10496 if (mPackages.containsKey(pkg.manifestPackageName)) { 10497 throw new PackageManagerException( 10498 "Duplicate static shared lib provider package"); 10499 } 10500 10501 // Static shared libraries should have at least O target SDK 10502 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10503 throw new PackageManagerException( 10504 "Packages declaring static-shared libs must target O SDK or higher"); 10505 } 10506 10507 // Package declaring static a shared lib cannot be instant apps 10508 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10509 throw new PackageManagerException( 10510 "Packages declaring static-shared libs cannot be instant apps"); 10511 } 10512 10513 // Package declaring static a shared lib cannot be renamed since the package 10514 // name is synthetic and apps can't code around package manager internals. 10515 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10516 throw new PackageManagerException( 10517 "Packages declaring static-shared libs cannot be renamed"); 10518 } 10519 10520 // Package declaring static a shared lib cannot declare child packages 10521 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10522 throw new PackageManagerException( 10523 "Packages declaring static-shared libs cannot have child packages"); 10524 } 10525 10526 // Package declaring static a shared lib cannot declare dynamic libs 10527 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10528 throw new PackageManagerException( 10529 "Packages declaring static-shared libs cannot declare dynamic libs"); 10530 } 10531 10532 // Package declaring static a shared lib cannot declare shared users 10533 if (pkg.mSharedUserId != null) { 10534 throw new PackageManagerException( 10535 "Packages declaring static-shared libs cannot declare shared users"); 10536 } 10537 10538 // Static shared libs cannot declare activities 10539 if (!pkg.activities.isEmpty()) { 10540 throw new PackageManagerException( 10541 "Static shared libs cannot declare activities"); 10542 } 10543 10544 // Static shared libs cannot declare services 10545 if (!pkg.services.isEmpty()) { 10546 throw new PackageManagerException( 10547 "Static shared libs cannot declare services"); 10548 } 10549 10550 // Static shared libs cannot declare providers 10551 if (!pkg.providers.isEmpty()) { 10552 throw new PackageManagerException( 10553 "Static shared libs cannot declare content providers"); 10554 } 10555 10556 // Static shared libs cannot declare receivers 10557 if (!pkg.receivers.isEmpty()) { 10558 throw new PackageManagerException( 10559 "Static shared libs cannot declare broadcast receivers"); 10560 } 10561 10562 // Static shared libs cannot declare permission groups 10563 if (!pkg.permissionGroups.isEmpty()) { 10564 throw new PackageManagerException( 10565 "Static shared libs cannot declare permission groups"); 10566 } 10567 10568 // Static shared libs cannot declare permissions 10569 if (!pkg.permissions.isEmpty()) { 10570 throw new PackageManagerException( 10571 "Static shared libs cannot declare permissions"); 10572 } 10573 10574 // Static shared libs cannot declare protected broadcasts 10575 if (pkg.protectedBroadcasts != null) { 10576 throw new PackageManagerException( 10577 "Static shared libs cannot declare protected broadcasts"); 10578 } 10579 10580 // Static shared libs cannot be overlay targets 10581 if (pkg.mOverlayTarget != null) { 10582 throw new PackageManagerException( 10583 "Static shared libs cannot be overlay targets"); 10584 } 10585 10586 // The version codes must be ordered as lib versions 10587 long minVersionCode = Long.MIN_VALUE; 10588 long maxVersionCode = Long.MAX_VALUE; 10589 10590 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10591 pkg.staticSharedLibName); 10592 if (versionedLib != null) { 10593 final int versionCount = versionedLib.size(); 10594 for (int i = 0; i < versionCount; i++) { 10595 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10596 final long libVersionCode = libInfo.getDeclaringPackage() 10597 .getLongVersionCode(); 10598 if (libInfo.getLongVersion() < pkg.staticSharedLibVersion) { 10599 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10600 } else if (libInfo.getLongVersion() > pkg.staticSharedLibVersion) { 10601 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10602 } else { 10603 minVersionCode = maxVersionCode = libVersionCode; 10604 break; 10605 } 10606 } 10607 } 10608 if (pkg.getLongVersionCode() < minVersionCode 10609 || pkg.getLongVersionCode() > maxVersionCode) { 10610 throw new PackageManagerException("Static shared" 10611 + " lib version codes must be ordered as lib versions"); 10612 } 10613 } 10614 10615 // Only privileged apps and updated privileged apps can add child packages. 10616 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10617 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10618 throw new PackageManagerException("Only privileged apps can add child " 10619 + "packages. Ignoring package " + pkg.packageName); 10620 } 10621 final int childCount = pkg.childPackages.size(); 10622 for (int i = 0; i < childCount; i++) { 10623 PackageParser.Package childPkg = pkg.childPackages.get(i); 10624 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10625 childPkg.packageName)) { 10626 throw new PackageManagerException("Can't override child of " 10627 + "another disabled app. Ignoring package " + pkg.packageName); 10628 } 10629 } 10630 } 10631 10632 // If we're only installing presumed-existing packages, require that the 10633 // scanned APK is both already known and at the path previously established 10634 // for it. Previously unknown packages we pick up normally, but if we have an 10635 // a priori expectation about this package's install presence, enforce it. 10636 // With a singular exception for new system packages. When an OTA contains 10637 // a new system package, we allow the codepath to change from a system location 10638 // to the user-installed location. If we don't allow this change, any newer, 10639 // user-installed version of the application will be ignored. 10640 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10641 if (mExpectingBetter.containsKey(pkg.packageName)) { 10642 logCriticalInfo(Log.WARN, 10643 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10644 } else { 10645 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10646 if (known != null) { 10647 if (DEBUG_PACKAGE_SCANNING) { 10648 Log.d(TAG, "Examining " + pkg.codePath 10649 + " and requiring known paths " + known.codePathString 10650 + " & " + known.resourcePathString); 10651 } 10652 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10653 || !pkg.applicationInfo.getResourcePath().equals( 10654 known.resourcePathString)) { 10655 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10656 "Application package " + pkg.packageName 10657 + " found at " + pkg.applicationInfo.getCodePath() 10658 + " but expected at " + known.codePathString 10659 + "; ignoring."); 10660 } 10661 } else { 10662 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10663 "Application package " + pkg.packageName 10664 + " not found; ignoring."); 10665 } 10666 } 10667 } 10668 10669 // Verify that this new package doesn't have any content providers 10670 // that conflict with existing packages. Only do this if the 10671 // package isn't already installed, since we don't want to break 10672 // things that are installed. 10673 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 10674 final int N = pkg.providers.size(); 10675 int i; 10676 for (i=0; i<N; i++) { 10677 PackageParser.Provider p = pkg.providers.get(i); 10678 if (p.info.authority != null) { 10679 String names[] = p.info.authority.split(";"); 10680 for (int j = 0; j < names.length; j++) { 10681 if (mProvidersByAuthority.containsKey(names[j])) { 10682 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10683 final String otherPackageName = 10684 ((other != null && other.getComponentName() != null) ? 10685 other.getComponentName().getPackageName() : "?"); 10686 throw new PackageManagerException( 10687 INSTALL_FAILED_CONFLICTING_PROVIDER, 10688 "Can't install because provider name " + names[j] 10689 + " (in package " + pkg.applicationInfo.packageName 10690 + ") is already used by " + otherPackageName); 10691 } 10692 } 10693 } 10694 } 10695 } 10696 } 10697 } 10698 10699 private boolean addSharedLibraryLPw(String path, String apk, String name, long version, 10700 int type, String declaringPackageName, long declaringVersionCode) { 10701 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10702 if (versionedLib == null) { 10703 versionedLib = new LongSparseArray<>(); 10704 mSharedLibraries.put(name, versionedLib); 10705 if (type == SharedLibraryInfo.TYPE_STATIC) { 10706 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 10707 } 10708 } else if (versionedLib.indexOfKey(version) >= 0) { 10709 return false; 10710 } 10711 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 10712 version, type, declaringPackageName, declaringVersionCode); 10713 versionedLib.put(version, libEntry); 10714 return true; 10715 } 10716 10717 private boolean removeSharedLibraryLPw(String name, long version) { 10718 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10719 if (versionedLib == null) { 10720 return false; 10721 } 10722 final int libIdx = versionedLib.indexOfKey(version); 10723 if (libIdx < 0) { 10724 return false; 10725 } 10726 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 10727 versionedLib.remove(version); 10728 if (versionedLib.size() <= 0) { 10729 mSharedLibraries.remove(name); 10730 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 10731 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 10732 .getPackageName()); 10733 } 10734 } 10735 return true; 10736 } 10737 10738 /** 10739 * Adds a scanned package to the system. When this method is finished, the package will 10740 * be available for query, resolution, etc... 10741 */ 10742 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 10743 UserHandle user, final @ScanFlags int scanFlags, boolean chatty) { 10744 final String pkgName = pkg.packageName; 10745 if (mCustomResolverComponentName != null && 10746 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 10747 setUpCustomResolverActivity(pkg); 10748 } 10749 10750 if (pkg.packageName.equals("android")) { 10751 synchronized (mPackages) { 10752 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10753 // Set up information for our fall-back user intent resolution activity. 10754 mPlatformPackage = pkg; 10755 pkg.mVersionCode = mSdkVersion; 10756 pkg.mVersionCodeMajor = 0; 10757 mAndroidApplication = pkg.applicationInfo; 10758 if (!mResolverReplaced) { 10759 mResolveActivity.applicationInfo = mAndroidApplication; 10760 mResolveActivity.name = ResolverActivity.class.getName(); 10761 mResolveActivity.packageName = mAndroidApplication.packageName; 10762 mResolveActivity.processName = "system:ui"; 10763 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10764 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 10765 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 10766 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 10767 mResolveActivity.exported = true; 10768 mResolveActivity.enabled = true; 10769 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 10770 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 10771 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 10772 | ActivityInfo.CONFIG_SCREEN_LAYOUT 10773 | ActivityInfo.CONFIG_ORIENTATION 10774 | ActivityInfo.CONFIG_KEYBOARD 10775 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 10776 mResolveInfo.activityInfo = mResolveActivity; 10777 mResolveInfo.priority = 0; 10778 mResolveInfo.preferredOrder = 0; 10779 mResolveInfo.match = 0; 10780 mResolveComponentName = new ComponentName( 10781 mAndroidApplication.packageName, mResolveActivity.name); 10782 } 10783 } 10784 } 10785 } 10786 10787 ArrayList<PackageParser.Package> clientLibPkgs = null; 10788 // writer 10789 synchronized (mPackages) { 10790 boolean hasStaticSharedLibs = false; 10791 10792 // Any app can add new static shared libraries 10793 if (pkg.staticSharedLibName != null) { 10794 // Static shared libs don't allow renaming as they have synthetic package 10795 // names to allow install of multiple versions, so use name from manifest. 10796 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 10797 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 10798 pkg.manifestPackageName, pkg.getLongVersionCode())) { 10799 hasStaticSharedLibs = true; 10800 } else { 10801 Slog.w(TAG, "Package " + pkg.packageName + " library " 10802 + pkg.staticSharedLibName + " already exists; skipping"); 10803 } 10804 // Static shared libs cannot be updated once installed since they 10805 // use synthetic package name which includes the version code, so 10806 // not need to update other packages's shared lib dependencies. 10807 } 10808 10809 if (!hasStaticSharedLibs 10810 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10811 // Only system apps can add new dynamic shared libraries. 10812 if (pkg.libraryNames != null) { 10813 for (int i = 0; i < pkg.libraryNames.size(); i++) { 10814 String name = pkg.libraryNames.get(i); 10815 boolean allowed = false; 10816 if (pkg.isUpdatedSystemApp()) { 10817 // New library entries can only be added through the 10818 // system image. This is important to get rid of a lot 10819 // of nasty edge cases: for example if we allowed a non- 10820 // system update of the app to add a library, then uninstalling 10821 // the update would make the library go away, and assumptions 10822 // we made such as through app install filtering would now 10823 // have allowed apps on the device which aren't compatible 10824 // with it. Better to just have the restriction here, be 10825 // conservative, and create many fewer cases that can negatively 10826 // impact the user experience. 10827 final PackageSetting sysPs = mSettings 10828 .getDisabledSystemPkgLPr(pkg.packageName); 10829 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 10830 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 10831 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 10832 allowed = true; 10833 break; 10834 } 10835 } 10836 } 10837 } else { 10838 allowed = true; 10839 } 10840 if (allowed) { 10841 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10842 SharedLibraryInfo.VERSION_UNDEFINED, 10843 SharedLibraryInfo.TYPE_DYNAMIC, 10844 pkg.packageName, pkg.getLongVersionCode())) { 10845 Slog.w(TAG, "Package " + pkg.packageName + " library " 10846 + name + " already exists; skipping"); 10847 } 10848 } else { 10849 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10850 + name + " that is not declared on system image; skipping"); 10851 } 10852 } 10853 10854 if ((scanFlags & SCAN_BOOTING) == 0) { 10855 // If we are not booting, we need to update any applications 10856 // that are clients of our shared library. If we are booting, 10857 // this will all be done once the scan is complete. 10858 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10859 } 10860 } 10861 } 10862 } 10863 10864 if ((scanFlags & SCAN_BOOTING) != 0) { 10865 // No apps can run during boot scan, so they don't need to be frozen 10866 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10867 // Caller asked to not kill app, so it's probably not frozen 10868 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10869 // Caller asked us to ignore frozen check for some reason; they 10870 // probably didn't know the package name 10871 } else { 10872 // We're doing major surgery on this package, so it better be frozen 10873 // right now to keep it from launching 10874 checkPackageFrozen(pkgName); 10875 } 10876 10877 // Also need to kill any apps that are dependent on the library. 10878 if (clientLibPkgs != null) { 10879 for (int i=0; i<clientLibPkgs.size(); i++) { 10880 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10881 killApplication(clientPkg.applicationInfo.packageName, 10882 clientPkg.applicationInfo.uid, "update lib"); 10883 } 10884 } 10885 10886 // writer 10887 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10888 10889 synchronized (mPackages) { 10890 // We don't expect installation to fail beyond this point 10891 10892 // Add the new setting to mSettings 10893 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10894 // Add the new setting to mPackages 10895 mPackages.put(pkg.applicationInfo.packageName, pkg); 10896 // Make sure we don't accidentally delete its data. 10897 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10898 while (iter.hasNext()) { 10899 PackageCleanItem item = iter.next(); 10900 if (pkgName.equals(item.packageName)) { 10901 iter.remove(); 10902 } 10903 } 10904 10905 // Add the package's KeySets to the global KeySetManagerService 10906 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10907 ksms.addScannedPackageLPw(pkg); 10908 10909 int N = pkg.providers.size(); 10910 StringBuilder r = null; 10911 int i; 10912 for (i=0; i<N; i++) { 10913 PackageParser.Provider p = pkg.providers.get(i); 10914 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10915 p.info.processName); 10916 mProviders.addProvider(p); 10917 p.syncable = p.info.isSyncable; 10918 if (p.info.authority != null) { 10919 String names[] = p.info.authority.split(";"); 10920 p.info.authority = null; 10921 for (int j = 0; j < names.length; j++) { 10922 if (j == 1 && p.syncable) { 10923 // We only want the first authority for a provider to possibly be 10924 // syncable, so if we already added this provider using a different 10925 // authority clear the syncable flag. We copy the provider before 10926 // changing it because the mProviders object contains a reference 10927 // to a provider that we don't want to change. 10928 // Only do this for the second authority since the resulting provider 10929 // object can be the same for all future authorities for this provider. 10930 p = new PackageParser.Provider(p); 10931 p.syncable = false; 10932 } 10933 if (!mProvidersByAuthority.containsKey(names[j])) { 10934 mProvidersByAuthority.put(names[j], p); 10935 if (p.info.authority == null) { 10936 p.info.authority = names[j]; 10937 } else { 10938 p.info.authority = p.info.authority + ";" + names[j]; 10939 } 10940 if (DEBUG_PACKAGE_SCANNING) { 10941 if (chatty) 10942 Log.d(TAG, "Registered content provider: " + names[j] 10943 + ", className = " + p.info.name + ", isSyncable = " 10944 + p.info.isSyncable); 10945 } 10946 } else { 10947 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10948 Slog.w(TAG, "Skipping provider name " + names[j] + 10949 " (in package " + pkg.applicationInfo.packageName + 10950 "): name already used by " 10951 + ((other != null && other.getComponentName() != null) 10952 ? other.getComponentName().getPackageName() : "?")); 10953 } 10954 } 10955 } 10956 if (chatty) { 10957 if (r == null) { 10958 r = new StringBuilder(256); 10959 } else { 10960 r.append(' '); 10961 } 10962 r.append(p.info.name); 10963 } 10964 } 10965 if (r != null) { 10966 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10967 } 10968 10969 N = pkg.services.size(); 10970 r = null; 10971 for (i=0; i<N; i++) { 10972 PackageParser.Service s = pkg.services.get(i); 10973 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10974 s.info.processName); 10975 mServices.addService(s); 10976 if (chatty) { 10977 if (r == null) { 10978 r = new StringBuilder(256); 10979 } else { 10980 r.append(' '); 10981 } 10982 r.append(s.info.name); 10983 } 10984 } 10985 if (r != null) { 10986 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10987 } 10988 10989 N = pkg.receivers.size(); 10990 r = null; 10991 for (i=0; i<N; i++) { 10992 PackageParser.Activity a = pkg.receivers.get(i); 10993 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10994 a.info.processName); 10995 mReceivers.addActivity(a, "receiver"); 10996 if (chatty) { 10997 if (r == null) { 10998 r = new StringBuilder(256); 10999 } else { 11000 r.append(' '); 11001 } 11002 r.append(a.info.name); 11003 } 11004 } 11005 if (r != null) { 11006 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 11007 } 11008 11009 N = pkg.activities.size(); 11010 r = null; 11011 for (i=0; i<N; i++) { 11012 PackageParser.Activity a = pkg.activities.get(i); 11013 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11014 a.info.processName); 11015 mActivities.addActivity(a, "activity"); 11016 if (chatty) { 11017 if (r == null) { 11018 r = new StringBuilder(256); 11019 } else { 11020 r.append(' '); 11021 } 11022 r.append(a.info.name); 11023 } 11024 } 11025 if (r != null) { 11026 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11027 } 11028 11029 // Don't allow ephemeral applications to define new permissions groups. 11030 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11031 Slog.w(TAG, "Permission groups from package " + pkg.packageName 11032 + " ignored: instant apps cannot define new permission groups."); 11033 } else { 11034 mPermissionManager.addAllPermissionGroups(pkg, chatty); 11035 } 11036 11037 // Don't allow ephemeral applications to define new permissions. 11038 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11039 Slog.w(TAG, "Permissions from package " + pkg.packageName 11040 + " ignored: instant apps cannot define new permissions."); 11041 } else { 11042 mPermissionManager.addAllPermissions(pkg, chatty); 11043 } 11044 11045 N = pkg.instrumentation.size(); 11046 r = null; 11047 for (i=0; i<N; i++) { 11048 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11049 a.info.packageName = pkg.applicationInfo.packageName; 11050 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11051 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11052 a.info.splitNames = pkg.splitNames; 11053 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11054 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11055 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11056 a.info.dataDir = pkg.applicationInfo.dataDir; 11057 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11058 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11059 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11060 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11061 mInstrumentation.put(a.getComponentName(), a); 11062 if (chatty) { 11063 if (r == null) { 11064 r = new StringBuilder(256); 11065 } else { 11066 r.append(' '); 11067 } 11068 r.append(a.info.name); 11069 } 11070 } 11071 if (r != null) { 11072 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11073 } 11074 11075 if (pkg.protectedBroadcasts != null) { 11076 N = pkg.protectedBroadcasts.size(); 11077 synchronized (mProtectedBroadcasts) { 11078 for (i = 0; i < N; i++) { 11079 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 11080 } 11081 } 11082 } 11083 } 11084 11085 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11086 } 11087 11088 /** 11089 * Derive the ABI of a non-system package located at {@code scanFile}. This information 11090 * is derived purely on the basis of the contents of {@code scanFile} and 11091 * {@code cpuAbiOverride}. 11092 * 11093 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 11094 */ 11095 private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride, 11096 boolean extractLibs) 11097 throws PackageManagerException { 11098 // Give ourselves some initial paths; we'll come back for another 11099 // pass once we've determined ABI below. 11100 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11101 11102 // We would never need to extract libs for forward-locked and external packages, 11103 // since the container service will do it for us. We shouldn't attempt to 11104 // extract libs from system app when it was not updated. 11105 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 11106 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 11107 extractLibs = false; 11108 } 11109 11110 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 11111 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 11112 11113 NativeLibraryHelper.Handle handle = null; 11114 try { 11115 handle = NativeLibraryHelper.Handle.create(pkg); 11116 // TODO(multiArch): This can be null for apps that didn't go through the 11117 // usual installation process. We can calculate it again, like we 11118 // do during install time. 11119 // 11120 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 11121 // unnecessary. 11122 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 11123 11124 // Null out the abis so that they can be recalculated. 11125 pkg.applicationInfo.primaryCpuAbi = null; 11126 pkg.applicationInfo.secondaryCpuAbi = null; 11127 if (isMultiArch(pkg.applicationInfo)) { 11128 // Warn if we've set an abiOverride for multi-lib packages.. 11129 // By definition, we need to copy both 32 and 64 bit libraries for 11130 // such packages. 11131 if (pkg.cpuAbiOverride != null 11132 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 11133 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 11134 } 11135 11136 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 11137 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 11138 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 11139 if (extractLibs) { 11140 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11141 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11142 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 11143 useIsaSpecificSubdirs); 11144 } else { 11145 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11146 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 11147 } 11148 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11149 } 11150 11151 // Shared library native code should be in the APK zip aligned 11152 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 11153 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11154 "Shared library native lib extraction not supported"); 11155 } 11156 11157 maybeThrowExceptionForMultiArchCopy( 11158 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 11159 11160 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 11161 if (extractLibs) { 11162 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11163 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11164 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 11165 useIsaSpecificSubdirs); 11166 } else { 11167 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11168 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 11169 } 11170 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11171 } 11172 11173 maybeThrowExceptionForMultiArchCopy( 11174 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 11175 11176 if (abi64 >= 0) { 11177 // Shared library native libs should be in the APK zip aligned 11178 if (extractLibs && pkg.isLibrary()) { 11179 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11180 "Shared library native lib extraction not supported"); 11181 } 11182 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11183 } 11184 11185 if (abi32 >= 0) { 11186 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11187 if (abi64 >= 0) { 11188 if (pkg.use32bitAbi) { 11189 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11190 pkg.applicationInfo.primaryCpuAbi = abi; 11191 } else { 11192 pkg.applicationInfo.secondaryCpuAbi = abi; 11193 } 11194 } else { 11195 pkg.applicationInfo.primaryCpuAbi = abi; 11196 } 11197 } 11198 } else { 11199 String[] abiList = (cpuAbiOverride != null) ? 11200 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11201 11202 // Enable gross and lame hacks for apps that are built with old 11203 // SDK tools. We must scan their APKs for renderscript bitcode and 11204 // not launch them if it's present. Don't bother checking on devices 11205 // that don't have 64 bit support. 11206 boolean needsRenderScriptOverride = false; 11207 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11208 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11209 abiList = Build.SUPPORTED_32_BIT_ABIS; 11210 needsRenderScriptOverride = true; 11211 } 11212 11213 final int copyRet; 11214 if (extractLibs) { 11215 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11216 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11217 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11218 } else { 11219 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11220 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11221 } 11222 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11223 11224 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11225 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11226 "Error unpackaging native libs for app, errorCode=" + copyRet); 11227 } 11228 11229 if (copyRet >= 0) { 11230 // Shared libraries that have native libs must be multi-architecture 11231 if (pkg.isLibrary()) { 11232 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11233 "Shared library with native libs must be multiarch"); 11234 } 11235 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11236 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11237 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11238 } else if (needsRenderScriptOverride) { 11239 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11240 } 11241 } 11242 } catch (IOException ioe) { 11243 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11244 } finally { 11245 IoUtils.closeQuietly(handle); 11246 } 11247 11248 // Now that we've calculated the ABIs and determined if it's an internal app, 11249 // we will go ahead and populate the nativeLibraryPath. 11250 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11251 } 11252 11253 /** 11254 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11255 * i.e, so that all packages can be run inside a single process if required. 11256 * 11257 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11258 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11259 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11260 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11261 * updating a package that belongs to a shared user. 11262 * 11263 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11264 * adds unnecessary complexity. 11265 */ 11266 private static @Nullable List<String> adjustCpuAbisForSharedUserLPw( 11267 Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) { 11268 List<String> changedAbiCodePath = null; 11269 String requiredInstructionSet = null; 11270 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11271 requiredInstructionSet = VMRuntime.getInstructionSet( 11272 scannedPackage.applicationInfo.primaryCpuAbi); 11273 } 11274 11275 PackageSetting requirer = null; 11276 for (PackageSetting ps : packagesForUser) { 11277 // If packagesForUser contains scannedPackage, we skip it. This will happen 11278 // when scannedPackage is an update of an existing package. Without this check, 11279 // we will never be able to change the ABI of any package belonging to a shared 11280 // user, even if it's compatible with other packages. 11281 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11282 if (ps.primaryCpuAbiString == null) { 11283 continue; 11284 } 11285 11286 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11287 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11288 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11289 // this but there's not much we can do. 11290 String errorMessage = "Instruction set mismatch, " 11291 + ((requirer == null) ? "[caller]" : requirer) 11292 + " requires " + requiredInstructionSet + " whereas " + ps 11293 + " requires " + instructionSet; 11294 Slog.w(TAG, errorMessage); 11295 } 11296 11297 if (requiredInstructionSet == null) { 11298 requiredInstructionSet = instructionSet; 11299 requirer = ps; 11300 } 11301 } 11302 } 11303 11304 if (requiredInstructionSet != null) { 11305 String adjustedAbi; 11306 if (requirer != null) { 11307 // requirer != null implies that either scannedPackage was null or that scannedPackage 11308 // did not require an ABI, in which case we have to adjust scannedPackage to match 11309 // the ABI of the set (which is the same as requirer's ABI) 11310 adjustedAbi = requirer.primaryCpuAbiString; 11311 if (scannedPackage != null) { 11312 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11313 } 11314 } else { 11315 // requirer == null implies that we're updating all ABIs in the set to 11316 // match scannedPackage. 11317 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11318 } 11319 11320 for (PackageSetting ps : packagesForUser) { 11321 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11322 if (ps.primaryCpuAbiString != null) { 11323 continue; 11324 } 11325 11326 ps.primaryCpuAbiString = adjustedAbi; 11327 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11328 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11329 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11330 if (DEBUG_ABI_SELECTION) { 11331 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11332 + " (requirer=" 11333 + (requirer != null ? requirer.pkg : "null") 11334 + ", scannedPackage=" 11335 + (scannedPackage != null ? scannedPackage : "null") 11336 + ")"); 11337 } 11338 if (changedAbiCodePath == null) { 11339 changedAbiCodePath = new ArrayList<>(); 11340 } 11341 changedAbiCodePath.add(ps.codePathString); 11342 } 11343 } 11344 } 11345 } 11346 return changedAbiCodePath; 11347 } 11348 11349 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11350 synchronized (mPackages) { 11351 mResolverReplaced = true; 11352 // Set up information for custom user intent resolution activity. 11353 mResolveActivity.applicationInfo = pkg.applicationInfo; 11354 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11355 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11356 mResolveActivity.processName = pkg.applicationInfo.packageName; 11357 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11358 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11359 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11360 mResolveActivity.theme = 0; 11361 mResolveActivity.exported = true; 11362 mResolveActivity.enabled = true; 11363 mResolveInfo.activityInfo = mResolveActivity; 11364 mResolveInfo.priority = 0; 11365 mResolveInfo.preferredOrder = 0; 11366 mResolveInfo.match = 0; 11367 mResolveComponentName = mCustomResolverComponentName; 11368 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11369 mResolveComponentName); 11370 } 11371 } 11372 11373 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11374 if (installerActivity == null) { 11375 if (DEBUG_EPHEMERAL) { 11376 Slog.d(TAG, "Clear ephemeral installer activity"); 11377 } 11378 mInstantAppInstallerActivity = null; 11379 return; 11380 } 11381 11382 if (DEBUG_EPHEMERAL) { 11383 Slog.d(TAG, "Set ephemeral installer activity: " 11384 + installerActivity.getComponentName()); 11385 } 11386 // Set up information for ephemeral installer activity 11387 mInstantAppInstallerActivity = installerActivity; 11388 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11389 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11390 mInstantAppInstallerActivity.exported = true; 11391 mInstantAppInstallerActivity.enabled = true; 11392 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11393 mInstantAppInstallerInfo.priority = 0; 11394 mInstantAppInstallerInfo.preferredOrder = 1; 11395 mInstantAppInstallerInfo.isDefault = true; 11396 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11397 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11398 } 11399 11400 private static String calculateBundledApkRoot(final String codePathString) { 11401 final File codePath = new File(codePathString); 11402 final File codeRoot; 11403 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11404 codeRoot = Environment.getRootDirectory(); 11405 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11406 codeRoot = Environment.getOemDirectory(); 11407 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11408 codeRoot = Environment.getVendorDirectory(); 11409 } else { 11410 // Unrecognized code path; take its top real segment as the apk root: 11411 // e.g. /something/app/blah.apk => /something 11412 try { 11413 File f = codePath.getCanonicalFile(); 11414 File parent = f.getParentFile(); // non-null because codePath is a file 11415 File tmp; 11416 while ((tmp = parent.getParentFile()) != null) { 11417 f = parent; 11418 parent = tmp; 11419 } 11420 codeRoot = f; 11421 Slog.w(TAG, "Unrecognized code path " 11422 + codePath + " - using " + codeRoot); 11423 } catch (IOException e) { 11424 // Can't canonicalize the code path -- shenanigans? 11425 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11426 return Environment.getRootDirectory().getPath(); 11427 } 11428 } 11429 return codeRoot.getPath(); 11430 } 11431 11432 /** 11433 * Derive and set the location of native libraries for the given package, 11434 * which varies depending on where and how the package was installed. 11435 */ 11436 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11437 final ApplicationInfo info = pkg.applicationInfo; 11438 final String codePath = pkg.codePath; 11439 final File codeFile = new File(codePath); 11440 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11441 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11442 11443 info.nativeLibraryRootDir = null; 11444 info.nativeLibraryRootRequiresIsa = false; 11445 info.nativeLibraryDir = null; 11446 info.secondaryNativeLibraryDir = null; 11447 11448 if (isApkFile(codeFile)) { 11449 // Monolithic install 11450 if (bundledApp) { 11451 // If "/system/lib64/apkname" exists, assume that is the per-package 11452 // native library directory to use; otherwise use "/system/lib/apkname". 11453 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11454 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11455 getPrimaryInstructionSet(info)); 11456 11457 // This is a bundled system app so choose the path based on the ABI. 11458 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11459 // is just the default path. 11460 final String apkName = deriveCodePathName(codePath); 11461 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11462 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11463 apkName).getAbsolutePath(); 11464 11465 if (info.secondaryCpuAbi != null) { 11466 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11467 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11468 secondaryLibDir, apkName).getAbsolutePath(); 11469 } 11470 } else if (asecApp) { 11471 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11472 .getAbsolutePath(); 11473 } else { 11474 final String apkName = deriveCodePathName(codePath); 11475 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11476 .getAbsolutePath(); 11477 } 11478 11479 info.nativeLibraryRootRequiresIsa = false; 11480 info.nativeLibraryDir = info.nativeLibraryRootDir; 11481 } else { 11482 // Cluster install 11483 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11484 info.nativeLibraryRootRequiresIsa = true; 11485 11486 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11487 getPrimaryInstructionSet(info)).getAbsolutePath(); 11488 11489 if (info.secondaryCpuAbi != null) { 11490 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11491 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11492 } 11493 } 11494 } 11495 11496 /** 11497 * Calculate the abis and roots for a bundled app. These can uniquely 11498 * be determined from the contents of the system partition, i.e whether 11499 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11500 * of this information, and instead assume that the system was built 11501 * sensibly. 11502 */ 11503 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11504 PackageSetting pkgSetting) { 11505 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11506 11507 // If "/system/lib64/apkname" exists, assume that is the per-package 11508 // native library directory to use; otherwise use "/system/lib/apkname". 11509 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11510 setBundledAppAbi(pkg, apkRoot, apkName); 11511 // pkgSetting might be null during rescan following uninstall of updates 11512 // to a bundled app, so accommodate that possibility. The settings in 11513 // that case will be established later from the parsed package. 11514 // 11515 // If the settings aren't null, sync them up with what we've just derived. 11516 // note that apkRoot isn't stored in the package settings. 11517 if (pkgSetting != null) { 11518 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11519 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11520 } 11521 } 11522 11523 /** 11524 * Deduces the ABI of a bundled app and sets the relevant fields on the 11525 * parsed pkg object. 11526 * 11527 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11528 * under which system libraries are installed. 11529 * @param apkName the name of the installed package. 11530 */ 11531 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11532 final File codeFile = new File(pkg.codePath); 11533 11534 final boolean has64BitLibs; 11535 final boolean has32BitLibs; 11536 if (isApkFile(codeFile)) { 11537 // Monolithic install 11538 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11539 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11540 } else { 11541 // Cluster install 11542 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11543 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11544 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11545 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11546 has64BitLibs = (new File(rootDir, isa)).exists(); 11547 } else { 11548 has64BitLibs = false; 11549 } 11550 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11551 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11552 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11553 has32BitLibs = (new File(rootDir, isa)).exists(); 11554 } else { 11555 has32BitLibs = false; 11556 } 11557 } 11558 11559 if (has64BitLibs && !has32BitLibs) { 11560 // The package has 64 bit libs, but not 32 bit libs. Its primary 11561 // ABI should be 64 bit. We can safely assume here that the bundled 11562 // native libraries correspond to the most preferred ABI in the list. 11563 11564 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11565 pkg.applicationInfo.secondaryCpuAbi = null; 11566 } else if (has32BitLibs && !has64BitLibs) { 11567 // The package has 32 bit libs but not 64 bit libs. Its primary 11568 // ABI should be 32 bit. 11569 11570 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11571 pkg.applicationInfo.secondaryCpuAbi = null; 11572 } else if (has32BitLibs && has64BitLibs) { 11573 // The application has both 64 and 32 bit bundled libraries. We check 11574 // here that the app declares multiArch support, and warn if it doesn't. 11575 // 11576 // We will be lenient here and record both ABIs. The primary will be the 11577 // ABI that's higher on the list, i.e, a device that's configured to prefer 11578 // 64 bit apps will see a 64 bit primary ABI, 11579 11580 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11581 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11582 } 11583 11584 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11585 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11586 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11587 } else { 11588 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11589 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11590 } 11591 } else { 11592 pkg.applicationInfo.primaryCpuAbi = null; 11593 pkg.applicationInfo.secondaryCpuAbi = null; 11594 } 11595 } 11596 11597 private void killApplication(String pkgName, int appId, String reason) { 11598 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11599 } 11600 11601 private void killApplication(String pkgName, int appId, int userId, String reason) { 11602 // Request the ActivityManager to kill the process(only for existing packages) 11603 // so that we do not end up in a confused state while the user is still using the older 11604 // version of the application while the new one gets installed. 11605 final long token = Binder.clearCallingIdentity(); 11606 try { 11607 IActivityManager am = ActivityManager.getService(); 11608 if (am != null) { 11609 try { 11610 am.killApplication(pkgName, appId, userId, reason); 11611 } catch (RemoteException e) { 11612 } 11613 } 11614 } finally { 11615 Binder.restoreCallingIdentity(token); 11616 } 11617 } 11618 11619 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 11620 // Remove the parent package setting 11621 PackageSetting ps = (PackageSetting) pkg.mExtras; 11622 if (ps != null) { 11623 removePackageLI(ps, chatty); 11624 } 11625 // Remove the child package setting 11626 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11627 for (int i = 0; i < childCount; i++) { 11628 PackageParser.Package childPkg = pkg.childPackages.get(i); 11629 ps = (PackageSetting) childPkg.mExtras; 11630 if (ps != null) { 11631 removePackageLI(ps, chatty); 11632 } 11633 } 11634 } 11635 11636 void removePackageLI(PackageSetting ps, boolean chatty) { 11637 if (DEBUG_INSTALL) { 11638 if (chatty) 11639 Log.d(TAG, "Removing package " + ps.name); 11640 } 11641 11642 // writer 11643 synchronized (mPackages) { 11644 mPackages.remove(ps.name); 11645 final PackageParser.Package pkg = ps.pkg; 11646 if (pkg != null) { 11647 cleanPackageDataStructuresLILPw(pkg, chatty); 11648 } 11649 } 11650 } 11651 11652 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11653 if (DEBUG_INSTALL) { 11654 if (chatty) 11655 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11656 } 11657 11658 // writer 11659 synchronized (mPackages) { 11660 // Remove the parent package 11661 mPackages.remove(pkg.applicationInfo.packageName); 11662 cleanPackageDataStructuresLILPw(pkg, chatty); 11663 11664 // Remove the child packages 11665 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11666 for (int i = 0; i < childCount; i++) { 11667 PackageParser.Package childPkg = pkg.childPackages.get(i); 11668 mPackages.remove(childPkg.applicationInfo.packageName); 11669 cleanPackageDataStructuresLILPw(childPkg, chatty); 11670 } 11671 } 11672 } 11673 11674 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11675 int N = pkg.providers.size(); 11676 StringBuilder r = null; 11677 int i; 11678 for (i=0; i<N; i++) { 11679 PackageParser.Provider p = pkg.providers.get(i); 11680 mProviders.removeProvider(p); 11681 if (p.info.authority == null) { 11682 11683 /* There was another ContentProvider with this authority when 11684 * this app was installed so this authority is null, 11685 * Ignore it as we don't have to unregister the provider. 11686 */ 11687 continue; 11688 } 11689 String names[] = p.info.authority.split(";"); 11690 for (int j = 0; j < names.length; j++) { 11691 if (mProvidersByAuthority.get(names[j]) == p) { 11692 mProvidersByAuthority.remove(names[j]); 11693 if (DEBUG_REMOVE) { 11694 if (chatty) 11695 Log.d(TAG, "Unregistered content provider: " + names[j] 11696 + ", className = " + p.info.name + ", isSyncable = " 11697 + p.info.isSyncable); 11698 } 11699 } 11700 } 11701 if (DEBUG_REMOVE && chatty) { 11702 if (r == null) { 11703 r = new StringBuilder(256); 11704 } else { 11705 r.append(' '); 11706 } 11707 r.append(p.info.name); 11708 } 11709 } 11710 if (r != null) { 11711 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11712 } 11713 11714 N = pkg.services.size(); 11715 r = null; 11716 for (i=0; i<N; i++) { 11717 PackageParser.Service s = pkg.services.get(i); 11718 mServices.removeService(s); 11719 if (chatty) { 11720 if (r == null) { 11721 r = new StringBuilder(256); 11722 } else { 11723 r.append(' '); 11724 } 11725 r.append(s.info.name); 11726 } 11727 } 11728 if (r != null) { 11729 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11730 } 11731 11732 N = pkg.receivers.size(); 11733 r = null; 11734 for (i=0; i<N; i++) { 11735 PackageParser.Activity a = pkg.receivers.get(i); 11736 mReceivers.removeActivity(a, "receiver"); 11737 if (DEBUG_REMOVE && chatty) { 11738 if (r == null) { 11739 r = new StringBuilder(256); 11740 } else { 11741 r.append(' '); 11742 } 11743 r.append(a.info.name); 11744 } 11745 } 11746 if (r != null) { 11747 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11748 } 11749 11750 N = pkg.activities.size(); 11751 r = null; 11752 for (i=0; i<N; i++) { 11753 PackageParser.Activity a = pkg.activities.get(i); 11754 mActivities.removeActivity(a, "activity"); 11755 if (DEBUG_REMOVE && chatty) { 11756 if (r == null) { 11757 r = new StringBuilder(256); 11758 } else { 11759 r.append(' '); 11760 } 11761 r.append(a.info.name); 11762 } 11763 } 11764 if (r != null) { 11765 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11766 } 11767 11768 mPermissionManager.removeAllPermissions(pkg, chatty); 11769 11770 N = pkg.instrumentation.size(); 11771 r = null; 11772 for (i=0; i<N; i++) { 11773 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11774 mInstrumentation.remove(a.getComponentName()); 11775 if (DEBUG_REMOVE && chatty) { 11776 if (r == null) { 11777 r = new StringBuilder(256); 11778 } else { 11779 r.append(' '); 11780 } 11781 r.append(a.info.name); 11782 } 11783 } 11784 if (r != null) { 11785 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11786 } 11787 11788 r = null; 11789 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11790 // Only system apps can hold shared libraries. 11791 if (pkg.libraryNames != null) { 11792 for (i = 0; i < pkg.libraryNames.size(); i++) { 11793 String name = pkg.libraryNames.get(i); 11794 if (removeSharedLibraryLPw(name, 0)) { 11795 if (DEBUG_REMOVE && chatty) { 11796 if (r == null) { 11797 r = new StringBuilder(256); 11798 } else { 11799 r.append(' '); 11800 } 11801 r.append(name); 11802 } 11803 } 11804 } 11805 } 11806 } 11807 11808 r = null; 11809 11810 // Any package can hold static shared libraries. 11811 if (pkg.staticSharedLibName != null) { 11812 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11813 if (DEBUG_REMOVE && chatty) { 11814 if (r == null) { 11815 r = new StringBuilder(256); 11816 } else { 11817 r.append(' '); 11818 } 11819 r.append(pkg.staticSharedLibName); 11820 } 11821 } 11822 } 11823 11824 if (r != null) { 11825 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11826 } 11827 } 11828 11829 11830 final class ActivityIntentResolver 11831 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11832 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11833 boolean defaultOnly, int userId) { 11834 if (!sUserManager.exists(userId)) return null; 11835 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11836 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11837 } 11838 11839 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11840 int userId) { 11841 if (!sUserManager.exists(userId)) return null; 11842 mFlags = flags; 11843 return super.queryIntent(intent, resolvedType, 11844 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11845 userId); 11846 } 11847 11848 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11849 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11850 if (!sUserManager.exists(userId)) return null; 11851 if (packageActivities == null) { 11852 return null; 11853 } 11854 mFlags = flags; 11855 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11856 final int N = packageActivities.size(); 11857 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11858 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11859 11860 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11861 for (int i = 0; i < N; ++i) { 11862 intentFilters = packageActivities.get(i).intents; 11863 if (intentFilters != null && intentFilters.size() > 0) { 11864 PackageParser.ActivityIntentInfo[] array = 11865 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11866 intentFilters.toArray(array); 11867 listCut.add(array); 11868 } 11869 } 11870 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11871 } 11872 11873 /** 11874 * Finds a privileged activity that matches the specified activity names. 11875 */ 11876 private PackageParser.Activity findMatchingActivity( 11877 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11878 for (PackageParser.Activity sysActivity : activityList) { 11879 if (sysActivity.info.name.equals(activityInfo.name)) { 11880 return sysActivity; 11881 } 11882 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11883 return sysActivity; 11884 } 11885 if (sysActivity.info.targetActivity != null) { 11886 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11887 return sysActivity; 11888 } 11889 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11890 return sysActivity; 11891 } 11892 } 11893 } 11894 return null; 11895 } 11896 11897 public class IterGenerator<E> { 11898 public Iterator<E> generate(ActivityIntentInfo info) { 11899 return null; 11900 } 11901 } 11902 11903 public class ActionIterGenerator extends IterGenerator<String> { 11904 @Override 11905 public Iterator<String> generate(ActivityIntentInfo info) { 11906 return info.actionsIterator(); 11907 } 11908 } 11909 11910 public class CategoriesIterGenerator extends IterGenerator<String> { 11911 @Override 11912 public Iterator<String> generate(ActivityIntentInfo info) { 11913 return info.categoriesIterator(); 11914 } 11915 } 11916 11917 public class SchemesIterGenerator extends IterGenerator<String> { 11918 @Override 11919 public Iterator<String> generate(ActivityIntentInfo info) { 11920 return info.schemesIterator(); 11921 } 11922 } 11923 11924 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11925 @Override 11926 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11927 return info.authoritiesIterator(); 11928 } 11929 } 11930 11931 /** 11932 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11933 * MODIFIED. Do not pass in a list that should not be changed. 11934 */ 11935 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11936 IterGenerator<T> generator, Iterator<T> searchIterator) { 11937 // loop through the set of actions; every one must be found in the intent filter 11938 while (searchIterator.hasNext()) { 11939 // we must have at least one filter in the list to consider a match 11940 if (intentList.size() == 0) { 11941 break; 11942 } 11943 11944 final T searchAction = searchIterator.next(); 11945 11946 // loop through the set of intent filters 11947 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11948 while (intentIter.hasNext()) { 11949 final ActivityIntentInfo intentInfo = intentIter.next(); 11950 boolean selectionFound = false; 11951 11952 // loop through the intent filter's selection criteria; at least one 11953 // of them must match the searched criteria 11954 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11955 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11956 final T intentSelection = intentSelectionIter.next(); 11957 if (intentSelection != null && intentSelection.equals(searchAction)) { 11958 selectionFound = true; 11959 break; 11960 } 11961 } 11962 11963 // the selection criteria wasn't found in this filter's set; this filter 11964 // is not a potential match 11965 if (!selectionFound) { 11966 intentIter.remove(); 11967 } 11968 } 11969 } 11970 } 11971 11972 private boolean isProtectedAction(ActivityIntentInfo filter) { 11973 final Iterator<String> actionsIter = filter.actionsIterator(); 11974 while (actionsIter != null && actionsIter.hasNext()) { 11975 final String filterAction = actionsIter.next(); 11976 if (PROTECTED_ACTIONS.contains(filterAction)) { 11977 return true; 11978 } 11979 } 11980 return false; 11981 } 11982 11983 /** 11984 * Adjusts the priority of the given intent filter according to policy. 11985 * <p> 11986 * <ul> 11987 * <li>The priority for non privileged applications is capped to '0'</li> 11988 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11989 * <li>The priority for unbundled updates to privileged applications is capped to the 11990 * priority defined on the system partition</li> 11991 * </ul> 11992 * <p> 11993 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11994 * allowed to obtain any priority on any action. 11995 */ 11996 private void adjustPriority( 11997 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11998 // nothing to do; priority is fine as-is 11999 if (intent.getPriority() <= 0) { 12000 return; 12001 } 12002 12003 final ActivityInfo activityInfo = intent.activity.info; 12004 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12005 12006 final boolean privilegedApp = 12007 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12008 if (!privilegedApp) { 12009 // non-privileged applications can never define a priority >0 12010 if (DEBUG_FILTERS) { 12011 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 12012 + " package: " + applicationInfo.packageName 12013 + " activity: " + intent.activity.className 12014 + " origPrio: " + intent.getPriority()); 12015 } 12016 intent.setPriority(0); 12017 return; 12018 } 12019 12020 if (systemActivities == null) { 12021 // the system package is not disabled; we're parsing the system partition 12022 if (isProtectedAction(intent)) { 12023 if (mDeferProtectedFilters) { 12024 // We can't deal with these just yet. No component should ever obtain a 12025 // >0 priority for a protected actions, with ONE exception -- the setup 12026 // wizard. The setup wizard, however, cannot be known until we're able to 12027 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12028 // until all intent filters have been processed. Chicken, meet egg. 12029 // Let the filter temporarily have a high priority and rectify the 12030 // priorities after all system packages have been scanned. 12031 mProtectedFilters.add(intent); 12032 if (DEBUG_FILTERS) { 12033 Slog.i(TAG, "Protected action; save for later;" 12034 + " package: " + applicationInfo.packageName 12035 + " activity: " + intent.activity.className 12036 + " origPrio: " + intent.getPriority()); 12037 } 12038 return; 12039 } else { 12040 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12041 Slog.i(TAG, "No setup wizard;" 12042 + " All protected intents capped to priority 0"); 12043 } 12044 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12045 if (DEBUG_FILTERS) { 12046 Slog.i(TAG, "Found setup wizard;" 12047 + " allow priority " + intent.getPriority() + ";" 12048 + " package: " + intent.activity.info.packageName 12049 + " activity: " + intent.activity.className 12050 + " priority: " + intent.getPriority()); 12051 } 12052 // setup wizard gets whatever it wants 12053 return; 12054 } 12055 if (DEBUG_FILTERS) { 12056 Slog.i(TAG, "Protected action; cap priority to 0;" 12057 + " package: " + intent.activity.info.packageName 12058 + " activity: " + intent.activity.className 12059 + " origPrio: " + intent.getPriority()); 12060 } 12061 intent.setPriority(0); 12062 return; 12063 } 12064 } 12065 // privileged apps on the system image get whatever priority they request 12066 return; 12067 } 12068 12069 // privileged app unbundled update ... try to find the same activity 12070 final PackageParser.Activity foundActivity = 12071 findMatchingActivity(systemActivities, activityInfo); 12072 if (foundActivity == null) { 12073 // this is a new activity; it cannot obtain >0 priority 12074 if (DEBUG_FILTERS) { 12075 Slog.i(TAG, "New activity; cap priority to 0;" 12076 + " package: " + applicationInfo.packageName 12077 + " activity: " + intent.activity.className 12078 + " origPrio: " + intent.getPriority()); 12079 } 12080 intent.setPriority(0); 12081 return; 12082 } 12083 12084 // found activity, now check for filter equivalence 12085 12086 // a shallow copy is enough; we modify the list, not its contents 12087 final List<ActivityIntentInfo> intentListCopy = 12088 new ArrayList<>(foundActivity.intents); 12089 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12090 12091 // find matching action subsets 12092 final Iterator<String> actionsIterator = intent.actionsIterator(); 12093 if (actionsIterator != null) { 12094 getIntentListSubset( 12095 intentListCopy, new ActionIterGenerator(), actionsIterator); 12096 if (intentListCopy.size() == 0) { 12097 // no more intents to match; we're not equivalent 12098 if (DEBUG_FILTERS) { 12099 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12100 + " package: " + applicationInfo.packageName 12101 + " activity: " + intent.activity.className 12102 + " origPrio: " + intent.getPriority()); 12103 } 12104 intent.setPriority(0); 12105 return; 12106 } 12107 } 12108 12109 // find matching category subsets 12110 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12111 if (categoriesIterator != null) { 12112 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12113 categoriesIterator); 12114 if (intentListCopy.size() == 0) { 12115 // no more intents to match; we're not equivalent 12116 if (DEBUG_FILTERS) { 12117 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12118 + " package: " + applicationInfo.packageName 12119 + " activity: " + intent.activity.className 12120 + " origPrio: " + intent.getPriority()); 12121 } 12122 intent.setPriority(0); 12123 return; 12124 } 12125 } 12126 12127 // find matching schemes subsets 12128 final Iterator<String> schemesIterator = intent.schemesIterator(); 12129 if (schemesIterator != null) { 12130 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12131 schemesIterator); 12132 if (intentListCopy.size() == 0) { 12133 // no more intents to match; we're not equivalent 12134 if (DEBUG_FILTERS) { 12135 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12136 + " package: " + applicationInfo.packageName 12137 + " activity: " + intent.activity.className 12138 + " origPrio: " + intent.getPriority()); 12139 } 12140 intent.setPriority(0); 12141 return; 12142 } 12143 } 12144 12145 // find matching authorities subsets 12146 final Iterator<IntentFilter.AuthorityEntry> 12147 authoritiesIterator = intent.authoritiesIterator(); 12148 if (authoritiesIterator != null) { 12149 getIntentListSubset(intentListCopy, 12150 new AuthoritiesIterGenerator(), 12151 authoritiesIterator); 12152 if (intentListCopy.size() == 0) { 12153 // no more intents to match; we're not equivalent 12154 if (DEBUG_FILTERS) { 12155 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12156 + " package: " + applicationInfo.packageName 12157 + " activity: " + intent.activity.className 12158 + " origPrio: " + intent.getPriority()); 12159 } 12160 intent.setPriority(0); 12161 return; 12162 } 12163 } 12164 12165 // we found matching filter(s); app gets the max priority of all intents 12166 int cappedPriority = 0; 12167 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12168 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12169 } 12170 if (intent.getPriority() > cappedPriority) { 12171 if (DEBUG_FILTERS) { 12172 Slog.i(TAG, "Found matching filter(s);" 12173 + " cap priority to " + cappedPriority + ";" 12174 + " package: " + applicationInfo.packageName 12175 + " activity: " + intent.activity.className 12176 + " origPrio: " + intent.getPriority()); 12177 } 12178 intent.setPriority(cappedPriority); 12179 return; 12180 } 12181 // all this for nothing; the requested priority was <= what was on the system 12182 } 12183 12184 public final void addActivity(PackageParser.Activity a, String type) { 12185 mActivities.put(a.getComponentName(), a); 12186 if (DEBUG_SHOW_INFO) 12187 Log.v( 12188 TAG, " " + type + " " + 12189 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12190 if (DEBUG_SHOW_INFO) 12191 Log.v(TAG, " Class=" + a.info.name); 12192 final int NI = a.intents.size(); 12193 for (int j=0; j<NI; j++) { 12194 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12195 if ("activity".equals(type)) { 12196 final PackageSetting ps = 12197 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12198 final List<PackageParser.Activity> systemActivities = 12199 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12200 adjustPriority(systemActivities, intent); 12201 } 12202 if (DEBUG_SHOW_INFO) { 12203 Log.v(TAG, " IntentFilter:"); 12204 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12205 } 12206 if (!intent.debugCheck()) { 12207 Log.w(TAG, "==> For Activity " + a.info.name); 12208 } 12209 addFilter(intent); 12210 } 12211 } 12212 12213 public final void removeActivity(PackageParser.Activity a, String type) { 12214 mActivities.remove(a.getComponentName()); 12215 if (DEBUG_SHOW_INFO) { 12216 Log.v(TAG, " " + type + " " 12217 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12218 : a.info.name) + ":"); 12219 Log.v(TAG, " Class=" + a.info.name); 12220 } 12221 final int NI = a.intents.size(); 12222 for (int j=0; j<NI; j++) { 12223 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12224 if (DEBUG_SHOW_INFO) { 12225 Log.v(TAG, " IntentFilter:"); 12226 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12227 } 12228 removeFilter(intent); 12229 } 12230 } 12231 12232 @Override 12233 protected boolean allowFilterResult( 12234 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12235 ActivityInfo filterAi = filter.activity.info; 12236 for (int i=dest.size()-1; i>=0; i--) { 12237 ActivityInfo destAi = dest.get(i).activityInfo; 12238 if (destAi.name == filterAi.name 12239 && destAi.packageName == filterAi.packageName) { 12240 return false; 12241 } 12242 } 12243 return true; 12244 } 12245 12246 @Override 12247 protected ActivityIntentInfo[] newArray(int size) { 12248 return new ActivityIntentInfo[size]; 12249 } 12250 12251 @Override 12252 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12253 if (!sUserManager.exists(userId)) return true; 12254 PackageParser.Package p = filter.activity.owner; 12255 if (p != null) { 12256 PackageSetting ps = (PackageSetting)p.mExtras; 12257 if (ps != null) { 12258 // System apps are never considered stopped for purposes of 12259 // filtering, because there may be no way for the user to 12260 // actually re-launch them. 12261 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12262 && ps.getStopped(userId); 12263 } 12264 } 12265 return false; 12266 } 12267 12268 @Override 12269 protected boolean isPackageForFilter(String packageName, 12270 PackageParser.ActivityIntentInfo info) { 12271 return packageName.equals(info.activity.owner.packageName); 12272 } 12273 12274 @Override 12275 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12276 int match, int userId) { 12277 if (!sUserManager.exists(userId)) return null; 12278 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12279 return null; 12280 } 12281 final PackageParser.Activity activity = info.activity; 12282 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12283 if (ps == null) { 12284 return null; 12285 } 12286 final PackageUserState userState = ps.readUserState(userId); 12287 ActivityInfo ai = 12288 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 12289 if (ai == null) { 12290 return null; 12291 } 12292 final boolean matchExplicitlyVisibleOnly = 12293 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12294 final boolean matchVisibleToInstantApp = 12295 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12296 final boolean componentVisible = 12297 matchVisibleToInstantApp 12298 && info.isVisibleToInstantApp() 12299 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12300 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12301 // throw out filters that aren't visible to ephemeral apps 12302 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12303 return null; 12304 } 12305 // throw out instant app filters if we're not explicitly requesting them 12306 if (!matchInstantApp && userState.instantApp) { 12307 return null; 12308 } 12309 // throw out instant app filters if updates are available; will trigger 12310 // instant app resolution 12311 if (userState.instantApp && ps.isUpdateAvailable()) { 12312 return null; 12313 } 12314 final ResolveInfo res = new ResolveInfo(); 12315 res.activityInfo = ai; 12316 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12317 res.filter = info; 12318 } 12319 if (info != null) { 12320 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12321 } 12322 res.priority = info.getPriority(); 12323 res.preferredOrder = activity.owner.mPreferredOrder; 12324 //System.out.println("Result: " + res.activityInfo.className + 12325 // " = " + res.priority); 12326 res.match = match; 12327 res.isDefault = info.hasDefault; 12328 res.labelRes = info.labelRes; 12329 res.nonLocalizedLabel = info.nonLocalizedLabel; 12330 if (userNeedsBadging(userId)) { 12331 res.noResourceId = true; 12332 } else { 12333 res.icon = info.icon; 12334 } 12335 res.iconResourceId = info.icon; 12336 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12337 res.isInstantAppAvailable = userState.instantApp; 12338 return res; 12339 } 12340 12341 @Override 12342 protected void sortResults(List<ResolveInfo> results) { 12343 Collections.sort(results, mResolvePrioritySorter); 12344 } 12345 12346 @Override 12347 protected void dumpFilter(PrintWriter out, String prefix, 12348 PackageParser.ActivityIntentInfo filter) { 12349 out.print(prefix); out.print( 12350 Integer.toHexString(System.identityHashCode(filter.activity))); 12351 out.print(' '); 12352 filter.activity.printComponentShortName(out); 12353 out.print(" filter "); 12354 out.println(Integer.toHexString(System.identityHashCode(filter))); 12355 } 12356 12357 @Override 12358 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12359 return filter.activity; 12360 } 12361 12362 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12363 PackageParser.Activity activity = (PackageParser.Activity)label; 12364 out.print(prefix); out.print( 12365 Integer.toHexString(System.identityHashCode(activity))); 12366 out.print(' '); 12367 activity.printComponentShortName(out); 12368 if (count > 1) { 12369 out.print(" ("); out.print(count); out.print(" filters)"); 12370 } 12371 out.println(); 12372 } 12373 12374 // Keys are String (activity class name), values are Activity. 12375 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12376 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12377 private int mFlags; 12378 } 12379 12380 private final class ServiceIntentResolver 12381 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12382 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12383 boolean defaultOnly, int userId) { 12384 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12385 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12386 } 12387 12388 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12389 int userId) { 12390 if (!sUserManager.exists(userId)) return null; 12391 mFlags = flags; 12392 return super.queryIntent(intent, resolvedType, 12393 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12394 userId); 12395 } 12396 12397 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12398 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12399 if (!sUserManager.exists(userId)) return null; 12400 if (packageServices == null) { 12401 return null; 12402 } 12403 mFlags = flags; 12404 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12405 final int N = packageServices.size(); 12406 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12407 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12408 12409 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12410 for (int i = 0; i < N; ++i) { 12411 intentFilters = packageServices.get(i).intents; 12412 if (intentFilters != null && intentFilters.size() > 0) { 12413 PackageParser.ServiceIntentInfo[] array = 12414 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12415 intentFilters.toArray(array); 12416 listCut.add(array); 12417 } 12418 } 12419 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12420 } 12421 12422 public final void addService(PackageParser.Service s) { 12423 mServices.put(s.getComponentName(), s); 12424 if (DEBUG_SHOW_INFO) { 12425 Log.v(TAG, " " 12426 + (s.info.nonLocalizedLabel != null 12427 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12428 Log.v(TAG, " Class=" + s.info.name); 12429 } 12430 final int NI = s.intents.size(); 12431 int j; 12432 for (j=0; j<NI; j++) { 12433 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12434 if (DEBUG_SHOW_INFO) { 12435 Log.v(TAG, " IntentFilter:"); 12436 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12437 } 12438 if (!intent.debugCheck()) { 12439 Log.w(TAG, "==> For Service " + s.info.name); 12440 } 12441 addFilter(intent); 12442 } 12443 } 12444 12445 public final void removeService(PackageParser.Service s) { 12446 mServices.remove(s.getComponentName()); 12447 if (DEBUG_SHOW_INFO) { 12448 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12449 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12450 Log.v(TAG, " Class=" + s.info.name); 12451 } 12452 final int NI = s.intents.size(); 12453 int j; 12454 for (j=0; j<NI; j++) { 12455 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12456 if (DEBUG_SHOW_INFO) { 12457 Log.v(TAG, " IntentFilter:"); 12458 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12459 } 12460 removeFilter(intent); 12461 } 12462 } 12463 12464 @Override 12465 protected boolean allowFilterResult( 12466 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12467 ServiceInfo filterSi = filter.service.info; 12468 for (int i=dest.size()-1; i>=0; i--) { 12469 ServiceInfo destAi = dest.get(i).serviceInfo; 12470 if (destAi.name == filterSi.name 12471 && destAi.packageName == filterSi.packageName) { 12472 return false; 12473 } 12474 } 12475 return true; 12476 } 12477 12478 @Override 12479 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12480 return new PackageParser.ServiceIntentInfo[size]; 12481 } 12482 12483 @Override 12484 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12485 if (!sUserManager.exists(userId)) return true; 12486 PackageParser.Package p = filter.service.owner; 12487 if (p != null) { 12488 PackageSetting ps = (PackageSetting)p.mExtras; 12489 if (ps != null) { 12490 // System apps are never considered stopped for purposes of 12491 // filtering, because there may be no way for the user to 12492 // actually re-launch them. 12493 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12494 && ps.getStopped(userId); 12495 } 12496 } 12497 return false; 12498 } 12499 12500 @Override 12501 protected boolean isPackageForFilter(String packageName, 12502 PackageParser.ServiceIntentInfo info) { 12503 return packageName.equals(info.service.owner.packageName); 12504 } 12505 12506 @Override 12507 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12508 int match, int userId) { 12509 if (!sUserManager.exists(userId)) return null; 12510 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12511 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12512 return null; 12513 } 12514 final PackageParser.Service service = info.service; 12515 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12516 if (ps == null) { 12517 return null; 12518 } 12519 final PackageUserState userState = ps.readUserState(userId); 12520 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12521 userState, userId); 12522 if (si == null) { 12523 return null; 12524 } 12525 final boolean matchVisibleToInstantApp = 12526 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12527 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12528 // throw out filters that aren't visible to ephemeral apps 12529 if (matchVisibleToInstantApp 12530 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12531 return null; 12532 } 12533 // throw out ephemeral filters if we're not explicitly requesting them 12534 if (!isInstantApp && userState.instantApp) { 12535 return null; 12536 } 12537 // throw out instant app filters if updates are available; will trigger 12538 // instant app resolution 12539 if (userState.instantApp && ps.isUpdateAvailable()) { 12540 return null; 12541 } 12542 final ResolveInfo res = new ResolveInfo(); 12543 res.serviceInfo = si; 12544 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12545 res.filter = filter; 12546 } 12547 res.priority = info.getPriority(); 12548 res.preferredOrder = service.owner.mPreferredOrder; 12549 res.match = match; 12550 res.isDefault = info.hasDefault; 12551 res.labelRes = info.labelRes; 12552 res.nonLocalizedLabel = info.nonLocalizedLabel; 12553 res.icon = info.icon; 12554 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12555 return res; 12556 } 12557 12558 @Override 12559 protected void sortResults(List<ResolveInfo> results) { 12560 Collections.sort(results, mResolvePrioritySorter); 12561 } 12562 12563 @Override 12564 protected void dumpFilter(PrintWriter out, String prefix, 12565 PackageParser.ServiceIntentInfo filter) { 12566 out.print(prefix); out.print( 12567 Integer.toHexString(System.identityHashCode(filter.service))); 12568 out.print(' '); 12569 filter.service.printComponentShortName(out); 12570 out.print(" filter "); 12571 out.print(Integer.toHexString(System.identityHashCode(filter))); 12572 if (filter.service.info.permission != null) { 12573 out.print(" permission "); out.println(filter.service.info.permission); 12574 } else { 12575 out.println(); 12576 } 12577 } 12578 12579 @Override 12580 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12581 return filter.service; 12582 } 12583 12584 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12585 PackageParser.Service service = (PackageParser.Service)label; 12586 out.print(prefix); out.print( 12587 Integer.toHexString(System.identityHashCode(service))); 12588 out.print(' '); 12589 service.printComponentShortName(out); 12590 if (count > 1) { 12591 out.print(" ("); out.print(count); out.print(" filters)"); 12592 } 12593 out.println(); 12594 } 12595 12596// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12597// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12598// final List<ResolveInfo> retList = Lists.newArrayList(); 12599// while (i.hasNext()) { 12600// final ResolveInfo resolveInfo = (ResolveInfo) i; 12601// if (isEnabledLP(resolveInfo.serviceInfo)) { 12602// retList.add(resolveInfo); 12603// } 12604// } 12605// return retList; 12606// } 12607 12608 // Keys are String (activity class name), values are Activity. 12609 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12610 = new ArrayMap<ComponentName, PackageParser.Service>(); 12611 private int mFlags; 12612 } 12613 12614 private final class ProviderIntentResolver 12615 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12616 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12617 boolean defaultOnly, int userId) { 12618 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12619 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12620 } 12621 12622 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12623 int userId) { 12624 if (!sUserManager.exists(userId)) 12625 return null; 12626 mFlags = flags; 12627 return super.queryIntent(intent, resolvedType, 12628 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12629 userId); 12630 } 12631 12632 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12633 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12634 if (!sUserManager.exists(userId)) 12635 return null; 12636 if (packageProviders == null) { 12637 return null; 12638 } 12639 mFlags = flags; 12640 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12641 final int N = packageProviders.size(); 12642 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12643 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12644 12645 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12646 for (int i = 0; i < N; ++i) { 12647 intentFilters = packageProviders.get(i).intents; 12648 if (intentFilters != null && intentFilters.size() > 0) { 12649 PackageParser.ProviderIntentInfo[] array = 12650 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12651 intentFilters.toArray(array); 12652 listCut.add(array); 12653 } 12654 } 12655 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12656 } 12657 12658 public final void addProvider(PackageParser.Provider p) { 12659 if (mProviders.containsKey(p.getComponentName())) { 12660 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12661 return; 12662 } 12663 12664 mProviders.put(p.getComponentName(), p); 12665 if (DEBUG_SHOW_INFO) { 12666 Log.v(TAG, " " 12667 + (p.info.nonLocalizedLabel != null 12668 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12669 Log.v(TAG, " Class=" + p.info.name); 12670 } 12671 final int NI = p.intents.size(); 12672 int j; 12673 for (j = 0; j < NI; j++) { 12674 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12675 if (DEBUG_SHOW_INFO) { 12676 Log.v(TAG, " IntentFilter:"); 12677 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12678 } 12679 if (!intent.debugCheck()) { 12680 Log.w(TAG, "==> For Provider " + p.info.name); 12681 } 12682 addFilter(intent); 12683 } 12684 } 12685 12686 public final void removeProvider(PackageParser.Provider p) { 12687 mProviders.remove(p.getComponentName()); 12688 if (DEBUG_SHOW_INFO) { 12689 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12690 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12691 Log.v(TAG, " Class=" + p.info.name); 12692 } 12693 final int NI = p.intents.size(); 12694 int j; 12695 for (j = 0; j < NI; j++) { 12696 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12697 if (DEBUG_SHOW_INFO) { 12698 Log.v(TAG, " IntentFilter:"); 12699 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12700 } 12701 removeFilter(intent); 12702 } 12703 } 12704 12705 @Override 12706 protected boolean allowFilterResult( 12707 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12708 ProviderInfo filterPi = filter.provider.info; 12709 for (int i = dest.size() - 1; i >= 0; i--) { 12710 ProviderInfo destPi = dest.get(i).providerInfo; 12711 if (destPi.name == filterPi.name 12712 && destPi.packageName == filterPi.packageName) { 12713 return false; 12714 } 12715 } 12716 return true; 12717 } 12718 12719 @Override 12720 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12721 return new PackageParser.ProviderIntentInfo[size]; 12722 } 12723 12724 @Override 12725 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12726 if (!sUserManager.exists(userId)) 12727 return true; 12728 PackageParser.Package p = filter.provider.owner; 12729 if (p != null) { 12730 PackageSetting ps = (PackageSetting) p.mExtras; 12731 if (ps != null) { 12732 // System apps are never considered stopped for purposes of 12733 // filtering, because there may be no way for the user to 12734 // actually re-launch them. 12735 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12736 && ps.getStopped(userId); 12737 } 12738 } 12739 return false; 12740 } 12741 12742 @Override 12743 protected boolean isPackageForFilter(String packageName, 12744 PackageParser.ProviderIntentInfo info) { 12745 return packageName.equals(info.provider.owner.packageName); 12746 } 12747 12748 @Override 12749 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12750 int match, int userId) { 12751 if (!sUserManager.exists(userId)) 12752 return null; 12753 final PackageParser.ProviderIntentInfo info = filter; 12754 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12755 return null; 12756 } 12757 final PackageParser.Provider provider = info.provider; 12758 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12759 if (ps == null) { 12760 return null; 12761 } 12762 final PackageUserState userState = ps.readUserState(userId); 12763 final boolean matchVisibleToInstantApp = 12764 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12765 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12766 // throw out filters that aren't visible to instant applications 12767 if (matchVisibleToInstantApp 12768 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12769 return null; 12770 } 12771 // throw out instant application filters if we're not explicitly requesting them 12772 if (!isInstantApp && userState.instantApp) { 12773 return null; 12774 } 12775 // throw out instant application filters if updates are available; will trigger 12776 // instant application resolution 12777 if (userState.instantApp && ps.isUpdateAvailable()) { 12778 return null; 12779 } 12780 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12781 userState, userId); 12782 if (pi == null) { 12783 return null; 12784 } 12785 final ResolveInfo res = new ResolveInfo(); 12786 res.providerInfo = pi; 12787 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12788 res.filter = filter; 12789 } 12790 res.priority = info.getPriority(); 12791 res.preferredOrder = provider.owner.mPreferredOrder; 12792 res.match = match; 12793 res.isDefault = info.hasDefault; 12794 res.labelRes = info.labelRes; 12795 res.nonLocalizedLabel = info.nonLocalizedLabel; 12796 res.icon = info.icon; 12797 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12798 return res; 12799 } 12800 12801 @Override 12802 protected void sortResults(List<ResolveInfo> results) { 12803 Collections.sort(results, mResolvePrioritySorter); 12804 } 12805 12806 @Override 12807 protected void dumpFilter(PrintWriter out, String prefix, 12808 PackageParser.ProviderIntentInfo filter) { 12809 out.print(prefix); 12810 out.print( 12811 Integer.toHexString(System.identityHashCode(filter.provider))); 12812 out.print(' '); 12813 filter.provider.printComponentShortName(out); 12814 out.print(" filter "); 12815 out.println(Integer.toHexString(System.identityHashCode(filter))); 12816 } 12817 12818 @Override 12819 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12820 return filter.provider; 12821 } 12822 12823 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12824 PackageParser.Provider provider = (PackageParser.Provider)label; 12825 out.print(prefix); out.print( 12826 Integer.toHexString(System.identityHashCode(provider))); 12827 out.print(' '); 12828 provider.printComponentShortName(out); 12829 if (count > 1) { 12830 out.print(" ("); out.print(count); out.print(" filters)"); 12831 } 12832 out.println(); 12833 } 12834 12835 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12836 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12837 private int mFlags; 12838 } 12839 12840 static final class EphemeralIntentResolver 12841 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12842 /** 12843 * The result that has the highest defined order. Ordering applies on a 12844 * per-package basis. Mapping is from package name to Pair of order and 12845 * EphemeralResolveInfo. 12846 * <p> 12847 * NOTE: This is implemented as a field variable for convenience and efficiency. 12848 * By having a field variable, we're able to track filter ordering as soon as 12849 * a non-zero order is defined. Otherwise, multiple loops across the result set 12850 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12851 * this needs to be contained entirely within {@link #filterResults}. 12852 */ 12853 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 12854 12855 @Override 12856 protected AuxiliaryResolveInfo[] newArray(int size) { 12857 return new AuxiliaryResolveInfo[size]; 12858 } 12859 12860 @Override 12861 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12862 return true; 12863 } 12864 12865 @Override 12866 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12867 int userId) { 12868 if (!sUserManager.exists(userId)) { 12869 return null; 12870 } 12871 final String packageName = responseObj.resolveInfo.getPackageName(); 12872 final Integer order = responseObj.getOrder(); 12873 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 12874 mOrderResult.get(packageName); 12875 // ordering is enabled and this item's order isn't high enough 12876 if (lastOrderResult != null && lastOrderResult.first >= order) { 12877 return null; 12878 } 12879 final InstantAppResolveInfo res = responseObj.resolveInfo; 12880 if (order > 0) { 12881 // non-zero order, enable ordering 12882 mOrderResult.put(packageName, new Pair<>(order, res)); 12883 } 12884 return responseObj; 12885 } 12886 12887 @Override 12888 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12889 // only do work if ordering is enabled [most of the time it won't be] 12890 if (mOrderResult.size() == 0) { 12891 return; 12892 } 12893 int resultSize = results.size(); 12894 for (int i = 0; i < resultSize; i++) { 12895 final InstantAppResolveInfo info = results.get(i).resolveInfo; 12896 final String packageName = info.getPackageName(); 12897 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 12898 if (savedInfo == null) { 12899 // package doesn't having ordering 12900 continue; 12901 } 12902 if (savedInfo.second == info) { 12903 // circled back to the highest ordered item; remove from order list 12904 mOrderResult.remove(packageName); 12905 if (mOrderResult.size() == 0) { 12906 // no more ordered items 12907 break; 12908 } 12909 continue; 12910 } 12911 // item has a worse order, remove it from the result list 12912 results.remove(i); 12913 resultSize--; 12914 i--; 12915 } 12916 } 12917 } 12918 12919 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12920 new Comparator<ResolveInfo>() { 12921 public int compare(ResolveInfo r1, ResolveInfo r2) { 12922 int v1 = r1.priority; 12923 int v2 = r2.priority; 12924 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12925 if (v1 != v2) { 12926 return (v1 > v2) ? -1 : 1; 12927 } 12928 v1 = r1.preferredOrder; 12929 v2 = r2.preferredOrder; 12930 if (v1 != v2) { 12931 return (v1 > v2) ? -1 : 1; 12932 } 12933 if (r1.isDefault != r2.isDefault) { 12934 return r1.isDefault ? -1 : 1; 12935 } 12936 v1 = r1.match; 12937 v2 = r2.match; 12938 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12939 if (v1 != v2) { 12940 return (v1 > v2) ? -1 : 1; 12941 } 12942 if (r1.system != r2.system) { 12943 return r1.system ? -1 : 1; 12944 } 12945 if (r1.activityInfo != null) { 12946 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12947 } 12948 if (r1.serviceInfo != null) { 12949 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12950 } 12951 if (r1.providerInfo != null) { 12952 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12953 } 12954 return 0; 12955 } 12956 }; 12957 12958 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12959 new Comparator<ProviderInfo>() { 12960 public int compare(ProviderInfo p1, ProviderInfo p2) { 12961 final int v1 = p1.initOrder; 12962 final int v2 = p2.initOrder; 12963 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12964 } 12965 }; 12966 12967 @Override 12968 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12969 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12970 final int[] userIds, int[] instantUserIds) { 12971 mHandler.post(new Runnable() { 12972 @Override 12973 public void run() { 12974 try { 12975 final IActivityManager am = ActivityManager.getService(); 12976 if (am == null) return; 12977 final int[] resolvedUserIds; 12978 if (userIds == null) { 12979 resolvedUserIds = am.getRunningUserIds(); 12980 } else { 12981 resolvedUserIds = userIds; 12982 } 12983 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 12984 resolvedUserIds, false); 12985 if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) { 12986 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 12987 instantUserIds, true); 12988 } 12989 } catch (RemoteException ex) { 12990 } 12991 } 12992 }); 12993 } 12994 12995 @Override 12996 public void notifyPackageAdded(String packageName) { 12997 final PackageListObserver[] observers; 12998 synchronized (mPackages) { 12999 if (mPackageListObservers.size() == 0) { 13000 return; 13001 } 13002 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13003 } 13004 for (int i = observers.length - 1; i >= 0; --i) { 13005 observers[i].onPackageAdded(packageName); 13006 } 13007 } 13008 13009 @Override 13010 public void notifyPackageRemoved(String packageName) { 13011 final PackageListObserver[] observers; 13012 synchronized (mPackages) { 13013 if (mPackageListObservers.size() == 0) { 13014 return; 13015 } 13016 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13017 } 13018 for (int i = observers.length - 1; i >= 0; --i) { 13019 observers[i].onPackageRemoved(packageName); 13020 } 13021 } 13022 13023 /** 13024 * Sends a broadcast for the given action. 13025 * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with 13026 * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows 13027 * the system and applications allowed to see instant applications to receive package 13028 * lifecycle events for instant applications. 13029 */ 13030 private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras, 13031 int flags, String targetPkg, IIntentReceiver finishedReceiver, 13032 int[] userIds, boolean isInstantApp) 13033 throws RemoteException { 13034 for (int id : userIds) { 13035 final Intent intent = new Intent(action, 13036 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13037 final String[] requiredPermissions = 13038 isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null; 13039 if (extras != null) { 13040 intent.putExtras(extras); 13041 } 13042 if (targetPkg != null) { 13043 intent.setPackage(targetPkg); 13044 } 13045 // Modify the UID when posting to other users 13046 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13047 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13048 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13049 intent.putExtra(Intent.EXTRA_UID, uid); 13050 } 13051 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13052 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13053 if (DEBUG_BROADCASTS) { 13054 RuntimeException here = new RuntimeException("here"); 13055 here.fillInStackTrace(); 13056 Slog.d(TAG, "Sending to user " + id + ": " 13057 + intent.toShortString(false, true, false, false) 13058 + " " + intent.getExtras(), here); 13059 } 13060 am.broadcastIntent(null, intent, null, finishedReceiver, 13061 0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE, 13062 null, finishedReceiver != null, false, id); 13063 } 13064 } 13065 13066 /** 13067 * Check if the external storage media is available. This is true if there 13068 * is a mounted external storage medium or if the external storage is 13069 * emulated. 13070 */ 13071 private boolean isExternalMediaAvailable() { 13072 return mMediaMounted || Environment.isExternalStorageEmulated(); 13073 } 13074 13075 @Override 13076 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13077 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 13078 return null; 13079 } 13080 if (!isExternalMediaAvailable()) { 13081 // If the external storage is no longer mounted at this point, 13082 // the caller may not have been able to delete all of this 13083 // packages files and can not delete any more. Bail. 13084 return null; 13085 } 13086 synchronized (mPackages) { 13087 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13088 if (lastPackage != null) { 13089 pkgs.remove(lastPackage); 13090 } 13091 if (pkgs.size() > 0) { 13092 return pkgs.get(0); 13093 } 13094 } 13095 return null; 13096 } 13097 13098 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13099 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13100 userId, andCode ? 1 : 0, packageName); 13101 if (mSystemReady) { 13102 msg.sendToTarget(); 13103 } else { 13104 if (mPostSystemReadyMessages == null) { 13105 mPostSystemReadyMessages = new ArrayList<>(); 13106 } 13107 mPostSystemReadyMessages.add(msg); 13108 } 13109 } 13110 13111 void startCleaningPackages() { 13112 // reader 13113 if (!isExternalMediaAvailable()) { 13114 return; 13115 } 13116 synchronized (mPackages) { 13117 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13118 return; 13119 } 13120 } 13121 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13122 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13123 IActivityManager am = ActivityManager.getService(); 13124 if (am != null) { 13125 int dcsUid = -1; 13126 synchronized (mPackages) { 13127 if (!mDefaultContainerWhitelisted) { 13128 mDefaultContainerWhitelisted = true; 13129 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13130 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13131 } 13132 } 13133 try { 13134 if (dcsUid > 0) { 13135 am.backgroundWhitelistUid(dcsUid); 13136 } 13137 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13138 UserHandle.USER_SYSTEM); 13139 } catch (RemoteException e) { 13140 } 13141 } 13142 } 13143 13144 /** 13145 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13146 * it is acting on behalf on an enterprise or the user). 13147 * 13148 * Note that the ordering of the conditionals in this method is important. The checks we perform 13149 * are as follows, in this order: 13150 * 13151 * 1) If the install is being performed by a system app, we can trust the app to have set the 13152 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13153 * what it is. 13154 * 2) If the install is being performed by a device or profile owner app, the install reason 13155 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13156 * set the install reason correctly. If the app targets an older SDK version where install 13157 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13158 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13159 * 3) In all other cases, the install is being performed by a regular app that is neither part 13160 * of the system nor a device or profile owner. We have no reason to believe that this app is 13161 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13162 * set to enterprise policy and if so, change it to unknown instead. 13163 */ 13164 private int fixUpInstallReason(String installerPackageName, int installerUid, 13165 int installReason) { 13166 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13167 == PERMISSION_GRANTED) { 13168 // If the install is being performed by a system app, we trust that app to have set the 13169 // install reason correctly. 13170 return installReason; 13171 } 13172 13173 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13174 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13175 if (dpm != null) { 13176 ComponentName owner = null; 13177 try { 13178 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13179 if (owner == null) { 13180 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13181 } 13182 } catch (RemoteException e) { 13183 } 13184 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13185 // If the install is being performed by a device or profile owner, the install 13186 // reason should be enterprise policy. 13187 return PackageManager.INSTALL_REASON_POLICY; 13188 } 13189 } 13190 13191 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13192 // If the install is being performed by a regular app (i.e. neither system app nor 13193 // device or profile owner), we have no reason to believe that the app is acting on 13194 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13195 // change it to unknown instead. 13196 return PackageManager.INSTALL_REASON_UNKNOWN; 13197 } 13198 13199 // If the install is being performed by a regular app and the install reason was set to any 13200 // value but enterprise policy, leave the install reason unchanged. 13201 return installReason; 13202 } 13203 13204 void installStage(String packageName, File stagedDir, 13205 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13206 String installerPackageName, int installerUid, UserHandle user, 13207 Certificate[][] certificates) { 13208 if (DEBUG_EPHEMERAL) { 13209 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13210 Slog.d(TAG, "Ephemeral install of " + packageName); 13211 } 13212 } 13213 final VerificationInfo verificationInfo = new VerificationInfo( 13214 sessionParams.originatingUri, sessionParams.referrerUri, 13215 sessionParams.originatingUid, installerUid); 13216 13217 final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir); 13218 13219 final Message msg = mHandler.obtainMessage(INIT_COPY); 13220 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13221 sessionParams.installReason); 13222 final InstallParams params = new InstallParams(origin, null, observer, 13223 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13224 verificationInfo, user, sessionParams.abiOverride, 13225 sessionParams.grantedRuntimePermissions, certificates, installReason); 13226 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13227 msg.obj = params; 13228 13229 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13230 System.identityHashCode(msg.obj)); 13231 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13232 System.identityHashCode(msg.obj)); 13233 13234 mHandler.sendMessage(msg); 13235 } 13236 13237 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13238 int userId) { 13239 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13240 final boolean isInstantApp = pkgSetting.getInstantApp(userId); 13241 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 13242 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 13243 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 13244 false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds); 13245 13246 // Send a session commit broadcast 13247 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 13248 info.installReason = pkgSetting.getInstallReason(userId); 13249 info.appPackageName = packageName; 13250 sendSessionCommitBroadcast(info, userId); 13251 } 13252 13253 @Override 13254 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 13255 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) { 13256 if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) { 13257 return; 13258 } 13259 Bundle extras = new Bundle(1); 13260 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13261 final int uid = UserHandle.getUid( 13262 (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId); 13263 extras.putInt(Intent.EXTRA_UID, uid); 13264 13265 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13266 packageName, extras, 0, null, null, userIds, instantUserIds); 13267 if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) { 13268 mHandler.post(() -> { 13269 for (int userId : userIds) { 13270 sendBootCompletedBroadcastToSystemApp( 13271 packageName, includeStopped, userId); 13272 } 13273 } 13274 ); 13275 } 13276 } 13277 13278 /** 13279 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13280 * automatically without needing an explicit launch. 13281 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13282 */ 13283 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 13284 int userId) { 13285 // If user is not running, the app didn't miss any broadcast 13286 if (!mUserManagerInternal.isUserRunning(userId)) { 13287 return; 13288 } 13289 final IActivityManager am = ActivityManager.getService(); 13290 try { 13291 // Deliver LOCKED_BOOT_COMPLETED first 13292 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13293 .setPackage(packageName); 13294 if (includeStopped) { 13295 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13296 } 13297 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13298 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13299 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13300 13301 // Deliver BOOT_COMPLETED only if user is unlocked 13302 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13303 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13304 if (includeStopped) { 13305 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13306 } 13307 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13308 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13309 } 13310 } catch (RemoteException e) { 13311 throw e.rethrowFromSystemServer(); 13312 } 13313 } 13314 13315 @Override 13316 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13317 int userId) { 13318 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13319 PackageSetting pkgSetting; 13320 final int callingUid = Binder.getCallingUid(); 13321 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13322 true /* requireFullPermission */, true /* checkShell */, 13323 "setApplicationHiddenSetting for user " + userId); 13324 13325 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13326 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13327 return false; 13328 } 13329 13330 long callingId = Binder.clearCallingIdentity(); 13331 try { 13332 boolean sendAdded = false; 13333 boolean sendRemoved = false; 13334 // writer 13335 synchronized (mPackages) { 13336 pkgSetting = mSettings.mPackages.get(packageName); 13337 if (pkgSetting == null) { 13338 return false; 13339 } 13340 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13341 return false; 13342 } 13343 // Do not allow "android" is being disabled 13344 if ("android".equals(packageName)) { 13345 Slog.w(TAG, "Cannot hide package: android"); 13346 return false; 13347 } 13348 // Cannot hide static shared libs as they are considered 13349 // a part of the using app (emulating static linking). Also 13350 // static libs are installed always on internal storage. 13351 PackageParser.Package pkg = mPackages.get(packageName); 13352 if (pkg != null && pkg.staticSharedLibName != null) { 13353 Slog.w(TAG, "Cannot hide package: " + packageName 13354 + " providing static shared library: " 13355 + pkg.staticSharedLibName); 13356 return false; 13357 } 13358 // Only allow protected packages to hide themselves. 13359 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 13360 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13361 Slog.w(TAG, "Not hiding protected package: " + packageName); 13362 return false; 13363 } 13364 13365 if (pkgSetting.getHidden(userId) != hidden) { 13366 pkgSetting.setHidden(hidden, userId); 13367 mSettings.writePackageRestrictionsLPr(userId); 13368 if (hidden) { 13369 sendRemoved = true; 13370 } else { 13371 sendAdded = true; 13372 } 13373 } 13374 } 13375 if (sendAdded) { 13376 sendPackageAddedForUser(packageName, pkgSetting, userId); 13377 return true; 13378 } 13379 if (sendRemoved) { 13380 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13381 "hiding pkg"); 13382 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13383 return true; 13384 } 13385 } finally { 13386 Binder.restoreCallingIdentity(callingId); 13387 } 13388 return false; 13389 } 13390 13391 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13392 int userId) { 13393 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13394 info.removedPackage = packageName; 13395 info.installerPackageName = pkgSetting.installerPackageName; 13396 info.removedUsers = new int[] {userId}; 13397 info.broadcastUsers = new int[] {userId}; 13398 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13399 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13400 } 13401 13402 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13403 if (pkgList.length > 0) { 13404 Bundle extras = new Bundle(1); 13405 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13406 13407 sendPackageBroadcast( 13408 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13409 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13410 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13411 new int[] {userId}, null); 13412 } 13413 } 13414 13415 /** 13416 * Returns true if application is not found or there was an error. Otherwise it returns 13417 * the hidden state of the package for the given user. 13418 */ 13419 @Override 13420 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13421 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13422 final int callingUid = Binder.getCallingUid(); 13423 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13424 true /* requireFullPermission */, false /* checkShell */, 13425 "getApplicationHidden for user " + userId); 13426 PackageSetting ps; 13427 long callingId = Binder.clearCallingIdentity(); 13428 try { 13429 // writer 13430 synchronized (mPackages) { 13431 ps = mSettings.mPackages.get(packageName); 13432 if (ps == null) { 13433 return true; 13434 } 13435 if (filterAppAccessLPr(ps, callingUid, userId)) { 13436 return true; 13437 } 13438 return ps.getHidden(userId); 13439 } 13440 } finally { 13441 Binder.restoreCallingIdentity(callingId); 13442 } 13443 } 13444 13445 /** 13446 * @hide 13447 */ 13448 @Override 13449 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13450 int installReason) { 13451 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13452 null); 13453 PackageSetting pkgSetting; 13454 final int callingUid = Binder.getCallingUid(); 13455 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13456 true /* requireFullPermission */, true /* checkShell */, 13457 "installExistingPackage for user " + userId); 13458 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13459 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13460 } 13461 13462 long callingId = Binder.clearCallingIdentity(); 13463 try { 13464 boolean installed = false; 13465 final boolean instantApp = 13466 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13467 final boolean fullApp = 13468 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13469 13470 // writer 13471 synchronized (mPackages) { 13472 pkgSetting = mSettings.mPackages.get(packageName); 13473 if (pkgSetting == null) { 13474 return PackageManager.INSTALL_FAILED_INVALID_URI; 13475 } 13476 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 13477 // only allow the existing package to be used if it's installed as a full 13478 // application for at least one user 13479 boolean installAllowed = false; 13480 for (int checkUserId : sUserManager.getUserIds()) { 13481 installAllowed = !pkgSetting.getInstantApp(checkUserId); 13482 if (installAllowed) { 13483 break; 13484 } 13485 } 13486 if (!installAllowed) { 13487 return PackageManager.INSTALL_FAILED_INVALID_URI; 13488 } 13489 } 13490 if (!pkgSetting.getInstalled(userId)) { 13491 pkgSetting.setInstalled(true, userId); 13492 pkgSetting.setHidden(false, userId); 13493 pkgSetting.setInstallReason(installReason, userId); 13494 mSettings.writePackageRestrictionsLPr(userId); 13495 mSettings.writeKernelMappingLPr(pkgSetting); 13496 installed = true; 13497 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13498 // upgrade app from instant to full; we don't allow app downgrade 13499 installed = true; 13500 } 13501 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13502 } 13503 13504 if (installed) { 13505 if (pkgSetting.pkg != null) { 13506 synchronized (mInstallLock) { 13507 // We don't need to freeze for a brand new install 13508 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13509 } 13510 } 13511 sendPackageAddedForUser(packageName, pkgSetting, userId); 13512 synchronized (mPackages) { 13513 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 13514 } 13515 } 13516 } finally { 13517 Binder.restoreCallingIdentity(callingId); 13518 } 13519 13520 return PackageManager.INSTALL_SUCCEEDED; 13521 } 13522 13523 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13524 boolean instantApp, boolean fullApp) { 13525 // no state specified; do nothing 13526 if (!instantApp && !fullApp) { 13527 return; 13528 } 13529 if (userId != UserHandle.USER_ALL) { 13530 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13531 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13532 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13533 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13534 } 13535 } else { 13536 for (int currentUserId : sUserManager.getUserIds()) { 13537 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13538 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13539 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13540 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13541 } 13542 } 13543 } 13544 } 13545 13546 boolean isUserRestricted(int userId, String restrictionKey) { 13547 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13548 if (restrictions.getBoolean(restrictionKey, false)) { 13549 Log.w(TAG, "User is restricted: " + restrictionKey); 13550 return true; 13551 } 13552 return false; 13553 } 13554 13555 @Override 13556 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13557 int userId) { 13558 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13559 final int callingUid = Binder.getCallingUid(); 13560 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13561 true /* requireFullPermission */, true /* checkShell */, 13562 "setPackagesSuspended for user " + userId); 13563 13564 if (ArrayUtils.isEmpty(packageNames)) { 13565 return packageNames; 13566 } 13567 13568 // List of package names for whom the suspended state has changed. 13569 List<String> changedPackages = new ArrayList<>(packageNames.length); 13570 // List of package names for whom the suspended state is not set as requested in this 13571 // method. 13572 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13573 long callingId = Binder.clearCallingIdentity(); 13574 try { 13575 for (int i = 0; i < packageNames.length; i++) { 13576 String packageName = packageNames[i]; 13577 boolean changed = false; 13578 final int appId; 13579 synchronized (mPackages) { 13580 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13581 if (pkgSetting == null 13582 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13583 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13584 + "\". Skipping suspending/un-suspending."); 13585 unactionedPackages.add(packageName); 13586 continue; 13587 } 13588 appId = pkgSetting.appId; 13589 if (pkgSetting.getSuspended(userId) != suspended) { 13590 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13591 unactionedPackages.add(packageName); 13592 continue; 13593 } 13594 pkgSetting.setSuspended(suspended, userId); 13595 mSettings.writePackageRestrictionsLPr(userId); 13596 changed = true; 13597 changedPackages.add(packageName); 13598 } 13599 } 13600 13601 if (changed && suspended) { 13602 killApplication(packageName, UserHandle.getUid(userId, appId), 13603 "suspending package"); 13604 } 13605 } 13606 } finally { 13607 Binder.restoreCallingIdentity(callingId); 13608 } 13609 13610 if (!changedPackages.isEmpty()) { 13611 sendPackagesSuspendedForUser(changedPackages.toArray( 13612 new String[changedPackages.size()]), userId, suspended); 13613 } 13614 13615 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13616 } 13617 13618 @Override 13619 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13620 final int callingUid = Binder.getCallingUid(); 13621 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13622 true /* requireFullPermission */, false /* checkShell */, 13623 "isPackageSuspendedForUser for user " + userId); 13624 synchronized (mPackages) { 13625 final PackageSetting ps = mSettings.mPackages.get(packageName); 13626 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 13627 throw new IllegalArgumentException("Unknown target package: " + packageName); 13628 } 13629 return ps.getSuspended(userId); 13630 } 13631 } 13632 13633 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13634 if (isPackageDeviceAdmin(packageName, userId)) { 13635 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13636 + "\": has an active device admin"); 13637 return false; 13638 } 13639 13640 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13641 if (packageName.equals(activeLauncherPackageName)) { 13642 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13643 + "\": contains the active launcher"); 13644 return false; 13645 } 13646 13647 if (packageName.equals(mRequiredInstallerPackage)) { 13648 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13649 + "\": required for package installation"); 13650 return false; 13651 } 13652 13653 if (packageName.equals(mRequiredUninstallerPackage)) { 13654 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13655 + "\": required for package uninstallation"); 13656 return false; 13657 } 13658 13659 if (packageName.equals(mRequiredVerifierPackage)) { 13660 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13661 + "\": required for package verification"); 13662 return false; 13663 } 13664 13665 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13666 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13667 + "\": is the default dialer"); 13668 return false; 13669 } 13670 13671 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13672 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13673 + "\": protected package"); 13674 return false; 13675 } 13676 13677 // Cannot suspend static shared libs as they are considered 13678 // a part of the using app (emulating static linking). Also 13679 // static libs are installed always on internal storage. 13680 PackageParser.Package pkg = mPackages.get(packageName); 13681 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13682 Slog.w(TAG, "Cannot suspend package: " + packageName 13683 + " providing static shared library: " 13684 + pkg.staticSharedLibName); 13685 return false; 13686 } 13687 13688 return true; 13689 } 13690 13691 private String getActiveLauncherPackageName(int userId) { 13692 Intent intent = new Intent(Intent.ACTION_MAIN); 13693 intent.addCategory(Intent.CATEGORY_HOME); 13694 ResolveInfo resolveInfo = resolveIntent( 13695 intent, 13696 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13697 PackageManager.MATCH_DEFAULT_ONLY, 13698 userId); 13699 13700 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13701 } 13702 13703 private String getDefaultDialerPackageName(int userId) { 13704 synchronized (mPackages) { 13705 return mSettings.getDefaultDialerPackageNameLPw(userId); 13706 } 13707 } 13708 13709 @Override 13710 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13711 mContext.enforceCallingOrSelfPermission( 13712 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13713 "Only package verification agents can verify applications"); 13714 13715 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13716 final PackageVerificationResponse response = new PackageVerificationResponse( 13717 verificationCode, Binder.getCallingUid()); 13718 msg.arg1 = id; 13719 msg.obj = response; 13720 mHandler.sendMessage(msg); 13721 } 13722 13723 @Override 13724 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13725 long millisecondsToDelay) { 13726 mContext.enforceCallingOrSelfPermission( 13727 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13728 "Only package verification agents can extend verification timeouts"); 13729 13730 final PackageVerificationState state = mPendingVerification.get(id); 13731 final PackageVerificationResponse response = new PackageVerificationResponse( 13732 verificationCodeAtTimeout, Binder.getCallingUid()); 13733 13734 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13735 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13736 } 13737 if (millisecondsToDelay < 0) { 13738 millisecondsToDelay = 0; 13739 } 13740 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13741 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13742 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13743 } 13744 13745 if ((state != null) && !state.timeoutExtended()) { 13746 state.extendTimeout(); 13747 13748 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13749 msg.arg1 = id; 13750 msg.obj = response; 13751 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13752 } 13753 } 13754 13755 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13756 int verificationCode, UserHandle user) { 13757 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13758 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13759 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13760 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13761 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13762 13763 mContext.sendBroadcastAsUser(intent, user, 13764 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13765 } 13766 13767 private ComponentName matchComponentForVerifier(String packageName, 13768 List<ResolveInfo> receivers) { 13769 ActivityInfo targetReceiver = null; 13770 13771 final int NR = receivers.size(); 13772 for (int i = 0; i < NR; i++) { 13773 final ResolveInfo info = receivers.get(i); 13774 if (info.activityInfo == null) { 13775 continue; 13776 } 13777 13778 if (packageName.equals(info.activityInfo.packageName)) { 13779 targetReceiver = info.activityInfo; 13780 break; 13781 } 13782 } 13783 13784 if (targetReceiver == null) { 13785 return null; 13786 } 13787 13788 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13789 } 13790 13791 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13792 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13793 if (pkgInfo.verifiers.length == 0) { 13794 return null; 13795 } 13796 13797 final int N = pkgInfo.verifiers.length; 13798 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13799 for (int i = 0; i < N; i++) { 13800 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13801 13802 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13803 receivers); 13804 if (comp == null) { 13805 continue; 13806 } 13807 13808 final int verifierUid = getUidForVerifier(verifierInfo); 13809 if (verifierUid == -1) { 13810 continue; 13811 } 13812 13813 if (DEBUG_VERIFY) { 13814 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13815 + " with the correct signature"); 13816 } 13817 sufficientVerifiers.add(comp); 13818 verificationState.addSufficientVerifier(verifierUid); 13819 } 13820 13821 return sufficientVerifiers; 13822 } 13823 13824 private int getUidForVerifier(VerifierInfo verifierInfo) { 13825 synchronized (mPackages) { 13826 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13827 if (pkg == null) { 13828 return -1; 13829 } else if (pkg.mSignatures.length != 1) { 13830 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13831 + " has more than one signature; ignoring"); 13832 return -1; 13833 } 13834 13835 /* 13836 * If the public key of the package's signature does not match 13837 * our expected public key, then this is a different package and 13838 * we should skip. 13839 */ 13840 13841 final byte[] expectedPublicKey; 13842 try { 13843 final Signature verifierSig = pkg.mSignatures[0]; 13844 final PublicKey publicKey = verifierSig.getPublicKey(); 13845 expectedPublicKey = publicKey.getEncoded(); 13846 } catch (CertificateException e) { 13847 return -1; 13848 } 13849 13850 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13851 13852 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13853 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13854 + " does not have the expected public key; ignoring"); 13855 return -1; 13856 } 13857 13858 return pkg.applicationInfo.uid; 13859 } 13860 } 13861 13862 @Override 13863 public void finishPackageInstall(int token, boolean didLaunch) { 13864 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13865 13866 if (DEBUG_INSTALL) { 13867 Slog.v(TAG, "BM finishing package install for " + token); 13868 } 13869 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13870 13871 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13872 mHandler.sendMessage(msg); 13873 } 13874 13875 /** 13876 * Get the verification agent timeout. Used for both the APK verifier and the 13877 * intent filter verifier. 13878 * 13879 * @return verification timeout in milliseconds 13880 */ 13881 private long getVerificationTimeout() { 13882 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13883 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13884 DEFAULT_VERIFICATION_TIMEOUT); 13885 } 13886 13887 /** 13888 * Get the default verification agent response code. 13889 * 13890 * @return default verification response code 13891 */ 13892 private int getDefaultVerificationResponse(UserHandle user) { 13893 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 13894 return PackageManager.VERIFICATION_REJECT; 13895 } 13896 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13897 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13898 DEFAULT_VERIFICATION_RESPONSE); 13899 } 13900 13901 /** 13902 * Check whether or not package verification has been enabled. 13903 * 13904 * @return true if verification should be performed 13905 */ 13906 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 13907 if (!DEFAULT_VERIFY_ENABLE) { 13908 return false; 13909 } 13910 13911 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13912 13913 // Check if installing from ADB 13914 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13915 // Do not run verification in a test harness environment 13916 if (ActivityManager.isRunningInTestHarness()) { 13917 return false; 13918 } 13919 if (ensureVerifyAppsEnabled) { 13920 return true; 13921 } 13922 // Check if the developer does not want package verification for ADB installs 13923 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13924 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13925 return false; 13926 } 13927 } else { 13928 // only when not installed from ADB, skip verification for instant apps when 13929 // the installer and verifier are the same. 13930 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13931 if (mInstantAppInstallerActivity != null 13932 && mInstantAppInstallerActivity.packageName.equals( 13933 mRequiredVerifierPackage)) { 13934 try { 13935 mContext.getSystemService(AppOpsManager.class) 13936 .checkPackage(installerUid, mRequiredVerifierPackage); 13937 if (DEBUG_VERIFY) { 13938 Slog.i(TAG, "disable verification for instant app"); 13939 } 13940 return false; 13941 } catch (SecurityException ignore) { } 13942 } 13943 } 13944 } 13945 13946 if (ensureVerifyAppsEnabled) { 13947 return true; 13948 } 13949 13950 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13951 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13952 } 13953 13954 @Override 13955 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13956 throws RemoteException { 13957 mContext.enforceCallingOrSelfPermission( 13958 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13959 "Only intentfilter verification agents can verify applications"); 13960 13961 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13962 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13963 Binder.getCallingUid(), verificationCode, failedDomains); 13964 msg.arg1 = id; 13965 msg.obj = response; 13966 mHandler.sendMessage(msg); 13967 } 13968 13969 @Override 13970 public int getIntentVerificationStatus(String packageName, int userId) { 13971 final int callingUid = Binder.getCallingUid(); 13972 if (UserHandle.getUserId(callingUid) != userId) { 13973 mContext.enforceCallingOrSelfPermission( 13974 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13975 "getIntentVerificationStatus" + userId); 13976 } 13977 if (getInstantAppPackageName(callingUid) != null) { 13978 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 13979 } 13980 synchronized (mPackages) { 13981 final PackageSetting ps = mSettings.mPackages.get(packageName); 13982 if (ps == null 13983 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 13984 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 13985 } 13986 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13987 } 13988 } 13989 13990 @Override 13991 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13992 mContext.enforceCallingOrSelfPermission( 13993 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13994 13995 boolean result = false; 13996 synchronized (mPackages) { 13997 final PackageSetting ps = mSettings.mPackages.get(packageName); 13998 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 13999 return false; 14000 } 14001 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14002 } 14003 if (result) { 14004 scheduleWritePackageRestrictionsLocked(userId); 14005 } 14006 return result; 14007 } 14008 14009 @Override 14010 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14011 String packageName) { 14012 final int callingUid = Binder.getCallingUid(); 14013 if (getInstantAppPackageName(callingUid) != null) { 14014 return ParceledListSlice.emptyList(); 14015 } 14016 synchronized (mPackages) { 14017 final PackageSetting ps = mSettings.mPackages.get(packageName); 14018 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14019 return ParceledListSlice.emptyList(); 14020 } 14021 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14022 } 14023 } 14024 14025 @Override 14026 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14027 if (TextUtils.isEmpty(packageName)) { 14028 return ParceledListSlice.emptyList(); 14029 } 14030 final int callingUid = Binder.getCallingUid(); 14031 final int callingUserId = UserHandle.getUserId(callingUid); 14032 synchronized (mPackages) { 14033 PackageParser.Package pkg = mPackages.get(packageName); 14034 if (pkg == null || pkg.activities == null) { 14035 return ParceledListSlice.emptyList(); 14036 } 14037 if (pkg.mExtras == null) { 14038 return ParceledListSlice.emptyList(); 14039 } 14040 final PackageSetting ps = (PackageSetting) pkg.mExtras; 14041 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 14042 return ParceledListSlice.emptyList(); 14043 } 14044 final int count = pkg.activities.size(); 14045 ArrayList<IntentFilter> result = new ArrayList<>(); 14046 for (int n=0; n<count; n++) { 14047 PackageParser.Activity activity = pkg.activities.get(n); 14048 if (activity.intents != null && activity.intents.size() > 0) { 14049 result.addAll(activity.intents); 14050 } 14051 } 14052 return new ParceledListSlice<>(result); 14053 } 14054 } 14055 14056 @Override 14057 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14058 mContext.enforceCallingOrSelfPermission( 14059 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14060 if (UserHandle.getCallingUserId() != userId) { 14061 mContext.enforceCallingOrSelfPermission( 14062 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14063 } 14064 14065 synchronized (mPackages) { 14066 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14067 if (packageName != null) { 14068 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser( 14069 packageName, userId); 14070 } 14071 return result; 14072 } 14073 } 14074 14075 @Override 14076 public String getDefaultBrowserPackageName(int userId) { 14077 if (UserHandle.getCallingUserId() != userId) { 14078 mContext.enforceCallingOrSelfPermission( 14079 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14080 } 14081 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14082 return null; 14083 } 14084 synchronized (mPackages) { 14085 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14086 } 14087 } 14088 14089 /** 14090 * Get the "allow unknown sources" setting. 14091 * 14092 * @return the current "allow unknown sources" setting 14093 */ 14094 private int getUnknownSourcesSettings() { 14095 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14096 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14097 -1); 14098 } 14099 14100 @Override 14101 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14102 final int callingUid = Binder.getCallingUid(); 14103 if (getInstantAppPackageName(callingUid) != null) { 14104 return; 14105 } 14106 // writer 14107 synchronized (mPackages) { 14108 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14109 if (targetPackageSetting == null 14110 || filterAppAccessLPr( 14111 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 14112 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14113 } 14114 14115 PackageSetting installerPackageSetting; 14116 if (installerPackageName != null) { 14117 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14118 if (installerPackageSetting == null) { 14119 throw new IllegalArgumentException("Unknown installer package: " 14120 + installerPackageName); 14121 } 14122 } else { 14123 installerPackageSetting = null; 14124 } 14125 14126 Signature[] callerSignature; 14127 Object obj = mSettings.getUserIdLPr(callingUid); 14128 if (obj != null) { 14129 if (obj instanceof SharedUserSetting) { 14130 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 14131 } else if (obj instanceof PackageSetting) { 14132 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 14133 } else { 14134 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 14135 } 14136 } else { 14137 throw new SecurityException("Unknown calling UID: " + callingUid); 14138 } 14139 14140 // Verify: can't set installerPackageName to a package that is 14141 // not signed with the same cert as the caller. 14142 if (installerPackageSetting != null) { 14143 if (compareSignatures(callerSignature, 14144 installerPackageSetting.signatures.mSignatures) 14145 != PackageManager.SIGNATURE_MATCH) { 14146 throw new SecurityException( 14147 "Caller does not have same cert as new installer package " 14148 + installerPackageName); 14149 } 14150 } 14151 14152 // Verify: if target already has an installer package, it must 14153 // be signed with the same cert as the caller. 14154 if (targetPackageSetting.installerPackageName != null) { 14155 PackageSetting setting = mSettings.mPackages.get( 14156 targetPackageSetting.installerPackageName); 14157 // If the currently set package isn't valid, then it's always 14158 // okay to change it. 14159 if (setting != null) { 14160 if (compareSignatures(callerSignature, 14161 setting.signatures.mSignatures) 14162 != PackageManager.SIGNATURE_MATCH) { 14163 throw new SecurityException( 14164 "Caller does not have same cert as old installer package " 14165 + targetPackageSetting.installerPackageName); 14166 } 14167 } 14168 } 14169 14170 // Okay! 14171 targetPackageSetting.installerPackageName = installerPackageName; 14172 if (installerPackageName != null) { 14173 mSettings.mInstallerPackages.add(installerPackageName); 14174 } 14175 scheduleWriteSettingsLocked(); 14176 } 14177 } 14178 14179 @Override 14180 public void setApplicationCategoryHint(String packageName, int categoryHint, 14181 String callerPackageName) { 14182 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14183 throw new SecurityException("Instant applications don't have access to this method"); 14184 } 14185 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14186 callerPackageName); 14187 synchronized (mPackages) { 14188 PackageSetting ps = mSettings.mPackages.get(packageName); 14189 if (ps == null) { 14190 throw new IllegalArgumentException("Unknown target package " + packageName); 14191 } 14192 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14193 throw new IllegalArgumentException("Unknown target package " + packageName); 14194 } 14195 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14196 throw new IllegalArgumentException("Calling package " + callerPackageName 14197 + " is not installer for " + packageName); 14198 } 14199 14200 if (ps.categoryHint != categoryHint) { 14201 ps.categoryHint = categoryHint; 14202 scheduleWriteSettingsLocked(); 14203 } 14204 } 14205 } 14206 14207 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14208 // Queue up an async operation since the package installation may take a little while. 14209 mHandler.post(new Runnable() { 14210 public void run() { 14211 mHandler.removeCallbacks(this); 14212 // Result object to be returned 14213 PackageInstalledInfo res = new PackageInstalledInfo(); 14214 res.setReturnCode(currentStatus); 14215 res.uid = -1; 14216 res.pkg = null; 14217 res.removedInfo = null; 14218 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14219 args.doPreInstall(res.returnCode); 14220 synchronized (mInstallLock) { 14221 installPackageTracedLI(args, res); 14222 } 14223 args.doPostInstall(res.returnCode, res.uid); 14224 } 14225 14226 // A restore should be performed at this point if (a) the install 14227 // succeeded, (b) the operation is not an update, and (c) the new 14228 // package has not opted out of backup participation. 14229 final boolean update = res.removedInfo != null 14230 && res.removedInfo.removedPackage != null; 14231 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14232 boolean doRestore = !update 14233 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14234 14235 // Set up the post-install work request bookkeeping. This will be used 14236 // and cleaned up by the post-install event handling regardless of whether 14237 // there's a restore pass performed. Token values are >= 1. 14238 int token; 14239 if (mNextInstallToken < 0) mNextInstallToken = 1; 14240 token = mNextInstallToken++; 14241 14242 PostInstallData data = new PostInstallData(args, res); 14243 mRunningInstalls.put(token, data); 14244 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14245 14246 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14247 // Pass responsibility to the Backup Manager. It will perform a 14248 // restore if appropriate, then pass responsibility back to the 14249 // Package Manager to run the post-install observer callbacks 14250 // and broadcasts. 14251 IBackupManager bm = IBackupManager.Stub.asInterface( 14252 ServiceManager.getService(Context.BACKUP_SERVICE)); 14253 if (bm != null) { 14254 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14255 + " to BM for possible restore"); 14256 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14257 try { 14258 // TODO: http://b/22388012 14259 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14260 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14261 } else { 14262 doRestore = false; 14263 } 14264 } catch (RemoteException e) { 14265 // can't happen; the backup manager is local 14266 } catch (Exception e) { 14267 Slog.e(TAG, "Exception trying to enqueue restore", e); 14268 doRestore = false; 14269 } 14270 } else { 14271 Slog.e(TAG, "Backup Manager not found!"); 14272 doRestore = false; 14273 } 14274 } 14275 14276 if (!doRestore) { 14277 // No restore possible, or the Backup Manager was mysteriously not 14278 // available -- just fire the post-install work request directly. 14279 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14280 14281 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14282 14283 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14284 mHandler.sendMessage(msg); 14285 } 14286 } 14287 }); 14288 } 14289 14290 /** 14291 * Callback from PackageSettings whenever an app is first transitioned out of the 14292 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14293 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14294 * here whether the app is the target of an ongoing install, and only send the 14295 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14296 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14297 * handling. 14298 */ 14299 void notifyFirstLaunch(final String packageName, final String installerPackage, 14300 final int userId) { 14301 // Serialize this with the rest of the install-process message chain. In the 14302 // restore-at-install case, this Runnable will necessarily run before the 14303 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14304 // are coherent. In the non-restore case, the app has already completed install 14305 // and been launched through some other means, so it is not in a problematic 14306 // state for observers to see the FIRST_LAUNCH signal. 14307 mHandler.post(new Runnable() { 14308 @Override 14309 public void run() { 14310 for (int i = 0; i < mRunningInstalls.size(); i++) { 14311 final PostInstallData data = mRunningInstalls.valueAt(i); 14312 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14313 continue; 14314 } 14315 if (packageName.equals(data.res.pkg.applicationInfo.packageName)) { 14316 // right package; but is it for the right user? 14317 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14318 if (userId == data.res.newUsers[uIndex]) { 14319 if (DEBUG_BACKUP) { 14320 Slog.i(TAG, "Package " + packageName 14321 + " being restored so deferring FIRST_LAUNCH"); 14322 } 14323 return; 14324 } 14325 } 14326 } 14327 } 14328 // didn't find it, so not being restored 14329 if (DEBUG_BACKUP) { 14330 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH"); 14331 } 14332 final boolean isInstantApp = isInstantApp(packageName, userId); 14333 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 14334 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 14335 sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds); 14336 } 14337 }); 14338 } 14339 14340 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, 14341 int[] userIds, int[] instantUserIds) { 14342 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14343 installerPkg, null, userIds, instantUserIds); 14344 } 14345 14346 private abstract class HandlerParams { 14347 private static final int MAX_RETRIES = 4; 14348 14349 /** 14350 * Number of times startCopy() has been attempted and had a non-fatal 14351 * error. 14352 */ 14353 private int mRetries = 0; 14354 14355 /** User handle for the user requesting the information or installation. */ 14356 private final UserHandle mUser; 14357 String traceMethod; 14358 int traceCookie; 14359 14360 HandlerParams(UserHandle user) { 14361 mUser = user; 14362 } 14363 14364 UserHandle getUser() { 14365 return mUser; 14366 } 14367 14368 HandlerParams setTraceMethod(String traceMethod) { 14369 this.traceMethod = traceMethod; 14370 return this; 14371 } 14372 14373 HandlerParams setTraceCookie(int traceCookie) { 14374 this.traceCookie = traceCookie; 14375 return this; 14376 } 14377 14378 final boolean startCopy() { 14379 boolean res; 14380 try { 14381 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14382 14383 if (++mRetries > MAX_RETRIES) { 14384 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14385 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14386 handleServiceError(); 14387 return false; 14388 } else { 14389 handleStartCopy(); 14390 res = true; 14391 } 14392 } catch (RemoteException e) { 14393 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14394 mHandler.sendEmptyMessage(MCS_RECONNECT); 14395 res = false; 14396 } 14397 handleReturnCode(); 14398 return res; 14399 } 14400 14401 final void serviceError() { 14402 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14403 handleServiceError(); 14404 handleReturnCode(); 14405 } 14406 14407 abstract void handleStartCopy() throws RemoteException; 14408 abstract void handleServiceError(); 14409 abstract void handleReturnCode(); 14410 } 14411 14412 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14413 for (File path : paths) { 14414 try { 14415 mcs.clearDirectory(path.getAbsolutePath()); 14416 } catch (RemoteException e) { 14417 } 14418 } 14419 } 14420 14421 static class OriginInfo { 14422 /** 14423 * Location where install is coming from, before it has been 14424 * copied/renamed into place. This could be a single monolithic APK 14425 * file, or a cluster directory. This location may be untrusted. 14426 */ 14427 final File file; 14428 14429 /** 14430 * Flag indicating that {@link #file} or {@link #cid} has already been 14431 * staged, meaning downstream users don't need to defensively copy the 14432 * contents. 14433 */ 14434 final boolean staged; 14435 14436 /** 14437 * Flag indicating that {@link #file} or {@link #cid} is an already 14438 * installed app that is being moved. 14439 */ 14440 final boolean existing; 14441 14442 final String resolvedPath; 14443 final File resolvedFile; 14444 14445 static OriginInfo fromNothing() { 14446 return new OriginInfo(null, false, false); 14447 } 14448 14449 static OriginInfo fromUntrustedFile(File file) { 14450 return new OriginInfo(file, false, false); 14451 } 14452 14453 static OriginInfo fromExistingFile(File file) { 14454 return new OriginInfo(file, false, true); 14455 } 14456 14457 static OriginInfo fromStagedFile(File file) { 14458 return new OriginInfo(file, true, false); 14459 } 14460 14461 private OriginInfo(File file, boolean staged, boolean existing) { 14462 this.file = file; 14463 this.staged = staged; 14464 this.existing = existing; 14465 14466 if (file != null) { 14467 resolvedPath = file.getAbsolutePath(); 14468 resolvedFile = file; 14469 } else { 14470 resolvedPath = null; 14471 resolvedFile = null; 14472 } 14473 } 14474 } 14475 14476 static class MoveInfo { 14477 final int moveId; 14478 final String fromUuid; 14479 final String toUuid; 14480 final String packageName; 14481 final String dataAppName; 14482 final int appId; 14483 final String seinfo; 14484 final int targetSdkVersion; 14485 14486 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14487 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14488 this.moveId = moveId; 14489 this.fromUuid = fromUuid; 14490 this.toUuid = toUuid; 14491 this.packageName = packageName; 14492 this.dataAppName = dataAppName; 14493 this.appId = appId; 14494 this.seinfo = seinfo; 14495 this.targetSdkVersion = targetSdkVersion; 14496 } 14497 } 14498 14499 static class VerificationInfo { 14500 /** A constant used to indicate that a uid value is not present. */ 14501 public static final int NO_UID = -1; 14502 14503 /** URI referencing where the package was downloaded from. */ 14504 final Uri originatingUri; 14505 14506 /** HTTP referrer URI associated with the originatingURI. */ 14507 final Uri referrer; 14508 14509 /** UID of the application that the install request originated from. */ 14510 final int originatingUid; 14511 14512 /** UID of application requesting the install */ 14513 final int installerUid; 14514 14515 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14516 this.originatingUri = originatingUri; 14517 this.referrer = referrer; 14518 this.originatingUid = originatingUid; 14519 this.installerUid = installerUid; 14520 } 14521 } 14522 14523 class InstallParams extends HandlerParams { 14524 final OriginInfo origin; 14525 final MoveInfo move; 14526 final IPackageInstallObserver2 observer; 14527 int installFlags; 14528 final String installerPackageName; 14529 final String volumeUuid; 14530 private InstallArgs mArgs; 14531 private int mRet; 14532 final String packageAbiOverride; 14533 final String[] grantedRuntimePermissions; 14534 final VerificationInfo verificationInfo; 14535 final Certificate[][] certificates; 14536 final int installReason; 14537 14538 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14539 int installFlags, String installerPackageName, String volumeUuid, 14540 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14541 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14542 super(user); 14543 this.origin = origin; 14544 this.move = move; 14545 this.observer = observer; 14546 this.installFlags = installFlags; 14547 this.installerPackageName = installerPackageName; 14548 this.volumeUuid = volumeUuid; 14549 this.verificationInfo = verificationInfo; 14550 this.packageAbiOverride = packageAbiOverride; 14551 this.grantedRuntimePermissions = grantedPermissions; 14552 this.certificates = certificates; 14553 this.installReason = installReason; 14554 } 14555 14556 @Override 14557 public String toString() { 14558 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14559 + " file=" + origin.file + "}"; 14560 } 14561 14562 private int installLocationPolicy(PackageInfoLite pkgLite) { 14563 String packageName = pkgLite.packageName; 14564 int installLocation = pkgLite.installLocation; 14565 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14566 // reader 14567 synchronized (mPackages) { 14568 // Currently installed package which the new package is attempting to replace or 14569 // null if no such package is installed. 14570 PackageParser.Package installedPkg = mPackages.get(packageName); 14571 // Package which currently owns the data which the new package will own if installed. 14572 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14573 // will be null whereas dataOwnerPkg will contain information about the package 14574 // which was uninstalled while keeping its data. 14575 PackageParser.Package dataOwnerPkg = installedPkg; 14576 if (dataOwnerPkg == null) { 14577 PackageSetting ps = mSettings.mPackages.get(packageName); 14578 if (ps != null) { 14579 dataOwnerPkg = ps.pkg; 14580 } 14581 } 14582 14583 if (dataOwnerPkg != null) { 14584 // If installed, the package will get access to data left on the device by its 14585 // predecessor. As a security measure, this is permited only if this is not a 14586 // version downgrade or if the predecessor package is marked as debuggable and 14587 // a downgrade is explicitly requested. 14588 // 14589 // On debuggable platform builds, downgrades are permitted even for 14590 // non-debuggable packages to make testing easier. Debuggable platform builds do 14591 // not offer security guarantees and thus it's OK to disable some security 14592 // mechanisms to make debugging/testing easier on those builds. However, even on 14593 // debuggable builds downgrades of packages are permitted only if requested via 14594 // installFlags. This is because we aim to keep the behavior of debuggable 14595 // platform builds as close as possible to the behavior of non-debuggable 14596 // platform builds. 14597 final boolean downgradeRequested = 14598 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14599 final boolean packageDebuggable = 14600 (dataOwnerPkg.applicationInfo.flags 14601 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14602 final boolean downgradePermitted = 14603 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14604 if (!downgradePermitted) { 14605 try { 14606 checkDowngrade(dataOwnerPkg, pkgLite); 14607 } catch (PackageManagerException e) { 14608 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14609 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14610 } 14611 } 14612 } 14613 14614 if (installedPkg != null) { 14615 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14616 // Check for updated system application. 14617 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14618 if (onSd) { 14619 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14620 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14621 } 14622 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14623 } else { 14624 if (onSd) { 14625 // Install flag overrides everything. 14626 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14627 } 14628 // If current upgrade specifies particular preference 14629 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14630 // Application explicitly specified internal. 14631 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14632 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14633 // App explictly prefers external. Let policy decide 14634 } else { 14635 // Prefer previous location 14636 if (isExternal(installedPkg)) { 14637 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14638 } 14639 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14640 } 14641 } 14642 } else { 14643 // Invalid install. Return error code 14644 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14645 } 14646 } 14647 } 14648 // All the special cases have been taken care of. 14649 // Return result based on recommended install location. 14650 if (onSd) { 14651 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14652 } 14653 return pkgLite.recommendedInstallLocation; 14654 } 14655 14656 /* 14657 * Invoke remote method to get package information and install 14658 * location values. Override install location based on default 14659 * policy if needed and then create install arguments based 14660 * on the install location. 14661 */ 14662 public void handleStartCopy() throws RemoteException { 14663 int ret = PackageManager.INSTALL_SUCCEEDED; 14664 14665 // If we're already staged, we've firmly committed to an install location 14666 if (origin.staged) { 14667 if (origin.file != null) { 14668 installFlags |= PackageManager.INSTALL_INTERNAL; 14669 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14670 } else { 14671 throw new IllegalStateException("Invalid stage location"); 14672 } 14673 } 14674 14675 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14676 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14677 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14678 PackageInfoLite pkgLite = null; 14679 14680 if (onInt && onSd) { 14681 // Check if both bits are set. 14682 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14683 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14684 } else if (onSd && ephemeral) { 14685 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14686 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14687 } else { 14688 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14689 packageAbiOverride); 14690 14691 if (DEBUG_EPHEMERAL && ephemeral) { 14692 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14693 } 14694 14695 /* 14696 * If we have too little free space, try to free cache 14697 * before giving up. 14698 */ 14699 if (!origin.staged && pkgLite.recommendedInstallLocation 14700 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14701 // TODO: focus freeing disk space on the target device 14702 final StorageManager storage = StorageManager.from(mContext); 14703 final long lowThreshold = storage.getStorageLowBytes( 14704 Environment.getDataDirectory()); 14705 14706 final long sizeBytes = mContainerService.calculateInstalledSize( 14707 origin.resolvedPath, packageAbiOverride); 14708 14709 try { 14710 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 14711 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14712 installFlags, packageAbiOverride); 14713 } catch (InstallerException e) { 14714 Slog.w(TAG, "Failed to free cache", e); 14715 } 14716 14717 /* 14718 * The cache free must have deleted the file we 14719 * downloaded to install. 14720 * 14721 * TODO: fix the "freeCache" call to not delete 14722 * the file we care about. 14723 */ 14724 if (pkgLite.recommendedInstallLocation 14725 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14726 pkgLite.recommendedInstallLocation 14727 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14728 } 14729 } 14730 } 14731 14732 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14733 int loc = pkgLite.recommendedInstallLocation; 14734 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14735 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14736 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14737 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14738 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14739 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14740 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14741 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14742 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14743 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14744 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14745 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14746 } else { 14747 // Override with defaults if needed. 14748 loc = installLocationPolicy(pkgLite); 14749 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14750 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14751 } else if (!onSd && !onInt) { 14752 // Override install location with flags 14753 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14754 // Set the flag to install on external media. 14755 installFlags |= PackageManager.INSTALL_EXTERNAL; 14756 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14757 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14758 if (DEBUG_EPHEMERAL) { 14759 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14760 } 14761 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14762 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14763 |PackageManager.INSTALL_INTERNAL); 14764 } else { 14765 // Make sure the flag for installing on external 14766 // media is unset 14767 installFlags |= PackageManager.INSTALL_INTERNAL; 14768 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14769 } 14770 } 14771 } 14772 } 14773 14774 final InstallArgs args = createInstallArgs(this); 14775 mArgs = args; 14776 14777 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14778 // TODO: http://b/22976637 14779 // Apps installed for "all" users use the device owner to verify the app 14780 UserHandle verifierUser = getUser(); 14781 if (verifierUser == UserHandle.ALL) { 14782 verifierUser = UserHandle.SYSTEM; 14783 } 14784 14785 /* 14786 * Determine if we have any installed package verifiers. If we 14787 * do, then we'll defer to them to verify the packages. 14788 */ 14789 final int requiredUid = mRequiredVerifierPackage == null ? -1 14790 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14791 verifierUser.getIdentifier()); 14792 final int installerUid = 14793 verificationInfo == null ? -1 : verificationInfo.installerUid; 14794 if (!origin.existing && requiredUid != -1 14795 && isVerificationEnabled( 14796 verifierUser.getIdentifier(), installFlags, installerUid)) { 14797 final Intent verification = new Intent( 14798 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14799 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14800 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14801 PACKAGE_MIME_TYPE); 14802 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14803 14804 // Query all live verifiers based on current user state 14805 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14806 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 14807 false /*allowDynamicSplits*/); 14808 14809 if (DEBUG_VERIFY) { 14810 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14811 + verification.toString() + " with " + pkgLite.verifiers.length 14812 + " optional verifiers"); 14813 } 14814 14815 final int verificationId = mPendingVerificationToken++; 14816 14817 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14818 14819 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14820 installerPackageName); 14821 14822 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14823 installFlags); 14824 14825 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14826 pkgLite.packageName); 14827 14828 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14829 pkgLite.versionCode); 14830 14831 verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE, 14832 pkgLite.getLongVersionCode()); 14833 14834 if (verificationInfo != null) { 14835 if (verificationInfo.originatingUri != null) { 14836 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14837 verificationInfo.originatingUri); 14838 } 14839 if (verificationInfo.referrer != null) { 14840 verification.putExtra(Intent.EXTRA_REFERRER, 14841 verificationInfo.referrer); 14842 } 14843 if (verificationInfo.originatingUid >= 0) { 14844 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14845 verificationInfo.originatingUid); 14846 } 14847 if (verificationInfo.installerUid >= 0) { 14848 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14849 verificationInfo.installerUid); 14850 } 14851 } 14852 14853 final PackageVerificationState verificationState = new PackageVerificationState( 14854 requiredUid, args); 14855 14856 mPendingVerification.append(verificationId, verificationState); 14857 14858 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14859 receivers, verificationState); 14860 14861 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14862 final long idleDuration = getVerificationTimeout(); 14863 14864 /* 14865 * If any sufficient verifiers were listed in the package 14866 * manifest, attempt to ask them. 14867 */ 14868 if (sufficientVerifiers != null) { 14869 final int N = sufficientVerifiers.size(); 14870 if (N == 0) { 14871 Slog.i(TAG, "Additional verifiers required, but none installed."); 14872 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14873 } else { 14874 for (int i = 0; i < N; i++) { 14875 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14876 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14877 verifierComponent.getPackageName(), idleDuration, 14878 verifierUser.getIdentifier(), false, "package verifier"); 14879 14880 final Intent sufficientIntent = new Intent(verification); 14881 sufficientIntent.setComponent(verifierComponent); 14882 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14883 } 14884 } 14885 } 14886 14887 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14888 mRequiredVerifierPackage, receivers); 14889 if (ret == PackageManager.INSTALL_SUCCEEDED 14890 && mRequiredVerifierPackage != null) { 14891 Trace.asyncTraceBegin( 14892 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14893 /* 14894 * Send the intent to the required verification agent, 14895 * but only start the verification timeout after the 14896 * target BroadcastReceivers have run. 14897 */ 14898 verification.setComponent(requiredVerifierComponent); 14899 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14900 mRequiredVerifierPackage, idleDuration, 14901 verifierUser.getIdentifier(), false, "package verifier"); 14902 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14903 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14904 new BroadcastReceiver() { 14905 @Override 14906 public void onReceive(Context context, Intent intent) { 14907 final Message msg = mHandler 14908 .obtainMessage(CHECK_PENDING_VERIFICATION); 14909 msg.arg1 = verificationId; 14910 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14911 } 14912 }, null, 0, null, null); 14913 14914 /* 14915 * We don't want the copy to proceed until verification 14916 * succeeds, so null out this field. 14917 */ 14918 mArgs = null; 14919 } 14920 } else { 14921 /* 14922 * No package verification is enabled, so immediately start 14923 * the remote call to initiate copy using temporary file. 14924 */ 14925 ret = args.copyApk(mContainerService, true); 14926 } 14927 } 14928 14929 mRet = ret; 14930 } 14931 14932 @Override 14933 void handleReturnCode() { 14934 // If mArgs is null, then MCS couldn't be reached. When it 14935 // reconnects, it will try again to install. At that point, this 14936 // will succeed. 14937 if (mArgs != null) { 14938 processPendingInstall(mArgs, mRet); 14939 } 14940 } 14941 14942 @Override 14943 void handleServiceError() { 14944 mArgs = createInstallArgs(this); 14945 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14946 } 14947 } 14948 14949 private InstallArgs createInstallArgs(InstallParams params) { 14950 if (params.move != null) { 14951 return new MoveInstallArgs(params); 14952 } else { 14953 return new FileInstallArgs(params); 14954 } 14955 } 14956 14957 /** 14958 * Create args that describe an existing installed package. Typically used 14959 * when cleaning up old installs, or used as a move source. 14960 */ 14961 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14962 String resourcePath, String[] instructionSets) { 14963 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14964 } 14965 14966 static abstract class InstallArgs { 14967 /** @see InstallParams#origin */ 14968 final OriginInfo origin; 14969 /** @see InstallParams#move */ 14970 final MoveInfo move; 14971 14972 final IPackageInstallObserver2 observer; 14973 // Always refers to PackageManager flags only 14974 final int installFlags; 14975 final String installerPackageName; 14976 final String volumeUuid; 14977 final UserHandle user; 14978 final String abiOverride; 14979 final String[] installGrantPermissions; 14980 /** If non-null, drop an async trace when the install completes */ 14981 final String traceMethod; 14982 final int traceCookie; 14983 final Certificate[][] certificates; 14984 final int installReason; 14985 14986 // The list of instruction sets supported by this app. This is currently 14987 // only used during the rmdex() phase to clean up resources. We can get rid of this 14988 // if we move dex files under the common app path. 14989 /* nullable */ String[] instructionSets; 14990 14991 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14992 int installFlags, String installerPackageName, String volumeUuid, 14993 UserHandle user, String[] instructionSets, 14994 String abiOverride, String[] installGrantPermissions, 14995 String traceMethod, int traceCookie, Certificate[][] certificates, 14996 int installReason) { 14997 this.origin = origin; 14998 this.move = move; 14999 this.installFlags = installFlags; 15000 this.observer = observer; 15001 this.installerPackageName = installerPackageName; 15002 this.volumeUuid = volumeUuid; 15003 this.user = user; 15004 this.instructionSets = instructionSets; 15005 this.abiOverride = abiOverride; 15006 this.installGrantPermissions = installGrantPermissions; 15007 this.traceMethod = traceMethod; 15008 this.traceCookie = traceCookie; 15009 this.certificates = certificates; 15010 this.installReason = installReason; 15011 } 15012 15013 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15014 abstract int doPreInstall(int status); 15015 15016 /** 15017 * Rename package into final resting place. All paths on the given 15018 * scanned package should be updated to reflect the rename. 15019 */ 15020 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15021 abstract int doPostInstall(int status, int uid); 15022 15023 /** @see PackageSettingBase#codePathString */ 15024 abstract String getCodePath(); 15025 /** @see PackageSettingBase#resourcePathString */ 15026 abstract String getResourcePath(); 15027 15028 // Need installer lock especially for dex file removal. 15029 abstract void cleanUpResourcesLI(); 15030 abstract boolean doPostDeleteLI(boolean delete); 15031 15032 /** 15033 * Called before the source arguments are copied. This is used mostly 15034 * for MoveParams when it needs to read the source file to put it in the 15035 * destination. 15036 */ 15037 int doPreCopy() { 15038 return PackageManager.INSTALL_SUCCEEDED; 15039 } 15040 15041 /** 15042 * Called after the source arguments are copied. This is used mostly for 15043 * MoveParams when it needs to read the source file to put it in the 15044 * destination. 15045 */ 15046 int doPostCopy(int uid) { 15047 return PackageManager.INSTALL_SUCCEEDED; 15048 } 15049 15050 protected boolean isFwdLocked() { 15051 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15052 } 15053 15054 protected boolean isExternalAsec() { 15055 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15056 } 15057 15058 protected boolean isEphemeral() { 15059 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15060 } 15061 15062 UserHandle getUser() { 15063 return user; 15064 } 15065 } 15066 15067 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15068 if (!allCodePaths.isEmpty()) { 15069 if (instructionSets == null) { 15070 throw new IllegalStateException("instructionSet == null"); 15071 } 15072 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15073 for (String codePath : allCodePaths) { 15074 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15075 try { 15076 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15077 } catch (InstallerException ignored) { 15078 } 15079 } 15080 } 15081 } 15082 } 15083 15084 /** 15085 * Logic to handle installation of non-ASEC applications, including copying 15086 * and renaming logic. 15087 */ 15088 class FileInstallArgs extends InstallArgs { 15089 private File codeFile; 15090 private File resourceFile; 15091 15092 // Example topology: 15093 // /data/app/com.example/base.apk 15094 // /data/app/com.example/split_foo.apk 15095 // /data/app/com.example/lib/arm/libfoo.so 15096 // /data/app/com.example/lib/arm64/libfoo.so 15097 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15098 15099 /** New install */ 15100 FileInstallArgs(InstallParams params) { 15101 super(params.origin, params.move, params.observer, params.installFlags, 15102 params.installerPackageName, params.volumeUuid, 15103 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15104 params.grantedRuntimePermissions, 15105 params.traceMethod, params.traceCookie, params.certificates, 15106 params.installReason); 15107 if (isFwdLocked()) { 15108 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15109 } 15110 } 15111 15112 /** Existing install */ 15113 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15114 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15115 null, null, null, 0, null /*certificates*/, 15116 PackageManager.INSTALL_REASON_UNKNOWN); 15117 this.codeFile = (codePath != null) ? new File(codePath) : null; 15118 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15119 } 15120 15121 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15122 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15123 try { 15124 return doCopyApk(imcs, temp); 15125 } finally { 15126 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15127 } 15128 } 15129 15130 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15131 if (origin.staged) { 15132 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15133 codeFile = origin.file; 15134 resourceFile = origin.file; 15135 return PackageManager.INSTALL_SUCCEEDED; 15136 } 15137 15138 try { 15139 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15140 final File tempDir = 15141 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15142 codeFile = tempDir; 15143 resourceFile = tempDir; 15144 } catch (IOException e) { 15145 Slog.w(TAG, "Failed to create copy file: " + e); 15146 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15147 } 15148 15149 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15150 @Override 15151 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15152 if (!FileUtils.isValidExtFilename(name)) { 15153 throw new IllegalArgumentException("Invalid filename: " + name); 15154 } 15155 try { 15156 final File file = new File(codeFile, name); 15157 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15158 O_RDWR | O_CREAT, 0644); 15159 Os.chmod(file.getAbsolutePath(), 0644); 15160 return new ParcelFileDescriptor(fd); 15161 } catch (ErrnoException e) { 15162 throw new RemoteException("Failed to open: " + e.getMessage()); 15163 } 15164 } 15165 }; 15166 15167 int ret = PackageManager.INSTALL_SUCCEEDED; 15168 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15169 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15170 Slog.e(TAG, "Failed to copy package"); 15171 return ret; 15172 } 15173 15174 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15175 NativeLibraryHelper.Handle handle = null; 15176 try { 15177 handle = NativeLibraryHelper.Handle.create(codeFile); 15178 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15179 abiOverride); 15180 } catch (IOException e) { 15181 Slog.e(TAG, "Copying native libraries failed", e); 15182 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15183 } finally { 15184 IoUtils.closeQuietly(handle); 15185 } 15186 15187 return ret; 15188 } 15189 15190 int doPreInstall(int status) { 15191 if (status != PackageManager.INSTALL_SUCCEEDED) { 15192 cleanUp(); 15193 } 15194 return status; 15195 } 15196 15197 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15198 if (status != PackageManager.INSTALL_SUCCEEDED) { 15199 cleanUp(); 15200 return false; 15201 } 15202 15203 final File targetDir = codeFile.getParentFile(); 15204 final File beforeCodeFile = codeFile; 15205 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15206 15207 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15208 try { 15209 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15210 } catch (ErrnoException e) { 15211 Slog.w(TAG, "Failed to rename", e); 15212 return false; 15213 } 15214 15215 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15216 Slog.w(TAG, "Failed to restorecon"); 15217 return false; 15218 } 15219 15220 // Reflect the rename internally 15221 codeFile = afterCodeFile; 15222 resourceFile = afterCodeFile; 15223 15224 // Reflect the rename in scanned details 15225 try { 15226 pkg.setCodePath(afterCodeFile.getCanonicalPath()); 15227 } catch (IOException e) { 15228 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e); 15229 return false; 15230 } 15231 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15232 afterCodeFile, pkg.baseCodePath)); 15233 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15234 afterCodeFile, pkg.splitCodePaths)); 15235 15236 // Reflect the rename in app info 15237 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15238 pkg.setApplicationInfoCodePath(pkg.codePath); 15239 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15240 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15241 pkg.setApplicationInfoResourcePath(pkg.codePath); 15242 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15243 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15244 15245 return true; 15246 } 15247 15248 int doPostInstall(int status, int uid) { 15249 if (status != PackageManager.INSTALL_SUCCEEDED) { 15250 cleanUp(); 15251 } 15252 return status; 15253 } 15254 15255 @Override 15256 String getCodePath() { 15257 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15258 } 15259 15260 @Override 15261 String getResourcePath() { 15262 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15263 } 15264 15265 private boolean cleanUp() { 15266 if (codeFile == null || !codeFile.exists()) { 15267 return false; 15268 } 15269 15270 removeCodePathLI(codeFile); 15271 15272 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15273 resourceFile.delete(); 15274 } 15275 15276 return true; 15277 } 15278 15279 void cleanUpResourcesLI() { 15280 // Try enumerating all code paths before deleting 15281 List<String> allCodePaths = Collections.EMPTY_LIST; 15282 if (codeFile != null && codeFile.exists()) { 15283 try { 15284 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15285 allCodePaths = pkg.getAllCodePaths(); 15286 } catch (PackageParserException e) { 15287 // Ignored; we tried our best 15288 } 15289 } 15290 15291 cleanUp(); 15292 removeDexFiles(allCodePaths, instructionSets); 15293 } 15294 15295 boolean doPostDeleteLI(boolean delete) { 15296 // XXX err, shouldn't we respect the delete flag? 15297 cleanUpResourcesLI(); 15298 return true; 15299 } 15300 } 15301 15302 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15303 PackageManagerException { 15304 if (copyRet < 0) { 15305 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15306 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15307 throw new PackageManagerException(copyRet, message); 15308 } 15309 } 15310 } 15311 15312 /** 15313 * Extract the StorageManagerService "container ID" from the full code path of an 15314 * .apk. 15315 */ 15316 static String cidFromCodePath(String fullCodePath) { 15317 int eidx = fullCodePath.lastIndexOf("/"); 15318 String subStr1 = fullCodePath.substring(0, eidx); 15319 int sidx = subStr1.lastIndexOf("/"); 15320 return subStr1.substring(sidx+1, eidx); 15321 } 15322 15323 /** 15324 * Logic to handle movement of existing installed applications. 15325 */ 15326 class MoveInstallArgs extends InstallArgs { 15327 private File codeFile; 15328 private File resourceFile; 15329 15330 /** New install */ 15331 MoveInstallArgs(InstallParams params) { 15332 super(params.origin, params.move, params.observer, params.installFlags, 15333 params.installerPackageName, params.volumeUuid, 15334 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15335 params.grantedRuntimePermissions, 15336 params.traceMethod, params.traceCookie, params.certificates, 15337 params.installReason); 15338 } 15339 15340 int copyApk(IMediaContainerService imcs, boolean temp) { 15341 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15342 + move.fromUuid + " to " + move.toUuid); 15343 synchronized (mInstaller) { 15344 try { 15345 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15346 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15347 } catch (InstallerException e) { 15348 Slog.w(TAG, "Failed to move app", e); 15349 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15350 } 15351 } 15352 15353 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15354 resourceFile = codeFile; 15355 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15356 15357 return PackageManager.INSTALL_SUCCEEDED; 15358 } 15359 15360 int doPreInstall(int status) { 15361 if (status != PackageManager.INSTALL_SUCCEEDED) { 15362 cleanUp(move.toUuid); 15363 } 15364 return status; 15365 } 15366 15367 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15368 if (status != PackageManager.INSTALL_SUCCEEDED) { 15369 cleanUp(move.toUuid); 15370 return false; 15371 } 15372 15373 // Reflect the move in app info 15374 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15375 pkg.setApplicationInfoCodePath(pkg.codePath); 15376 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15377 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15378 pkg.setApplicationInfoResourcePath(pkg.codePath); 15379 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15380 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15381 15382 return true; 15383 } 15384 15385 int doPostInstall(int status, int uid) { 15386 if (status == PackageManager.INSTALL_SUCCEEDED) { 15387 cleanUp(move.fromUuid); 15388 } else { 15389 cleanUp(move.toUuid); 15390 } 15391 return status; 15392 } 15393 15394 @Override 15395 String getCodePath() { 15396 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15397 } 15398 15399 @Override 15400 String getResourcePath() { 15401 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15402 } 15403 15404 private boolean cleanUp(String volumeUuid) { 15405 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15406 move.dataAppName); 15407 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15408 final int[] userIds = sUserManager.getUserIds(); 15409 synchronized (mInstallLock) { 15410 // Clean up both app data and code 15411 // All package moves are frozen until finished 15412 for (int userId : userIds) { 15413 try { 15414 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15415 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15416 } catch (InstallerException e) { 15417 Slog.w(TAG, String.valueOf(e)); 15418 } 15419 } 15420 removeCodePathLI(codeFile); 15421 } 15422 return true; 15423 } 15424 15425 void cleanUpResourcesLI() { 15426 throw new UnsupportedOperationException(); 15427 } 15428 15429 boolean doPostDeleteLI(boolean delete) { 15430 throw new UnsupportedOperationException(); 15431 } 15432 } 15433 15434 static String getAsecPackageName(String packageCid) { 15435 int idx = packageCid.lastIndexOf("-"); 15436 if (idx == -1) { 15437 return packageCid; 15438 } 15439 return packageCid.substring(0, idx); 15440 } 15441 15442 // Utility method used to create code paths based on package name and available index. 15443 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15444 String idxStr = ""; 15445 int idx = 1; 15446 // Fall back to default value of idx=1 if prefix is not 15447 // part of oldCodePath 15448 if (oldCodePath != null) { 15449 String subStr = oldCodePath; 15450 // Drop the suffix right away 15451 if (suffix != null && subStr.endsWith(suffix)) { 15452 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15453 } 15454 // If oldCodePath already contains prefix find out the 15455 // ending index to either increment or decrement. 15456 int sidx = subStr.lastIndexOf(prefix); 15457 if (sidx != -1) { 15458 subStr = subStr.substring(sidx + prefix.length()); 15459 if (subStr != null) { 15460 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15461 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15462 } 15463 try { 15464 idx = Integer.parseInt(subStr); 15465 if (idx <= 1) { 15466 idx++; 15467 } else { 15468 idx--; 15469 } 15470 } catch(NumberFormatException e) { 15471 } 15472 } 15473 } 15474 } 15475 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15476 return prefix + idxStr; 15477 } 15478 15479 private File getNextCodePath(File targetDir, String packageName) { 15480 File result; 15481 SecureRandom random = new SecureRandom(); 15482 byte[] bytes = new byte[16]; 15483 do { 15484 random.nextBytes(bytes); 15485 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15486 result = new File(targetDir, packageName + "-" + suffix); 15487 } while (result.exists()); 15488 return result; 15489 } 15490 15491 // Utility method that returns the relative package path with respect 15492 // to the installation directory. Like say for /data/data/com.test-1.apk 15493 // string com.test-1 is returned. 15494 static String deriveCodePathName(String codePath) { 15495 if (codePath == null) { 15496 return null; 15497 } 15498 final File codeFile = new File(codePath); 15499 final String name = codeFile.getName(); 15500 if (codeFile.isDirectory()) { 15501 return name; 15502 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15503 final int lastDot = name.lastIndexOf('.'); 15504 return name.substring(0, lastDot); 15505 } else { 15506 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15507 return null; 15508 } 15509 } 15510 15511 static class PackageInstalledInfo { 15512 String name; 15513 int uid; 15514 // The set of users that originally had this package installed. 15515 int[] origUsers; 15516 // The set of users that now have this package installed. 15517 int[] newUsers; 15518 PackageParser.Package pkg; 15519 int returnCode; 15520 String returnMsg; 15521 String installerPackageName; 15522 PackageRemovedInfo removedInfo; 15523 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15524 15525 public void setError(int code, String msg) { 15526 setReturnCode(code); 15527 setReturnMessage(msg); 15528 Slog.w(TAG, msg); 15529 } 15530 15531 public void setError(String msg, PackageParserException e) { 15532 setReturnCode(e.error); 15533 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15534 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15535 for (int i = 0; i < childCount; i++) { 15536 addedChildPackages.valueAt(i).setError(msg, e); 15537 } 15538 Slog.w(TAG, msg, e); 15539 } 15540 15541 public void setError(String msg, PackageManagerException e) { 15542 returnCode = e.error; 15543 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15544 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15545 for (int i = 0; i < childCount; i++) { 15546 addedChildPackages.valueAt(i).setError(msg, e); 15547 } 15548 Slog.w(TAG, msg, e); 15549 } 15550 15551 public void setReturnCode(int returnCode) { 15552 this.returnCode = returnCode; 15553 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15554 for (int i = 0; i < childCount; i++) { 15555 addedChildPackages.valueAt(i).returnCode = returnCode; 15556 } 15557 } 15558 15559 private void setReturnMessage(String returnMsg) { 15560 this.returnMsg = returnMsg; 15561 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15562 for (int i = 0; i < childCount; i++) { 15563 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15564 } 15565 } 15566 15567 // In some error cases we want to convey more info back to the observer 15568 String origPackage; 15569 String origPermission; 15570 } 15571 15572 /* 15573 * Install a non-existing package. 15574 */ 15575 private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15576 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15577 String volumeUuid, PackageInstalledInfo res, int installReason) { 15578 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15579 15580 // Remember this for later, in case we need to rollback this install 15581 String pkgName = pkg.packageName; 15582 15583 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15584 15585 synchronized(mPackages) { 15586 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15587 if (renamedPackage != null) { 15588 // A package with the same name is already installed, though 15589 // it has been renamed to an older name. The package we 15590 // are trying to install should be installed as an update to 15591 // the existing one, but that has not been requested, so bail. 15592 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15593 + " without first uninstalling package running as " 15594 + renamedPackage); 15595 return; 15596 } 15597 if (mPackages.containsKey(pkgName)) { 15598 // Don't allow installation over an existing package with the same name. 15599 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15600 + " without first uninstalling."); 15601 return; 15602 } 15603 } 15604 15605 try { 15606 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 15607 System.currentTimeMillis(), user); 15608 15609 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15610 15611 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15612 prepareAppDataAfterInstallLIF(newPackage); 15613 15614 } else { 15615 // Remove package from internal structures, but keep around any 15616 // data that might have already existed 15617 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15618 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15619 } 15620 } catch (PackageManagerException e) { 15621 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15622 } 15623 15624 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15625 } 15626 15627 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15628 try (DigestInputStream digestStream = 15629 new DigestInputStream(new FileInputStream(file), digest)) { 15630 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15631 } 15632 } 15633 15634 private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15635 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15636 PackageInstalledInfo res, int installReason) { 15637 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15638 15639 final PackageParser.Package oldPackage; 15640 final PackageSetting ps; 15641 final String pkgName = pkg.packageName; 15642 final int[] allUsers; 15643 final int[] installedUsers; 15644 15645 synchronized(mPackages) { 15646 oldPackage = mPackages.get(pkgName); 15647 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15648 15649 // don't allow upgrade to target a release SDK from a pre-release SDK 15650 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15651 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15652 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15653 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15654 if (oldTargetsPreRelease 15655 && !newTargetsPreRelease 15656 && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15657 Slog.w(TAG, "Can't install package targeting released sdk"); 15658 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15659 return; 15660 } 15661 15662 ps = mSettings.mPackages.get(pkgName); 15663 15664 // verify signatures are valid 15665 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 15666 if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) { 15667 if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) { 15668 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15669 "New package not signed by keys specified by upgrade-keysets: " 15670 + pkgName); 15671 return; 15672 } 15673 } else { 15674 // default to original signature matching 15675 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15676 != PackageManager.SIGNATURE_MATCH) { 15677 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15678 "New package has a different signature: " + pkgName); 15679 return; 15680 } 15681 } 15682 15683 // don't allow a system upgrade unless the upgrade hash matches 15684 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) { 15685 byte[] digestBytes = null; 15686 try { 15687 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15688 updateDigest(digest, new File(pkg.baseCodePath)); 15689 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15690 for (String path : pkg.splitCodePaths) { 15691 updateDigest(digest, new File(path)); 15692 } 15693 } 15694 digestBytes = digest.digest(); 15695 } catch (NoSuchAlgorithmException | IOException e) { 15696 res.setError(INSTALL_FAILED_INVALID_APK, 15697 "Could not compute hash: " + pkgName); 15698 return; 15699 } 15700 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15701 res.setError(INSTALL_FAILED_INVALID_APK, 15702 "New package fails restrict-update check: " + pkgName); 15703 return; 15704 } 15705 // retain upgrade restriction 15706 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15707 } 15708 15709 // Check for shared user id changes 15710 String invalidPackageName = 15711 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15712 if (invalidPackageName != null) { 15713 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15714 "Package " + invalidPackageName + " tried to change user " 15715 + oldPackage.mSharedUserId); 15716 return; 15717 } 15718 15719 // check if the new package supports all of the abis which the old package supports 15720 boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null; 15721 boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null; 15722 if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) { 15723 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15724 "Update to package " + pkgName + " doesn't support multi arch"); 15725 return; 15726 } 15727 15728 // In case of rollback, remember per-user/profile install state 15729 allUsers = sUserManager.getUserIds(); 15730 installedUsers = ps.queryInstalledUsers(allUsers, true); 15731 15732 // don't allow an upgrade from full to ephemeral 15733 if (isInstantApp) { 15734 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 15735 for (int currentUser : allUsers) { 15736 if (!ps.getInstantApp(currentUser)) { 15737 // can't downgrade from full to instant 15738 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15739 + " for user: " + currentUser); 15740 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15741 return; 15742 } 15743 } 15744 } else if (!ps.getInstantApp(user.getIdentifier())) { 15745 // can't downgrade from full to instant 15746 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15747 + " for user: " + user.getIdentifier()); 15748 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15749 return; 15750 } 15751 } 15752 } 15753 15754 // Update what is removed 15755 res.removedInfo = new PackageRemovedInfo(this); 15756 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15757 res.removedInfo.removedPackage = oldPackage.packageName; 15758 res.removedInfo.installerPackageName = ps.installerPackageName; 15759 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15760 res.removedInfo.isUpdate = true; 15761 res.removedInfo.origUsers = installedUsers; 15762 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15763 for (int i = 0; i < installedUsers.length; i++) { 15764 final int userId = installedUsers[i]; 15765 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15766 } 15767 15768 final int childCount = (oldPackage.childPackages != null) 15769 ? oldPackage.childPackages.size() : 0; 15770 for (int i = 0; i < childCount; i++) { 15771 boolean childPackageUpdated = false; 15772 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15773 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15774 if (res.addedChildPackages != null) { 15775 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15776 if (childRes != null) { 15777 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15778 childRes.removedInfo.removedPackage = childPkg.packageName; 15779 if (childPs != null) { 15780 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 15781 } 15782 childRes.removedInfo.isUpdate = true; 15783 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15784 childPackageUpdated = true; 15785 } 15786 } 15787 if (!childPackageUpdated) { 15788 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 15789 childRemovedRes.removedPackage = childPkg.packageName; 15790 if (childPs != null) { 15791 childRemovedRes.installerPackageName = childPs.installerPackageName; 15792 } 15793 childRemovedRes.isUpdate = false; 15794 childRemovedRes.dataRemoved = true; 15795 synchronized (mPackages) { 15796 if (childPs != null) { 15797 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15798 } 15799 } 15800 if (res.removedInfo.removedChildPackages == null) { 15801 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15802 } 15803 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15804 } 15805 } 15806 15807 boolean sysPkg = (isSystemApp(oldPackage)); 15808 if (sysPkg) { 15809 // Set the system/privileged/oem/vendor flags as needed 15810 final boolean privileged = 15811 (oldPackage.applicationInfo.privateFlags 15812 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15813 final boolean oem = 15814 (oldPackage.applicationInfo.privateFlags 15815 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 15816 final boolean vendor = 15817 (oldPackage.applicationInfo.privateFlags 15818 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 15819 final @ParseFlags int systemParseFlags = parseFlags; 15820 final @ScanFlags int systemScanFlags = scanFlags 15821 | SCAN_AS_SYSTEM 15822 | (privileged ? SCAN_AS_PRIVILEGED : 0) 15823 | (oem ? SCAN_AS_OEM : 0) 15824 | (vendor ? SCAN_AS_VENDOR : 0); 15825 15826 replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags, 15827 user, allUsers, installerPackageName, res, installReason); 15828 } else { 15829 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 15830 user, allUsers, installerPackageName, res, installReason); 15831 } 15832 } 15833 15834 @Override 15835 public List<String> getPreviousCodePaths(String packageName) { 15836 final int callingUid = Binder.getCallingUid(); 15837 final List<String> result = new ArrayList<>(); 15838 if (getInstantAppPackageName(callingUid) != null) { 15839 return result; 15840 } 15841 final PackageSetting ps = mSettings.mPackages.get(packageName); 15842 if (ps != null 15843 && ps.oldCodePaths != null 15844 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 15845 result.addAll(ps.oldCodePaths); 15846 } 15847 return result; 15848 } 15849 15850 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 15851 PackageParser.Package pkg, final @ParseFlags int parseFlags, 15852 final @ScanFlags int scanFlags, UserHandle user, int[] allUsers, 15853 String installerPackageName, PackageInstalledInfo res, int installReason) { 15854 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 15855 + deletedPackage); 15856 15857 String pkgName = deletedPackage.packageName; 15858 boolean deletedPkg = true; 15859 boolean addedPkg = false; 15860 boolean updatedSettings = false; 15861 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 15862 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 15863 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 15864 15865 final long origUpdateTime = (pkg.mExtras != null) 15866 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 15867 15868 // First delete the existing package while retaining the data directory 15869 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15870 res.removedInfo, true, pkg)) { 15871 // If the existing package wasn't successfully deleted 15872 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 15873 deletedPkg = false; 15874 } else { 15875 // Successfully deleted the old package; proceed with replace. 15876 15877 // If deleted package lived in a container, give users a chance to 15878 // relinquish resources before killing. 15879 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 15880 if (DEBUG_INSTALL) { 15881 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 15882 } 15883 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 15884 final ArrayList<String> pkgList = new ArrayList<String>(1); 15885 pkgList.add(deletedPackage.applicationInfo.packageName); 15886 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 15887 } 15888 15889 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15890 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15891 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15892 15893 try { 15894 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 15895 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 15896 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 15897 installReason); 15898 15899 // Update the in-memory copy of the previous code paths. 15900 PackageSetting ps = mSettings.mPackages.get(pkgName); 15901 if (!killApp) { 15902 if (ps.oldCodePaths == null) { 15903 ps.oldCodePaths = new ArraySet<>(); 15904 } 15905 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 15906 if (deletedPackage.splitCodePaths != null) { 15907 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 15908 } 15909 } else { 15910 ps.oldCodePaths = null; 15911 } 15912 if (ps.childPackageNames != null) { 15913 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 15914 final String childPkgName = ps.childPackageNames.get(i); 15915 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 15916 childPs.oldCodePaths = ps.oldCodePaths; 15917 } 15918 } 15919 // set instant app status, but, only if it's explicitly specified 15920 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15921 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 15922 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 15923 prepareAppDataAfterInstallLIF(newPackage); 15924 addedPkg = true; 15925 mDexManager.notifyPackageUpdated(newPackage.packageName, 15926 newPackage.baseCodePath, newPackage.splitCodePaths); 15927 } catch (PackageManagerException e) { 15928 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15929 } 15930 } 15931 15932 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15933 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 15934 15935 // Revert all internal state mutations and added folders for the failed install 15936 if (addedPkg) { 15937 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15938 res.removedInfo, true, null); 15939 } 15940 15941 // Restore the old package 15942 if (deletedPkg) { 15943 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 15944 File restoreFile = new File(deletedPackage.codePath); 15945 // Parse old package 15946 boolean oldExternal = isExternal(deletedPackage); 15947 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 15948 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 15949 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 15950 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 15951 try { 15952 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 15953 null); 15954 } catch (PackageManagerException e) { 15955 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 15956 + e.getMessage()); 15957 return; 15958 } 15959 15960 synchronized (mPackages) { 15961 // Ensure the installer package name up to date 15962 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15963 15964 // Update permissions for restored package 15965 mPermissionManager.updatePermissions( 15966 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 15967 mPermissionCallback); 15968 15969 mSettings.writeLPr(); 15970 } 15971 15972 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 15973 } 15974 } else { 15975 synchronized (mPackages) { 15976 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 15977 if (ps != null) { 15978 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15979 if (res.removedInfo.removedChildPackages != null) { 15980 final int childCount = res.removedInfo.removedChildPackages.size(); 15981 // Iterate in reverse as we may modify the collection 15982 for (int i = childCount - 1; i >= 0; i--) { 15983 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 15984 if (res.addedChildPackages.containsKey(childPackageName)) { 15985 res.removedInfo.removedChildPackages.removeAt(i); 15986 } else { 15987 PackageRemovedInfo childInfo = res.removedInfo 15988 .removedChildPackages.valueAt(i); 15989 childInfo.removedForAllUsers = mPackages.get( 15990 childInfo.removedPackage) == null; 15991 } 15992 } 15993 } 15994 } 15995 } 15996 } 15997 } 15998 15999 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16000 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16001 final @ScanFlags int scanFlags, UserHandle user, 16002 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16003 int installReason) { 16004 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16005 + ", old=" + deletedPackage); 16006 16007 final boolean disabledSystem; 16008 16009 // Remove existing system package 16010 removePackageLI(deletedPackage, true); 16011 16012 synchronized (mPackages) { 16013 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16014 } 16015 if (!disabledSystem) { 16016 // We didn't need to disable the .apk as a current system package, 16017 // which means we are replacing another update that is already 16018 // installed. We need to make sure to delete the older one's .apk. 16019 res.removedInfo.args = createInstallArgsForExisting(0, 16020 deletedPackage.applicationInfo.getCodePath(), 16021 deletedPackage.applicationInfo.getResourcePath(), 16022 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16023 } else { 16024 res.removedInfo.args = null; 16025 } 16026 16027 // Successfully disabled the old package. Now proceed with re-installation 16028 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16029 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16030 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16031 16032 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16033 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16034 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16035 16036 PackageParser.Package newPackage = null; 16037 try { 16038 // Add the package to the internal data structures 16039 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 16040 16041 // Set the update and install times 16042 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16043 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16044 System.currentTimeMillis()); 16045 16046 // Update the package dynamic state if succeeded 16047 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16048 // Now that the install succeeded make sure we remove data 16049 // directories for any child package the update removed. 16050 final int deletedChildCount = (deletedPackage.childPackages != null) 16051 ? deletedPackage.childPackages.size() : 0; 16052 final int newChildCount = (newPackage.childPackages != null) 16053 ? newPackage.childPackages.size() : 0; 16054 for (int i = 0; i < deletedChildCount; i++) { 16055 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16056 boolean childPackageDeleted = true; 16057 for (int j = 0; j < newChildCount; j++) { 16058 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16059 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16060 childPackageDeleted = false; 16061 break; 16062 } 16063 } 16064 if (childPackageDeleted) { 16065 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16066 deletedChildPkg.packageName); 16067 if (ps != null && res.removedInfo.removedChildPackages != null) { 16068 PackageRemovedInfo removedChildRes = res.removedInfo 16069 .removedChildPackages.get(deletedChildPkg.packageName); 16070 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16071 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16072 } 16073 } 16074 } 16075 16076 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16077 installReason); 16078 prepareAppDataAfterInstallLIF(newPackage); 16079 16080 mDexManager.notifyPackageUpdated(newPackage.packageName, 16081 newPackage.baseCodePath, newPackage.splitCodePaths); 16082 } 16083 } catch (PackageManagerException e) { 16084 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16085 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16086 } 16087 16088 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16089 // Re installation failed. Restore old information 16090 // Remove new pkg information 16091 if (newPackage != null) { 16092 removeInstalledPackageLI(newPackage, true); 16093 } 16094 // Add back the old system package 16095 try { 16096 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16097 } catch (PackageManagerException e) { 16098 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16099 } 16100 16101 synchronized (mPackages) { 16102 if (disabledSystem) { 16103 enableSystemPackageLPw(deletedPackage); 16104 } 16105 16106 // Ensure the installer package name up to date 16107 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16108 16109 // Update permissions for restored package 16110 mPermissionManager.updatePermissions( 16111 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16112 mPermissionCallback); 16113 16114 mSettings.writeLPr(); 16115 } 16116 16117 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16118 + " after failed upgrade"); 16119 } 16120 } 16121 16122 /** 16123 * Checks whether the parent or any of the child packages have a change shared 16124 * user. For a package to be a valid update the shred users of the parent and 16125 * the children should match. We may later support changing child shared users. 16126 * @param oldPkg The updated package. 16127 * @param newPkg The update package. 16128 * @return The shared user that change between the versions. 16129 */ 16130 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16131 PackageParser.Package newPkg) { 16132 // Check parent shared user 16133 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16134 return newPkg.packageName; 16135 } 16136 // Check child shared users 16137 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16138 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16139 for (int i = 0; i < newChildCount; i++) { 16140 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16141 // If this child was present, did it have the same shared user? 16142 for (int j = 0; j < oldChildCount; j++) { 16143 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16144 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16145 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16146 return newChildPkg.packageName; 16147 } 16148 } 16149 } 16150 return null; 16151 } 16152 16153 private void removeNativeBinariesLI(PackageSetting ps) { 16154 // Remove the lib path for the parent package 16155 if (ps != null) { 16156 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16157 // Remove the lib path for the child packages 16158 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16159 for (int i = 0; i < childCount; i++) { 16160 PackageSetting childPs = null; 16161 synchronized (mPackages) { 16162 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16163 } 16164 if (childPs != null) { 16165 NativeLibraryHelper.removeNativeBinariesLI(childPs 16166 .legacyNativeLibraryPathString); 16167 } 16168 } 16169 } 16170 } 16171 16172 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16173 // Enable the parent package 16174 mSettings.enableSystemPackageLPw(pkg.packageName); 16175 // Enable the child packages 16176 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16177 for (int i = 0; i < childCount; i++) { 16178 PackageParser.Package childPkg = pkg.childPackages.get(i); 16179 mSettings.enableSystemPackageLPw(childPkg.packageName); 16180 } 16181 } 16182 16183 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16184 PackageParser.Package newPkg) { 16185 // Disable the parent package (parent always replaced) 16186 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16187 // Disable the child packages 16188 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16189 for (int i = 0; i < childCount; i++) { 16190 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16191 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16192 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16193 } 16194 return disabled; 16195 } 16196 16197 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16198 String installerPackageName) { 16199 // Enable the parent package 16200 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16201 // Enable the child packages 16202 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16203 for (int i = 0; i < childCount; i++) { 16204 PackageParser.Package childPkg = pkg.childPackages.get(i); 16205 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16206 } 16207 } 16208 16209 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16210 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16211 // Update the parent package setting 16212 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16213 res, user, installReason); 16214 // Update the child packages setting 16215 final int childCount = (newPackage.childPackages != null) 16216 ? newPackage.childPackages.size() : 0; 16217 for (int i = 0; i < childCount; i++) { 16218 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16219 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16220 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16221 childRes.origUsers, childRes, user, installReason); 16222 } 16223 } 16224 16225 private void updateSettingsInternalLI(PackageParser.Package pkg, 16226 String installerPackageName, int[] allUsers, int[] installedForUsers, 16227 PackageInstalledInfo res, UserHandle user, int installReason) { 16228 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16229 16230 String pkgName = pkg.packageName; 16231 synchronized (mPackages) { 16232 //write settings. the installStatus will be incomplete at this stage. 16233 //note that the new package setting would have already been 16234 //added to mPackages. It hasn't been persisted yet. 16235 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16236 // TODO: Remove this write? It's also written at the end of this method 16237 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16238 mSettings.writeLPr(); 16239 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16240 } 16241 16242 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath); 16243 synchronized (mPackages) { 16244// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions 16245 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 16246 mPermissionCallback); 16247 // For system-bundled packages, we assume that installing an upgraded version 16248 // of the package implies that the user actually wants to run that new code, 16249 // so we enable the package. 16250 PackageSetting ps = mSettings.mPackages.get(pkgName); 16251 final int userId = user.getIdentifier(); 16252 if (ps != null) { 16253 if (isSystemApp(pkg)) { 16254 if (DEBUG_INSTALL) { 16255 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16256 } 16257 // Enable system package for requested users 16258 if (res.origUsers != null) { 16259 for (int origUserId : res.origUsers) { 16260 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16261 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16262 origUserId, installerPackageName); 16263 } 16264 } 16265 } 16266 // Also convey the prior install/uninstall state 16267 if (allUsers != null && installedForUsers != null) { 16268 for (int currentUserId : allUsers) { 16269 final boolean installed = ArrayUtils.contains( 16270 installedForUsers, currentUserId); 16271 if (DEBUG_INSTALL) { 16272 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16273 } 16274 ps.setInstalled(installed, currentUserId); 16275 } 16276 // these install state changes will be persisted in the 16277 // upcoming call to mSettings.writeLPr(). 16278 } 16279 } 16280 // It's implied that when a user requests installation, they want the app to be 16281 // installed and enabled. 16282 if (userId != UserHandle.USER_ALL) { 16283 ps.setInstalled(true, userId); 16284 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16285 } 16286 16287 // When replacing an existing package, preserve the original install reason for all 16288 // users that had the package installed before. 16289 final Set<Integer> previousUserIds = new ArraySet<>(); 16290 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16291 final int installReasonCount = res.removedInfo.installReasons.size(); 16292 for (int i = 0; i < installReasonCount; i++) { 16293 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16294 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16295 ps.setInstallReason(previousInstallReason, previousUserId); 16296 previousUserIds.add(previousUserId); 16297 } 16298 } 16299 16300 // Set install reason for users that are having the package newly installed. 16301 if (userId == UserHandle.USER_ALL) { 16302 for (int currentUserId : sUserManager.getUserIds()) { 16303 if (!previousUserIds.contains(currentUserId)) { 16304 ps.setInstallReason(installReason, currentUserId); 16305 } 16306 } 16307 } else if (!previousUserIds.contains(userId)) { 16308 ps.setInstallReason(installReason, userId); 16309 } 16310 mSettings.writeKernelMappingLPr(ps); 16311 } 16312 res.name = pkgName; 16313 res.uid = pkg.applicationInfo.uid; 16314 res.pkg = pkg; 16315 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16316 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16317 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16318 //to update install status 16319 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16320 mSettings.writeLPr(); 16321 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16322 } 16323 16324 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16325 } 16326 16327 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16328 try { 16329 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16330 installPackageLI(args, res); 16331 } finally { 16332 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16333 } 16334 } 16335 16336 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16337 final int installFlags = args.installFlags; 16338 final String installerPackageName = args.installerPackageName; 16339 final String volumeUuid = args.volumeUuid; 16340 final File tmpPackageFile = new File(args.getCodePath()); 16341 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16342 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16343 || (args.volumeUuid != null)); 16344 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16345 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16346 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16347 final boolean virtualPreload = 16348 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 16349 boolean replace = false; 16350 @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16351 if (args.move != null) { 16352 // moving a complete application; perform an initial scan on the new install location 16353 scanFlags |= SCAN_INITIAL; 16354 } 16355 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16356 scanFlags |= SCAN_DONT_KILL_APP; 16357 } 16358 if (instantApp) { 16359 scanFlags |= SCAN_AS_INSTANT_APP; 16360 } 16361 if (fullApp) { 16362 scanFlags |= SCAN_AS_FULL_APP; 16363 } 16364 if (virtualPreload) { 16365 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 16366 } 16367 16368 // Result object to be returned 16369 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16370 res.installerPackageName = installerPackageName; 16371 16372 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16373 16374 // Sanity check 16375 if (instantApp && (forwardLocked || onExternal)) { 16376 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16377 + " external=" + onExternal); 16378 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16379 return; 16380 } 16381 16382 // Retrieve PackageSettings and parse package 16383 @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16384 | PackageParser.PARSE_ENFORCE_CODE 16385 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16386 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16387 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16388 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16389 PackageParser pp = new PackageParser(); 16390 pp.setSeparateProcesses(mSeparateProcesses); 16391 pp.setDisplayMetrics(mMetrics); 16392 pp.setCallback(mPackageParserCallback); 16393 16394 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16395 final PackageParser.Package pkg; 16396 try { 16397 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16398 } catch (PackageParserException e) { 16399 res.setError("Failed parse during installPackageLI", e); 16400 return; 16401 } finally { 16402 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16403 } 16404 16405 // App targetSdkVersion is below min supported version 16406 if (!forceSdk && pkg.applicationInfo.isTargetingDeprecatedSdkVersion()) { 16407 Slog.w(TAG, "App " + pkg.packageName + " targets deprecated sdk"); 16408 16409 res.setError(INSTALL_FAILED_NEWER_SDK, 16410 "App is targeting deprecated sdk (targetSdkVersion should be at least " 16411 + Build.VERSION.MIN_SUPPORTED_TARGET_SDK_INT + ")."); 16412 return; 16413 } 16414 16415 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 16416 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16417 Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O"); 16418 res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16419 "Instant app package must target O"); 16420 return; 16421 } 16422 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 16423 Slog.w(TAG, "Instant app package " + pkg.packageName 16424 + " does not target targetSandboxVersion 2"); 16425 res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16426 "Instant app package must use targetSanboxVersion 2"); 16427 return; 16428 } 16429 16430 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16431 // Static shared libraries have synthetic package names 16432 renameStaticSharedLibraryPackage(pkg); 16433 16434 // No static shared libs on external storage 16435 if (onExternal) { 16436 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16437 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16438 "Packages declaring static-shared libs cannot be updated"); 16439 return; 16440 } 16441 } 16442 16443 // If we are installing a clustered package add results for the children 16444 if (pkg.childPackages != null) { 16445 synchronized (mPackages) { 16446 final int childCount = pkg.childPackages.size(); 16447 for (int i = 0; i < childCount; i++) { 16448 PackageParser.Package childPkg = pkg.childPackages.get(i); 16449 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16450 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16451 childRes.pkg = childPkg; 16452 childRes.name = childPkg.packageName; 16453 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16454 if (childPs != null) { 16455 childRes.origUsers = childPs.queryInstalledUsers( 16456 sUserManager.getUserIds(), true); 16457 } 16458 if ((mPackages.containsKey(childPkg.packageName))) { 16459 childRes.removedInfo = new PackageRemovedInfo(this); 16460 childRes.removedInfo.removedPackage = childPkg.packageName; 16461 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16462 } 16463 if (res.addedChildPackages == null) { 16464 res.addedChildPackages = new ArrayMap<>(); 16465 } 16466 res.addedChildPackages.put(childPkg.packageName, childRes); 16467 } 16468 } 16469 } 16470 16471 // If package doesn't declare API override, mark that we have an install 16472 // time CPU ABI override. 16473 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16474 pkg.cpuAbiOverride = args.abiOverride; 16475 } 16476 16477 String pkgName = res.name = pkg.packageName; 16478 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16479 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16480 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16481 return; 16482 } 16483 } 16484 16485 try { 16486 // either use what we've been given or parse directly from the APK 16487 if (args.certificates != null) { 16488 try { 16489 PackageParser.populateCertificates(pkg, args.certificates); 16490 } catch (PackageParserException e) { 16491 // there was something wrong with the certificates we were given; 16492 // try to pull them from the APK 16493 PackageParser.collectCertificates(pkg, parseFlags); 16494 } 16495 } else { 16496 PackageParser.collectCertificates(pkg, parseFlags); 16497 } 16498 } catch (PackageParserException e) { 16499 res.setError("Failed collect during installPackageLI", e); 16500 return; 16501 } 16502 16503 // Get rid of all references to package scan path via parser. 16504 pp = null; 16505 String oldCodePath = null; 16506 boolean systemApp = false; 16507 synchronized (mPackages) { 16508 // Check if installing already existing package 16509 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16510 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16511 if (pkg.mOriginalPackages != null 16512 && pkg.mOriginalPackages.contains(oldName) 16513 && mPackages.containsKey(oldName)) { 16514 // This package is derived from an original package, 16515 // and this device has been updating from that original 16516 // name. We must continue using the original name, so 16517 // rename the new package here. 16518 pkg.setPackageName(oldName); 16519 pkgName = pkg.packageName; 16520 replace = true; 16521 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16522 + oldName + " pkgName=" + pkgName); 16523 } else if (mPackages.containsKey(pkgName)) { 16524 // This package, under its official name, already exists 16525 // on the device; we should replace it. 16526 replace = true; 16527 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16528 } 16529 16530 // Child packages are installed through the parent package 16531 if (pkg.parentPackage != null) { 16532 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16533 "Package " + pkg.packageName + " is child of package " 16534 + pkg.parentPackage.parentPackage + ". Child packages " 16535 + "can be updated only through the parent package."); 16536 return; 16537 } 16538 16539 if (replace) { 16540 // Prevent apps opting out from runtime permissions 16541 PackageParser.Package oldPackage = mPackages.get(pkgName); 16542 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16543 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16544 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16545 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16546 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16547 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16548 + " doesn't support runtime permissions but the old" 16549 + " target SDK " + oldTargetSdk + " does."); 16550 return; 16551 } 16552 // Prevent persistent apps from being updated 16553 if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) { 16554 res.setError(PackageManager.INSTALL_FAILED_INVALID_APK, 16555 "Package " + oldPackage.packageName + " is a persistent app. " 16556 + "Persistent apps are not updateable."); 16557 return; 16558 } 16559 // Prevent apps from downgrading their targetSandbox. 16560 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16561 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16562 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16563 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16564 "Package " + pkg.packageName + " new target sandbox " 16565 + newTargetSandbox + " is incompatible with the previous value of" 16566 + oldTargetSandbox + "."); 16567 return; 16568 } 16569 16570 // Prevent installing of child packages 16571 if (oldPackage.parentPackage != null) { 16572 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16573 "Package " + pkg.packageName + " is child of package " 16574 + oldPackage.parentPackage + ". Child packages " 16575 + "can be updated only through the parent package."); 16576 return; 16577 } 16578 } 16579 } 16580 16581 PackageSetting ps = mSettings.mPackages.get(pkgName); 16582 if (ps != null) { 16583 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16584 16585 // Static shared libs have same package with different versions where 16586 // we internally use a synthetic package name to allow multiple versions 16587 // of the same package, therefore we need to compare signatures against 16588 // the package setting for the latest library version. 16589 PackageSetting signatureCheckPs = ps; 16590 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16591 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16592 if (libraryEntry != null) { 16593 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16594 } 16595 } 16596 16597 // Quick sanity check that we're signed correctly if updating; 16598 // we'll check this again later when scanning, but we want to 16599 // bail early here before tripping over redefined permissions. 16600 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16601 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 16602 if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 16603 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16604 + pkg.packageName + " upgrade keys do not match the " 16605 + "previously installed version"); 16606 return; 16607 } 16608 } else { 16609 try { 16610 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 16611 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 16612 final boolean compatMatch = verifySignatures( 16613 signatureCheckPs, pkg.mSignatures, compareCompat, compareRecover); 16614 // The new KeySets will be re-added later in the scanning process. 16615 if (compatMatch) { 16616 synchronized (mPackages) { 16617 ksms.removeAppKeySetDataLPw(pkg.packageName); 16618 } 16619 } 16620 } catch (PackageManagerException e) { 16621 res.setError(e.error, e.getMessage()); 16622 return; 16623 } 16624 } 16625 16626 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16627 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16628 systemApp = (ps.pkg.applicationInfo.flags & 16629 ApplicationInfo.FLAG_SYSTEM) != 0; 16630 } 16631 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16632 } 16633 16634 int N = pkg.permissions.size(); 16635 for (int i = N-1; i >= 0; i--) { 16636 final PackageParser.Permission perm = pkg.permissions.get(i); 16637 final BasePermission bp = 16638 (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name); 16639 16640 // Don't allow anyone but the system to define ephemeral permissions. 16641 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 16642 && !systemApp) { 16643 Slog.w(TAG, "Non-System package " + pkg.packageName 16644 + " attempting to delcare ephemeral permission " 16645 + perm.info.name + "; Removing ephemeral."); 16646 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 16647 } 16648 16649 // Check whether the newly-scanned package wants to define an already-defined perm 16650 if (bp != null) { 16651 // If the defining package is signed with our cert, it's okay. This 16652 // also includes the "updating the same package" case, of course. 16653 // "updating same package" could also involve key-rotation. 16654 final boolean sigsOk; 16655 final String sourcePackageName = bp.getSourcePackageName(); 16656 final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting(); 16657 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16658 if (sourcePackageName.equals(pkg.packageName) 16659 && (ksms.shouldCheckUpgradeKeySetLocked( 16660 sourcePackageSetting, scanFlags))) { 16661 sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg); 16662 } else { 16663 sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures, 16664 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16665 } 16666 if (!sigsOk) { 16667 // If the owning package is the system itself, we log but allow 16668 // install to proceed; we fail the install on all other permission 16669 // redefinitions. 16670 if (!sourcePackageName.equals("android")) { 16671 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16672 + pkg.packageName + " attempting to redeclare permission " 16673 + perm.info.name + " already owned by " + sourcePackageName); 16674 res.origPermission = perm.info.name; 16675 res.origPackage = sourcePackageName; 16676 return; 16677 } else { 16678 Slog.w(TAG, "Package " + pkg.packageName 16679 + " attempting to redeclare system permission " 16680 + perm.info.name + "; ignoring new declaration"); 16681 pkg.permissions.remove(i); 16682 } 16683 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16684 // Prevent apps to change protection level to dangerous from any other 16685 // type as this would allow a privilege escalation where an app adds a 16686 // normal/signature permission in other app's group and later redefines 16687 // it as dangerous leading to the group auto-grant. 16688 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16689 == PermissionInfo.PROTECTION_DANGEROUS) { 16690 if (bp != null && !bp.isRuntime()) { 16691 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16692 + "non-runtime permission " + perm.info.name 16693 + " to runtime; keeping old protection level"); 16694 perm.info.protectionLevel = bp.getProtectionLevel(); 16695 } 16696 } 16697 } 16698 } 16699 } 16700 } 16701 16702 if (systemApp) { 16703 if (onExternal) { 16704 // Abort update; system app can't be replaced with app on sdcard 16705 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16706 "Cannot install updates to system apps on sdcard"); 16707 return; 16708 } else if (instantApp) { 16709 // Abort update; system app can't be replaced with an instant app 16710 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16711 "Cannot update a system app with an instant app"); 16712 return; 16713 } 16714 } 16715 16716 if (args.move != null) { 16717 // We did an in-place move, so dex is ready to roll 16718 scanFlags |= SCAN_NO_DEX; 16719 scanFlags |= SCAN_MOVE; 16720 16721 synchronized (mPackages) { 16722 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16723 if (ps == null) { 16724 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16725 "Missing settings for moved package " + pkgName); 16726 } 16727 16728 // We moved the entire application as-is, so bring over the 16729 // previously derived ABI information. 16730 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16731 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16732 } 16733 16734 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16735 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16736 scanFlags |= SCAN_NO_DEX; 16737 16738 try { 16739 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16740 args.abiOverride : pkg.cpuAbiOverride); 16741 final boolean extractNativeLibs = !pkg.isLibrary(); 16742 derivePackageAbi(pkg, abiOverride, extractNativeLibs); 16743 } catch (PackageManagerException pme) { 16744 Slog.e(TAG, "Error deriving application ABI", pme); 16745 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16746 return; 16747 } 16748 16749 // Shared libraries for the package need to be updated. 16750 synchronized (mPackages) { 16751 try { 16752 updateSharedLibrariesLPr(pkg, null); 16753 } catch (PackageManagerException e) { 16754 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16755 } 16756 } 16757 } 16758 16759 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16760 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16761 return; 16762 } 16763 16764 if (!instantApp) { 16765 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16766 } else { 16767 if (DEBUG_DOMAIN_VERIFICATION) { 16768 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName); 16769 } 16770 } 16771 16772 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16773 "installPackageLI")) { 16774 if (replace) { 16775 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16776 // Static libs have a synthetic package name containing the version 16777 // and cannot be updated as an update would get a new package name, 16778 // unless this is the exact same version code which is useful for 16779 // development. 16780 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16781 if (existingPkg != null && 16782 existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) { 16783 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16784 + "static-shared libs cannot be updated"); 16785 return; 16786 } 16787 } 16788 replacePackageLIF(pkg, parseFlags, scanFlags, args.user, 16789 installerPackageName, res, args.installReason); 16790 } else { 16791 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16792 args.user, installerPackageName, volumeUuid, res, args.installReason); 16793 } 16794 } 16795 16796 // Check whether we need to dexopt the app. 16797 // 16798 // NOTE: it is IMPORTANT to call dexopt: 16799 // - after doRename which will sync the package data from PackageParser.Package and its 16800 // corresponding ApplicationInfo. 16801 // - after installNewPackageLIF or replacePackageLIF which will update result with the 16802 // uid of the application (pkg.applicationInfo.uid). 16803 // This update happens in place! 16804 // 16805 // We only need to dexopt if the package meets ALL of the following conditions: 16806 // 1) it is not forward locked. 16807 // 2) it is not on on an external ASEC container. 16808 // 3) it is not an instant app or if it is then dexopt is enabled via gservices. 16809 // 16810 // Note that we do not dexopt instant apps by default. dexopt can take some time to 16811 // complete, so we skip this step during installation. Instead, we'll take extra time 16812 // the first time the instant app starts. It's preferred to do it this way to provide 16813 // continuous progress to the useur instead of mysteriously blocking somewhere in the 16814 // middle of running an instant app. The default behaviour can be overridden 16815 // via gservices. 16816 final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED) 16817 && !forwardLocked 16818 && !pkg.applicationInfo.isExternalAsec() 16819 && (!instantApp || Global.getInt(mContext.getContentResolver(), 16820 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0); 16821 16822 if (performDexopt) { 16823 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16824 // Do not run PackageDexOptimizer through the local performDexOpt 16825 // method because `pkg` may not be in `mPackages` yet. 16826 // 16827 // Also, don't fail application installs if the dexopt step fails. 16828 DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName, 16829 REASON_INSTALL, 16830 DexoptOptions.DEXOPT_BOOT_COMPLETE); 16831 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16832 null /* instructionSets */, 16833 getOrCreateCompilerPackageStats(pkg), 16834 mDexManager.getPackageUseInfoOrDefault(pkg.packageName), 16835 dexoptOptions); 16836 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16837 } 16838 16839 // Notify BackgroundDexOptService that the package has been changed. 16840 // If this is an update of a package which used to fail to compile, 16841 // BackgroundDexOptService will remove it from its blacklist. 16842 // TODO: Layering violation 16843 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 16844 16845 synchronized (mPackages) { 16846 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16847 if (ps != null) { 16848 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16849 ps.setUpdateAvailable(false /*updateAvailable*/); 16850 } 16851 16852 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16853 for (int i = 0; i < childCount; i++) { 16854 PackageParser.Package childPkg = pkg.childPackages.get(i); 16855 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16856 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16857 if (childPs != null) { 16858 childRes.newUsers = childPs.queryInstalledUsers( 16859 sUserManager.getUserIds(), true); 16860 } 16861 } 16862 16863 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16864 updateSequenceNumberLP(ps, res.newUsers); 16865 updateInstantAppInstallerLocked(pkgName); 16866 } 16867 } 16868 } 16869 16870 private void startIntentFilterVerifications(int userId, boolean replacing, 16871 PackageParser.Package pkg) { 16872 if (mIntentFilterVerifierComponent == null) { 16873 Slog.w(TAG, "No IntentFilter verification will not be done as " 16874 + "there is no IntentFilterVerifier available!"); 16875 return; 16876 } 16877 16878 final int verifierUid = getPackageUid( 16879 mIntentFilterVerifierComponent.getPackageName(), 16880 MATCH_DEBUG_TRIAGED_MISSING, 16881 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 16882 16883 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16884 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 16885 mHandler.sendMessage(msg); 16886 16887 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16888 for (int i = 0; i < childCount; i++) { 16889 PackageParser.Package childPkg = pkg.childPackages.get(i); 16890 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16891 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 16892 mHandler.sendMessage(msg); 16893 } 16894 } 16895 16896 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 16897 PackageParser.Package pkg) { 16898 int size = pkg.activities.size(); 16899 if (size == 0) { 16900 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16901 "No activity, so no need to verify any IntentFilter!"); 16902 return; 16903 } 16904 16905 final boolean hasDomainURLs = hasDomainURLs(pkg); 16906 if (!hasDomainURLs) { 16907 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16908 "No domain URLs, so no need to verify any IntentFilter!"); 16909 return; 16910 } 16911 16912 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 16913 + " if any IntentFilter from the " + size 16914 + " Activities needs verification ..."); 16915 16916 int count = 0; 16917 final String packageName = pkg.packageName; 16918 16919 synchronized (mPackages) { 16920 // If this is a new install and we see that we've already run verification for this 16921 // package, we have nothing to do: it means the state was restored from backup. 16922 if (!replacing) { 16923 IntentFilterVerificationInfo ivi = 16924 mSettings.getIntentFilterVerificationLPr(packageName); 16925 if (ivi != null) { 16926 if (DEBUG_DOMAIN_VERIFICATION) { 16927 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 16928 + ivi.getStatusString()); 16929 } 16930 return; 16931 } 16932 } 16933 16934 // If any filters need to be verified, then all need to be. 16935 boolean needToVerify = false; 16936 for (PackageParser.Activity a : pkg.activities) { 16937 for (ActivityIntentInfo filter : a.intents) { 16938 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 16939 if (DEBUG_DOMAIN_VERIFICATION) { 16940 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 16941 } 16942 needToVerify = true; 16943 break; 16944 } 16945 } 16946 } 16947 16948 if (needToVerify) { 16949 final int verificationId = mIntentFilterVerificationToken++; 16950 for (PackageParser.Activity a : pkg.activities) { 16951 for (ActivityIntentInfo filter : a.intents) { 16952 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 16953 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16954 "Verification needed for IntentFilter:" + filter.toString()); 16955 mIntentFilterVerifier.addOneIntentFilterVerification( 16956 verifierUid, userId, verificationId, filter, packageName); 16957 count++; 16958 } 16959 } 16960 } 16961 } 16962 } 16963 16964 if (count > 0) { 16965 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 16966 + " IntentFilter verification" + (count > 1 ? "s" : "") 16967 + " for userId:" + userId); 16968 mIntentFilterVerifier.startVerifications(userId); 16969 } else { 16970 if (DEBUG_DOMAIN_VERIFICATION) { 16971 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 16972 } 16973 } 16974 } 16975 16976 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 16977 final ComponentName cn = filter.activity.getComponentName(); 16978 final String packageName = cn.getPackageName(); 16979 16980 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 16981 packageName); 16982 if (ivi == null) { 16983 return true; 16984 } 16985 int status = ivi.getStatus(); 16986 switch (status) { 16987 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 16988 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 16989 return true; 16990 16991 default: 16992 // Nothing to do 16993 return false; 16994 } 16995 } 16996 16997 private static boolean isMultiArch(ApplicationInfo info) { 16998 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 16999 } 17000 17001 private static boolean isExternal(PackageParser.Package pkg) { 17002 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17003 } 17004 17005 private static boolean isExternal(PackageSetting ps) { 17006 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17007 } 17008 17009 private static boolean isSystemApp(PackageParser.Package pkg) { 17010 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17011 } 17012 17013 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17014 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17015 } 17016 17017 private static boolean isOemApp(PackageParser.Package pkg) { 17018 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 17019 } 17020 17021 private static boolean isVendorApp(PackageParser.Package pkg) { 17022 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 17023 } 17024 17025 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17026 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17027 } 17028 17029 private static boolean isSystemApp(PackageSetting ps) { 17030 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17031 } 17032 17033 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17034 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17035 } 17036 17037 private int packageFlagsToInstallFlags(PackageSetting ps) { 17038 int installFlags = 0; 17039 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17040 // This existing package was an external ASEC install when we have 17041 // the external flag without a UUID 17042 installFlags |= PackageManager.INSTALL_EXTERNAL; 17043 } 17044 if (ps.isForwardLocked()) { 17045 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17046 } 17047 return installFlags; 17048 } 17049 17050 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17051 if (isExternal(pkg)) { 17052 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17053 return mSettings.getExternalVersion(); 17054 } else { 17055 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17056 } 17057 } else { 17058 return mSettings.getInternalVersion(); 17059 } 17060 } 17061 17062 private void deleteTempPackageFiles() { 17063 final FilenameFilter filter = new FilenameFilter() { 17064 public boolean accept(File dir, String name) { 17065 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17066 } 17067 }; 17068 for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) { 17069 file.delete(); 17070 } 17071 } 17072 17073 @Override 17074 public void deletePackageAsUser(String packageName, int versionCode, 17075 IPackageDeleteObserver observer, int userId, int flags) { 17076 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17077 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17078 } 17079 17080 @Override 17081 public void deletePackageVersioned(VersionedPackage versionedPackage, 17082 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17083 final int callingUid = Binder.getCallingUid(); 17084 mContext.enforceCallingOrSelfPermission( 17085 android.Manifest.permission.DELETE_PACKAGES, null); 17086 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 17087 Preconditions.checkNotNull(versionedPackage); 17088 Preconditions.checkNotNull(observer); 17089 Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(), 17090 PackageManager.VERSION_CODE_HIGHEST, 17091 Long.MAX_VALUE, "versionCode must be >= -1"); 17092 17093 final String packageName = versionedPackage.getPackageName(); 17094 final long versionCode = versionedPackage.getLongVersionCode(); 17095 final String internalPackageName; 17096 synchronized (mPackages) { 17097 // Normalize package name to handle renamed packages and static libs 17098 internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode); 17099 } 17100 17101 final int uid = Binder.getCallingUid(); 17102 if (!isOrphaned(internalPackageName) 17103 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17104 try { 17105 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17106 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17107 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17108 observer.onUserActionRequired(intent); 17109 } catch (RemoteException re) { 17110 } 17111 return; 17112 } 17113 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17114 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17115 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17116 mContext.enforceCallingOrSelfPermission( 17117 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17118 "deletePackage for user " + userId); 17119 } 17120 17121 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17122 try { 17123 observer.onPackageDeleted(packageName, 17124 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17125 } catch (RemoteException re) { 17126 } 17127 return; 17128 } 17129 17130 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17131 try { 17132 observer.onPackageDeleted(packageName, 17133 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17134 } catch (RemoteException re) { 17135 } 17136 return; 17137 } 17138 17139 if (DEBUG_REMOVE) { 17140 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17141 + " deleteAllUsers: " + deleteAllUsers + " version=" 17142 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17143 ? "VERSION_CODE_HIGHEST" : versionCode)); 17144 } 17145 // Queue up an async operation since the package deletion may take a little while. 17146 mHandler.post(new Runnable() { 17147 public void run() { 17148 mHandler.removeCallbacks(this); 17149 int returnCode; 17150 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 17151 boolean doDeletePackage = true; 17152 if (ps != null) { 17153 final boolean targetIsInstantApp = 17154 ps.getInstantApp(UserHandle.getUserId(callingUid)); 17155 doDeletePackage = !targetIsInstantApp 17156 || canViewInstantApps; 17157 } 17158 if (doDeletePackage) { 17159 if (!deleteAllUsers) { 17160 returnCode = deletePackageX(internalPackageName, versionCode, 17161 userId, deleteFlags); 17162 } else { 17163 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17164 internalPackageName, users); 17165 // If nobody is blocking uninstall, proceed with delete for all users 17166 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17167 returnCode = deletePackageX(internalPackageName, versionCode, 17168 userId, deleteFlags); 17169 } else { 17170 // Otherwise uninstall individually for users with blockUninstalls=false 17171 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17172 for (int userId : users) { 17173 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17174 returnCode = deletePackageX(internalPackageName, versionCode, 17175 userId, userFlags); 17176 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17177 Slog.w(TAG, "Package delete failed for user " + userId 17178 + ", returnCode " + returnCode); 17179 } 17180 } 17181 } 17182 // The app has only been marked uninstalled for certain users. 17183 // We still need to report that delete was blocked 17184 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17185 } 17186 } 17187 } else { 17188 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17189 } 17190 try { 17191 observer.onPackageDeleted(packageName, returnCode, null); 17192 } catch (RemoteException e) { 17193 Log.i(TAG, "Observer no longer exists."); 17194 } //end catch 17195 } //end run 17196 }); 17197 } 17198 17199 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17200 if (pkg.staticSharedLibName != null) { 17201 return pkg.manifestPackageName; 17202 } 17203 return pkg.packageName; 17204 } 17205 17206 private String resolveInternalPackageNameLPr(String packageName, long versionCode) { 17207 // Handle renamed packages 17208 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17209 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17210 17211 // Is this a static library? 17212 LongSparseArray<SharedLibraryEntry> versionedLib = 17213 mStaticLibsByDeclaringPackage.get(packageName); 17214 if (versionedLib == null || versionedLib.size() <= 0) { 17215 return packageName; 17216 } 17217 17218 // Figure out which lib versions the caller can see 17219 LongSparseLongArray versionsCallerCanSee = null; 17220 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17221 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17222 && callingAppId != Process.ROOT_UID) { 17223 versionsCallerCanSee = new LongSparseLongArray(); 17224 String libName = versionedLib.valueAt(0).info.getName(); 17225 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17226 if (uidPackages != null) { 17227 for (String uidPackage : uidPackages) { 17228 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17229 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17230 if (libIdx >= 0) { 17231 final long libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17232 versionsCallerCanSee.append(libVersion, libVersion); 17233 } 17234 } 17235 } 17236 } 17237 17238 // Caller can see nothing - done 17239 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17240 return packageName; 17241 } 17242 17243 // Find the version the caller can see and the app version code 17244 SharedLibraryEntry highestVersion = null; 17245 final int versionCount = versionedLib.size(); 17246 for (int i = 0; i < versionCount; i++) { 17247 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17248 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17249 libEntry.info.getLongVersion()) < 0) { 17250 continue; 17251 } 17252 final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode(); 17253 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17254 if (libVersionCode == versionCode) { 17255 return libEntry.apk; 17256 } 17257 } else if (highestVersion == null) { 17258 highestVersion = libEntry; 17259 } else if (libVersionCode > highestVersion.info 17260 .getDeclaringPackage().getLongVersionCode()) { 17261 highestVersion = libEntry; 17262 } 17263 } 17264 17265 if (highestVersion != null) { 17266 return highestVersion.apk; 17267 } 17268 17269 return packageName; 17270 } 17271 17272 boolean isCallerVerifier(int callingUid) { 17273 final int callingUserId = UserHandle.getUserId(callingUid); 17274 return mRequiredVerifierPackage != null && 17275 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 17276 } 17277 17278 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17279 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17280 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17281 return true; 17282 } 17283 final int callingUserId = UserHandle.getUserId(callingUid); 17284 // If the caller installed the pkgName, then allow it to silently uninstall. 17285 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17286 return true; 17287 } 17288 17289 // Allow package verifier to silently uninstall. 17290 if (mRequiredVerifierPackage != null && 17291 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17292 return true; 17293 } 17294 17295 // Allow package uninstaller to silently uninstall. 17296 if (mRequiredUninstallerPackage != null && 17297 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17298 return true; 17299 } 17300 17301 // Allow storage manager to silently uninstall. 17302 if (mStorageManagerPackage != null && 17303 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17304 return true; 17305 } 17306 17307 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 17308 // uninstall for device owner provisioning. 17309 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 17310 == PERMISSION_GRANTED) { 17311 return true; 17312 } 17313 17314 return false; 17315 } 17316 17317 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17318 int[] result = EMPTY_INT_ARRAY; 17319 for (int userId : userIds) { 17320 if (getBlockUninstallForUser(packageName, userId)) { 17321 result = ArrayUtils.appendInt(result, userId); 17322 } 17323 } 17324 return result; 17325 } 17326 17327 @Override 17328 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17329 final int callingUid = Binder.getCallingUid(); 17330 if (getInstantAppPackageName(callingUid) != null 17331 && !isCallerSameApp(packageName, callingUid)) { 17332 return false; 17333 } 17334 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17335 } 17336 17337 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17338 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17339 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17340 try { 17341 if (dpm != null) { 17342 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17343 /* callingUserOnly =*/ false); 17344 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17345 : deviceOwnerComponentName.getPackageName(); 17346 // Does the package contains the device owner? 17347 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17348 // this check is probably not needed, since DO should be registered as a device 17349 // admin on some user too. (Original bug for this: b/17657954) 17350 if (packageName.equals(deviceOwnerPackageName)) { 17351 return true; 17352 } 17353 // Does it contain a device admin for any user? 17354 int[] users; 17355 if (userId == UserHandle.USER_ALL) { 17356 users = sUserManager.getUserIds(); 17357 } else { 17358 users = new int[]{userId}; 17359 } 17360 for (int i = 0; i < users.length; ++i) { 17361 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17362 return true; 17363 } 17364 } 17365 } 17366 } catch (RemoteException e) { 17367 } 17368 return false; 17369 } 17370 17371 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17372 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17373 } 17374 17375 /** 17376 * This method is an internal method that could be get invoked either 17377 * to delete an installed package or to clean up a failed installation. 17378 * After deleting an installed package, a broadcast is sent to notify any 17379 * listeners that the package has been removed. For cleaning up a failed 17380 * installation, the broadcast is not necessary since the package's 17381 * installation wouldn't have sent the initial broadcast either 17382 * The key steps in deleting a package are 17383 * deleting the package information in internal structures like mPackages, 17384 * deleting the packages base directories through installd 17385 * updating mSettings to reflect current status 17386 * persisting settings for later use 17387 * sending a broadcast if necessary 17388 */ 17389 int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) { 17390 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17391 final boolean res; 17392 17393 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17394 ? UserHandle.USER_ALL : userId; 17395 17396 if (isPackageDeviceAdmin(packageName, removeUser)) { 17397 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17398 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17399 } 17400 17401 PackageSetting uninstalledPs = null; 17402 PackageParser.Package pkg = null; 17403 17404 // for the uninstall-updates case and restricted profiles, remember the per- 17405 // user handle installed state 17406 int[] allUsers; 17407 synchronized (mPackages) { 17408 uninstalledPs = mSettings.mPackages.get(packageName); 17409 if (uninstalledPs == null) { 17410 Slog.w(TAG, "Not removing non-existent package " + packageName); 17411 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17412 } 17413 17414 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17415 && uninstalledPs.versionCode != versionCode) { 17416 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17417 + uninstalledPs.versionCode + " != " + versionCode); 17418 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17419 } 17420 17421 // Static shared libs can be declared by any package, so let us not 17422 // allow removing a package if it provides a lib others depend on. 17423 pkg = mPackages.get(packageName); 17424 17425 allUsers = sUserManager.getUserIds(); 17426 17427 if (pkg != null && pkg.staticSharedLibName != null) { 17428 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17429 pkg.staticSharedLibVersion); 17430 if (libEntry != null) { 17431 for (int currUserId : allUsers) { 17432 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 17433 continue; 17434 } 17435 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17436 libEntry.info, 0, currUserId); 17437 if (!ArrayUtils.isEmpty(libClientPackages)) { 17438 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17439 + " hosting lib " + libEntry.info.getName() + " version " 17440 + libEntry.info.getLongVersion() + " used by " + libClientPackages 17441 + " for user " + currUserId); 17442 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17443 } 17444 } 17445 } 17446 } 17447 17448 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17449 } 17450 17451 final int freezeUser; 17452 if (isUpdatedSystemApp(uninstalledPs) 17453 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17454 // We're downgrading a system app, which will apply to all users, so 17455 // freeze them all during the downgrade 17456 freezeUser = UserHandle.USER_ALL; 17457 } else { 17458 freezeUser = removeUser; 17459 } 17460 17461 synchronized (mInstallLock) { 17462 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17463 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17464 deleteFlags, "deletePackageX")) { 17465 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17466 deleteFlags | PackageManager.DELETE_CHATTY, info, true, null); 17467 } 17468 synchronized (mPackages) { 17469 if (res) { 17470 if (pkg != null) { 17471 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17472 } 17473 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 17474 updateInstantAppInstallerLocked(packageName); 17475 } 17476 } 17477 } 17478 17479 if (res) { 17480 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17481 info.sendPackageRemovedBroadcasts(killApp); 17482 info.sendSystemPackageUpdatedBroadcasts(); 17483 info.sendSystemPackageAppearedBroadcasts(); 17484 } 17485 // Force a gc here. 17486 Runtime.getRuntime().gc(); 17487 // Delete the resources here after sending the broadcast to let 17488 // other processes clean up before deleting resources. 17489 if (info.args != null) { 17490 synchronized (mInstallLock) { 17491 info.args.doPostDeleteLI(true); 17492 } 17493 } 17494 17495 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17496 } 17497 17498 static class PackageRemovedInfo { 17499 final PackageSender packageSender; 17500 String removedPackage; 17501 String installerPackageName; 17502 int uid = -1; 17503 int removedAppId = -1; 17504 int[] origUsers; 17505 int[] removedUsers = null; 17506 int[] broadcastUsers = null; 17507 int[] instantUserIds = null; 17508 SparseArray<Integer> installReasons; 17509 boolean isRemovedPackageSystemUpdate = false; 17510 boolean isUpdate; 17511 boolean dataRemoved; 17512 boolean removedForAllUsers; 17513 boolean isStaticSharedLib; 17514 // Clean up resources deleted packages. 17515 InstallArgs args = null; 17516 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17517 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17518 17519 PackageRemovedInfo(PackageSender packageSender) { 17520 this.packageSender = packageSender; 17521 } 17522 17523 void sendPackageRemovedBroadcasts(boolean killApp) { 17524 sendPackageRemovedBroadcastInternal(killApp); 17525 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17526 for (int i = 0; i < childCount; i++) { 17527 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17528 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17529 } 17530 } 17531 17532 void sendSystemPackageUpdatedBroadcasts() { 17533 if (isRemovedPackageSystemUpdate) { 17534 sendSystemPackageUpdatedBroadcastsInternal(); 17535 final int childCount = (removedChildPackages != null) 17536 ? removedChildPackages.size() : 0; 17537 for (int i = 0; i < childCount; i++) { 17538 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17539 if (childInfo.isRemovedPackageSystemUpdate) { 17540 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17541 } 17542 } 17543 } 17544 } 17545 17546 void sendSystemPackageAppearedBroadcasts() { 17547 final int packageCount = (appearedChildPackages != null) 17548 ? appearedChildPackages.size() : 0; 17549 for (int i = 0; i < packageCount; i++) { 17550 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17551 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 17552 true /*sendBootCompleted*/, false /*startReceiver*/, 17553 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null); 17554 } 17555 } 17556 17557 private void sendSystemPackageUpdatedBroadcastsInternal() { 17558 Bundle extras = new Bundle(2); 17559 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17560 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17561 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17562 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 17563 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17564 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 17565 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 17566 null, null, 0, removedPackage, null, null, null); 17567 if (installerPackageName != null) { 17568 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17569 removedPackage, extras, 0 /*flags*/, 17570 installerPackageName, null, null, null); 17571 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17572 removedPackage, extras, 0 /*flags*/, 17573 installerPackageName, null, null, null); 17574 } 17575 } 17576 17577 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17578 // Don't send static shared library removal broadcasts as these 17579 // libs are visible only the the apps that depend on them an one 17580 // cannot remove the library if it has a dependency. 17581 if (isStaticSharedLib) { 17582 return; 17583 } 17584 Bundle extras = new Bundle(2); 17585 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17586 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17587 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17588 if (isUpdate || isRemovedPackageSystemUpdate) { 17589 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17590 } 17591 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17592 if (removedPackage != null) { 17593 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 17594 removedPackage, extras, 0, null /*targetPackage*/, null, 17595 broadcastUsers, instantUserIds); 17596 if (installerPackageName != null) { 17597 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 17598 removedPackage, extras, 0 /*flags*/, 17599 installerPackageName, null, broadcastUsers, instantUserIds); 17600 } 17601 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17602 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17603 removedPackage, extras, 17604 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17605 null, null, broadcastUsers, instantUserIds); 17606 packageSender.notifyPackageRemoved(removedPackage); 17607 } 17608 } 17609 if (removedAppId >= 0) { 17610 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 17611 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17612 null, null, broadcastUsers, instantUserIds); 17613 } 17614 } 17615 17616 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 17617 removedUsers = userIds; 17618 if (removedUsers == null) { 17619 broadcastUsers = null; 17620 return; 17621 } 17622 17623 broadcastUsers = EMPTY_INT_ARRAY; 17624 instantUserIds = EMPTY_INT_ARRAY; 17625 for (int i = userIds.length - 1; i >= 0; --i) { 17626 final int userId = userIds[i]; 17627 if (deletedPackageSetting.getInstantApp(userId)) { 17628 instantUserIds = ArrayUtils.appendInt(instantUserIds, userId); 17629 } else { 17630 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 17631 } 17632 } 17633 } 17634 } 17635 17636 /* 17637 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17638 * flag is not set, the data directory is removed as well. 17639 * make sure this flag is set for partially installed apps. If not its meaningless to 17640 * delete a partially installed application. 17641 */ 17642 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17643 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17644 String packageName = ps.name; 17645 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17646 // Retrieve object to delete permissions for shared user later on 17647 final PackageParser.Package deletedPkg; 17648 final PackageSetting deletedPs; 17649 // reader 17650 synchronized (mPackages) { 17651 deletedPkg = mPackages.get(packageName); 17652 deletedPs = mSettings.mPackages.get(packageName); 17653 if (outInfo != null) { 17654 outInfo.removedPackage = packageName; 17655 outInfo.installerPackageName = ps.installerPackageName; 17656 outInfo.isStaticSharedLib = deletedPkg != null 17657 && deletedPkg.staticSharedLibName != null; 17658 outInfo.populateUsers(deletedPs == null ? null 17659 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 17660 } 17661 } 17662 17663 removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0); 17664 17665 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17666 final PackageParser.Package resolvedPkg; 17667 if (deletedPkg != null) { 17668 resolvedPkg = deletedPkg; 17669 } else { 17670 // We don't have a parsed package when it lives on an ejected 17671 // adopted storage device, so fake something together 17672 resolvedPkg = new PackageParser.Package(ps.name); 17673 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17674 } 17675 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17676 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17677 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17678 if (outInfo != null) { 17679 outInfo.dataRemoved = true; 17680 } 17681 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17682 } 17683 17684 int removedAppId = -1; 17685 17686 // writer 17687 synchronized (mPackages) { 17688 boolean installedStateChanged = false; 17689 if (deletedPs != null) { 17690 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17691 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17692 clearDefaultBrowserIfNeeded(packageName); 17693 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17694 removedAppId = mSettings.removePackageLPw(packageName); 17695 if (outInfo != null) { 17696 outInfo.removedAppId = removedAppId; 17697 } 17698 mPermissionManager.updatePermissions( 17699 deletedPs.name, null, false, mPackages.values(), mPermissionCallback); 17700 if (deletedPs.sharedUser != null) { 17701 // Remove permissions associated with package. Since runtime 17702 // permissions are per user we have to kill the removed package 17703 // or packages running under the shared user of the removed 17704 // package if revoking the permissions requested only by the removed 17705 // package is successful and this causes a change in gids. 17706 for (int userId : UserManagerService.getInstance().getUserIds()) { 17707 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17708 userId); 17709 if (userIdToKill == UserHandle.USER_ALL 17710 || userIdToKill >= UserHandle.USER_SYSTEM) { 17711 // If gids changed for this user, kill all affected packages. 17712 mHandler.post(new Runnable() { 17713 @Override 17714 public void run() { 17715 // This has to happen with no lock held. 17716 killApplication(deletedPs.name, deletedPs.appId, 17717 KILL_APP_REASON_GIDS_CHANGED); 17718 } 17719 }); 17720 break; 17721 } 17722 } 17723 } 17724 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17725 } 17726 // make sure to preserve per-user disabled state if this removal was just 17727 // a downgrade of a system app to the factory package 17728 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17729 if (DEBUG_REMOVE) { 17730 Slog.d(TAG, "Propagating install state across downgrade"); 17731 } 17732 for (int userId : allUserHandles) { 17733 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17734 if (DEBUG_REMOVE) { 17735 Slog.d(TAG, " user " + userId + " => " + installed); 17736 } 17737 if (installed != ps.getInstalled(userId)) { 17738 installedStateChanged = true; 17739 } 17740 ps.setInstalled(installed, userId); 17741 } 17742 } 17743 } 17744 // can downgrade to reader 17745 if (writeSettings) { 17746 // Save settings now 17747 mSettings.writeLPr(); 17748 } 17749 if (installedStateChanged) { 17750 mSettings.writeKernelMappingLPr(ps); 17751 } 17752 } 17753 if (removedAppId != -1) { 17754 // A user ID was deleted here. Go through all users and remove it 17755 // from KeyStore. 17756 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17757 } 17758 } 17759 17760 static boolean locationIsPrivileged(String path) { 17761 try { 17762 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 17763 final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 17764 return path.startsWith(privilegedAppDir.getCanonicalPath()) 17765 || path.startsWith(privilegedVendorAppDir.getCanonicalPath()); 17766 } catch (IOException e) { 17767 Slog.e(TAG, "Unable to access code path " + path); 17768 } 17769 return false; 17770 } 17771 17772 static boolean locationIsOem(String path) { 17773 try { 17774 return path.startsWith(Environment.getOemDirectory().getCanonicalPath()); 17775 } catch (IOException e) { 17776 Slog.e(TAG, "Unable to access code path " + path); 17777 } 17778 return false; 17779 } 17780 17781 static boolean locationIsVendor(String path) { 17782 try { 17783 return path.startsWith(Environment.getVendorDirectory().getCanonicalPath()); 17784 } catch (IOException e) { 17785 Slog.e(TAG, "Unable to access code path " + path); 17786 } 17787 return false; 17788 } 17789 17790 /* 17791 * Tries to delete system package. 17792 */ 17793 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17794 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17795 boolean writeSettings) { 17796 if (deletedPs.parentPackageName != null) { 17797 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17798 return false; 17799 } 17800 17801 final boolean applyUserRestrictions 17802 = (allUserHandles != null) && (outInfo.origUsers != null); 17803 final PackageSetting disabledPs; 17804 // Confirm if the system package has been updated 17805 // An updated system app can be deleted. This will also have to restore 17806 // the system pkg from system partition 17807 // reader 17808 synchronized (mPackages) { 17809 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17810 } 17811 17812 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17813 + " disabledPs=" + disabledPs); 17814 17815 if (disabledPs == null) { 17816 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17817 return false; 17818 } else if (DEBUG_REMOVE) { 17819 Slog.d(TAG, "Deleting system pkg from data partition"); 17820 } 17821 17822 if (DEBUG_REMOVE) { 17823 if (applyUserRestrictions) { 17824 Slog.d(TAG, "Remembering install states:"); 17825 for (int userId : allUserHandles) { 17826 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17827 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17828 } 17829 } 17830 } 17831 17832 // Delete the updated package 17833 outInfo.isRemovedPackageSystemUpdate = true; 17834 if (outInfo.removedChildPackages != null) { 17835 final int childCount = (deletedPs.childPackageNames != null) 17836 ? deletedPs.childPackageNames.size() : 0; 17837 for (int i = 0; i < childCount; i++) { 17838 String childPackageName = deletedPs.childPackageNames.get(i); 17839 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17840 .contains(childPackageName)) { 17841 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17842 childPackageName); 17843 if (childInfo != null) { 17844 childInfo.isRemovedPackageSystemUpdate = true; 17845 } 17846 } 17847 } 17848 } 17849 17850 if (disabledPs.versionCode < deletedPs.versionCode) { 17851 // Delete data for downgrades 17852 flags &= ~PackageManager.DELETE_KEEP_DATA; 17853 } else { 17854 // Preserve data by setting flag 17855 flags |= PackageManager.DELETE_KEEP_DATA; 17856 } 17857 17858 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17859 outInfo, writeSettings, disabledPs.pkg); 17860 if (!ret) { 17861 return false; 17862 } 17863 17864 // writer 17865 synchronized (mPackages) { 17866 // NOTE: The system package always needs to be enabled; even if it's for 17867 // a compressed stub. If we don't, installing the system package fails 17868 // during scan [scanning checks the disabled packages]. We will reverse 17869 // this later, after we've "installed" the stub. 17870 // Reinstate the old system package 17871 enableSystemPackageLPw(disabledPs.pkg); 17872 // Remove any native libraries from the upgraded package. 17873 removeNativeBinariesLI(deletedPs); 17874 } 17875 17876 // Install the system package 17877 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17878 try { 17879 installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles, 17880 outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings); 17881 } catch (PackageManagerException e) { 17882 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17883 + e.getMessage()); 17884 return false; 17885 } finally { 17886 if (disabledPs.pkg.isStub) { 17887 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/); 17888 } 17889 } 17890 return true; 17891 } 17892 17893 /** 17894 * Installs a package that's already on the system partition. 17895 */ 17896 private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString, 17897 boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 17898 @Nullable PermissionsState origPermissionState, boolean writeSettings) 17899 throws PackageManagerException { 17900 @ParseFlags int parseFlags = 17901 mDefParseFlags 17902 | PackageParser.PARSE_MUST_BE_APK 17903 | PackageParser.PARSE_IS_SYSTEM_DIR; 17904 @ScanFlags int scanFlags = SCAN_AS_SYSTEM; 17905 if (isPrivileged || locationIsPrivileged(codePathString)) { 17906 scanFlags |= SCAN_AS_PRIVILEGED; 17907 } 17908 if (locationIsOem(codePathString)) { 17909 scanFlags |= SCAN_AS_OEM; 17910 } 17911 if (locationIsVendor(codePathString)) { 17912 scanFlags |= SCAN_AS_VENDOR; 17913 } 17914 17915 final File codePath = new File(codePathString); 17916 final PackageParser.Package pkg = 17917 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null); 17918 17919 try { 17920 // update shared libraries for the newly re-installed system package 17921 updateSharedLibrariesLPr(pkg, null); 17922 } catch (PackageManagerException e) { 17923 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17924 } 17925 17926 prepareAppDataAfterInstallLIF(pkg); 17927 17928 // writer 17929 synchronized (mPackages) { 17930 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 17931 17932 // Propagate the permissions state as we do not want to drop on the floor 17933 // runtime permissions. The update permissions method below will take 17934 // care of removing obsolete permissions and grant install permissions. 17935 if (origPermissionState != null) { 17936 ps.getPermissionsState().copyFrom(origPermissionState); 17937 } 17938 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 17939 mPermissionCallback); 17940 17941 final boolean applyUserRestrictions 17942 = (allUserHandles != null) && (origUserHandles != null); 17943 if (applyUserRestrictions) { 17944 boolean installedStateChanged = false; 17945 if (DEBUG_REMOVE) { 17946 Slog.d(TAG, "Propagating install state across reinstall"); 17947 } 17948 for (int userId : allUserHandles) { 17949 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 17950 if (DEBUG_REMOVE) { 17951 Slog.d(TAG, " user " + userId + " => " + installed); 17952 } 17953 if (installed != ps.getInstalled(userId)) { 17954 installedStateChanged = true; 17955 } 17956 ps.setInstalled(installed, userId); 17957 17958 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17959 } 17960 // Regardless of writeSettings we need to ensure that this restriction 17961 // state propagation is persisted 17962 mSettings.writeAllUsersPackageRestrictionsLPr(); 17963 if (installedStateChanged) { 17964 mSettings.writeKernelMappingLPr(ps); 17965 } 17966 } 17967 // can downgrade to reader here 17968 if (writeSettings) { 17969 mSettings.writeLPr(); 17970 } 17971 } 17972 return pkg; 17973 } 17974 17975 private boolean deleteInstalledPackageLIF(PackageSetting ps, 17976 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 17977 PackageRemovedInfo outInfo, boolean writeSettings, 17978 PackageParser.Package replacingPackage) { 17979 synchronized (mPackages) { 17980 if (outInfo != null) { 17981 outInfo.uid = ps.appId; 17982 } 17983 17984 if (outInfo != null && outInfo.removedChildPackages != null) { 17985 final int childCount = (ps.childPackageNames != null) 17986 ? ps.childPackageNames.size() : 0; 17987 for (int i = 0; i < childCount; i++) { 17988 String childPackageName = ps.childPackageNames.get(i); 17989 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 17990 if (childPs == null) { 17991 return false; 17992 } 17993 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17994 childPackageName); 17995 if (childInfo != null) { 17996 childInfo.uid = childPs.appId; 17997 } 17998 } 17999 } 18000 } 18001 18002 // Delete package data from internal structures and also remove data if flag is set 18003 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18004 18005 // Delete the child packages data 18006 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18007 for (int i = 0; i < childCount; i++) { 18008 PackageSetting childPs; 18009 synchronized (mPackages) { 18010 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18011 } 18012 if (childPs != null) { 18013 PackageRemovedInfo childOutInfo = (outInfo != null 18014 && outInfo.removedChildPackages != null) 18015 ? outInfo.removedChildPackages.get(childPs.name) : null; 18016 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18017 && (replacingPackage != null 18018 && !replacingPackage.hasChildPackage(childPs.name)) 18019 ? flags & ~DELETE_KEEP_DATA : flags; 18020 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18021 deleteFlags, writeSettings); 18022 } 18023 } 18024 18025 // Delete application code and resources only for parent packages 18026 if (ps.parentPackageName == null) { 18027 if (deleteCodeAndResources && (outInfo != null)) { 18028 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18029 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18030 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18031 } 18032 } 18033 18034 return true; 18035 } 18036 18037 @Override 18038 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18039 int userId) { 18040 mContext.enforceCallingOrSelfPermission( 18041 android.Manifest.permission.DELETE_PACKAGES, null); 18042 synchronized (mPackages) { 18043 // Cannot block uninstall of static shared libs as they are 18044 // considered a part of the using app (emulating static linking). 18045 // Also static libs are installed always on internal storage. 18046 PackageParser.Package pkg = mPackages.get(packageName); 18047 if (pkg != null && pkg.staticSharedLibName != null) { 18048 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18049 + " providing static shared library: " + pkg.staticSharedLibName); 18050 return false; 18051 } 18052 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 18053 mSettings.writePackageRestrictionsLPr(userId); 18054 } 18055 return true; 18056 } 18057 18058 @Override 18059 public boolean getBlockUninstallForUser(String packageName, int userId) { 18060 synchronized (mPackages) { 18061 final PackageSetting ps = mSettings.mPackages.get(packageName); 18062 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 18063 return false; 18064 } 18065 return mSettings.getBlockUninstallLPr(userId, packageName); 18066 } 18067 } 18068 18069 @Override 18070 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18071 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 18072 synchronized (mPackages) { 18073 PackageSetting ps = mSettings.mPackages.get(packageName); 18074 if (ps == null) { 18075 Log.w(TAG, "Package doesn't exist: " + packageName); 18076 return false; 18077 } 18078 if (systemUserApp) { 18079 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18080 } else { 18081 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18082 } 18083 mSettings.writeLPr(); 18084 } 18085 return true; 18086 } 18087 18088 /* 18089 * This method handles package deletion in general 18090 */ 18091 private boolean deletePackageLIF(String packageName, UserHandle user, 18092 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18093 PackageRemovedInfo outInfo, boolean writeSettings, 18094 PackageParser.Package replacingPackage) { 18095 if (packageName == null) { 18096 Slog.w(TAG, "Attempt to delete null packageName."); 18097 return false; 18098 } 18099 18100 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18101 18102 PackageSetting ps; 18103 synchronized (mPackages) { 18104 ps = mSettings.mPackages.get(packageName); 18105 if (ps == null) { 18106 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18107 return false; 18108 } 18109 18110 if (ps.parentPackageName != null && (!isSystemApp(ps) 18111 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18112 if (DEBUG_REMOVE) { 18113 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18114 + ((user == null) ? UserHandle.USER_ALL : user)); 18115 } 18116 final int removedUserId = (user != null) ? user.getIdentifier() 18117 : UserHandle.USER_ALL; 18118 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18119 return false; 18120 } 18121 markPackageUninstalledForUserLPw(ps, user); 18122 scheduleWritePackageRestrictionsLocked(user); 18123 return true; 18124 } 18125 } 18126 18127 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18128 && user.getIdentifier() != UserHandle.USER_ALL)) { 18129 // The caller is asking that the package only be deleted for a single 18130 // user. To do this, we just mark its uninstalled state and delete 18131 // its data. If this is a system app, we only allow this to happen if 18132 // they have set the special DELETE_SYSTEM_APP which requests different 18133 // semantics than normal for uninstalling system apps. 18134 markPackageUninstalledForUserLPw(ps, user); 18135 18136 if (!isSystemApp(ps)) { 18137 // Do not uninstall the APK if an app should be cached 18138 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18139 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18140 // Other user still have this package installed, so all 18141 // we need to do is clear this user's data and save that 18142 // it is uninstalled. 18143 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18144 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18145 return false; 18146 } 18147 scheduleWritePackageRestrictionsLocked(user); 18148 return true; 18149 } else { 18150 // We need to set it back to 'installed' so the uninstall 18151 // broadcasts will be sent correctly. 18152 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18153 ps.setInstalled(true, user.getIdentifier()); 18154 mSettings.writeKernelMappingLPr(ps); 18155 } 18156 } else { 18157 // This is a system app, so we assume that the 18158 // other users still have this package installed, so all 18159 // we need to do is clear this user's data and save that 18160 // it is uninstalled. 18161 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18162 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18163 return false; 18164 } 18165 scheduleWritePackageRestrictionsLocked(user); 18166 return true; 18167 } 18168 } 18169 18170 // If we are deleting a composite package for all users, keep track 18171 // of result for each child. 18172 if (ps.childPackageNames != null && outInfo != null) { 18173 synchronized (mPackages) { 18174 final int childCount = ps.childPackageNames.size(); 18175 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18176 for (int i = 0; i < childCount; i++) { 18177 String childPackageName = ps.childPackageNames.get(i); 18178 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18179 childInfo.removedPackage = childPackageName; 18180 childInfo.installerPackageName = ps.installerPackageName; 18181 outInfo.removedChildPackages.put(childPackageName, childInfo); 18182 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18183 if (childPs != null) { 18184 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18185 } 18186 } 18187 } 18188 } 18189 18190 boolean ret = false; 18191 if (isSystemApp(ps)) { 18192 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18193 // When an updated system application is deleted we delete the existing resources 18194 // as well and fall back to existing code in system partition 18195 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18196 } else { 18197 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18198 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18199 outInfo, writeSettings, replacingPackage); 18200 } 18201 18202 // Take a note whether we deleted the package for all users 18203 if (outInfo != null) { 18204 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18205 if (outInfo.removedChildPackages != null) { 18206 synchronized (mPackages) { 18207 final int childCount = outInfo.removedChildPackages.size(); 18208 for (int i = 0; i < childCount; i++) { 18209 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18210 if (childInfo != null) { 18211 childInfo.removedForAllUsers = mPackages.get( 18212 childInfo.removedPackage) == null; 18213 } 18214 } 18215 } 18216 } 18217 // If we uninstalled an update to a system app there may be some 18218 // child packages that appeared as they are declared in the system 18219 // app but were not declared in the update. 18220 if (isSystemApp(ps)) { 18221 synchronized (mPackages) { 18222 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18223 final int childCount = (updatedPs.childPackageNames != null) 18224 ? updatedPs.childPackageNames.size() : 0; 18225 for (int i = 0; i < childCount; i++) { 18226 String childPackageName = updatedPs.childPackageNames.get(i); 18227 if (outInfo.removedChildPackages == null 18228 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18229 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18230 if (childPs == null) { 18231 continue; 18232 } 18233 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18234 installRes.name = childPackageName; 18235 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18236 installRes.pkg = mPackages.get(childPackageName); 18237 installRes.uid = childPs.pkg.applicationInfo.uid; 18238 if (outInfo.appearedChildPackages == null) { 18239 outInfo.appearedChildPackages = new ArrayMap<>(); 18240 } 18241 outInfo.appearedChildPackages.put(childPackageName, installRes); 18242 } 18243 } 18244 } 18245 } 18246 } 18247 18248 return ret; 18249 } 18250 18251 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18252 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18253 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18254 for (int nextUserId : userIds) { 18255 if (DEBUG_REMOVE) { 18256 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18257 } 18258 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18259 false /*installed*/, 18260 true /*stopped*/, 18261 true /*notLaunched*/, 18262 false /*hidden*/, 18263 false /*suspended*/, 18264 false /*instantApp*/, 18265 false /*virtualPreload*/, 18266 null /*lastDisableAppCaller*/, 18267 null /*enabledComponents*/, 18268 null /*disabledComponents*/, 18269 ps.readUserState(nextUserId).domainVerificationStatus, 18270 0, PackageManager.INSTALL_REASON_UNKNOWN); 18271 } 18272 mSettings.writeKernelMappingLPr(ps); 18273 } 18274 18275 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18276 PackageRemovedInfo outInfo) { 18277 final PackageParser.Package pkg; 18278 synchronized (mPackages) { 18279 pkg = mPackages.get(ps.name); 18280 } 18281 18282 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18283 : new int[] {userId}; 18284 for (int nextUserId : userIds) { 18285 if (DEBUG_REMOVE) { 18286 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18287 + nextUserId); 18288 } 18289 18290 destroyAppDataLIF(pkg, userId, 18291 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18292 destroyAppProfilesLIF(pkg, userId); 18293 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18294 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18295 schedulePackageCleaning(ps.name, nextUserId, false); 18296 synchronized (mPackages) { 18297 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18298 scheduleWritePackageRestrictionsLocked(nextUserId); 18299 } 18300 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18301 } 18302 } 18303 18304 if (outInfo != null) { 18305 outInfo.removedPackage = ps.name; 18306 outInfo.installerPackageName = ps.installerPackageName; 18307 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18308 outInfo.removedAppId = ps.appId; 18309 outInfo.removedUsers = userIds; 18310 outInfo.broadcastUsers = userIds; 18311 } 18312 18313 return true; 18314 } 18315 18316 private final class ClearStorageConnection implements ServiceConnection { 18317 IMediaContainerService mContainerService; 18318 18319 @Override 18320 public void onServiceConnected(ComponentName name, IBinder service) { 18321 synchronized (this) { 18322 mContainerService = IMediaContainerService.Stub 18323 .asInterface(Binder.allowBlocking(service)); 18324 notifyAll(); 18325 } 18326 } 18327 18328 @Override 18329 public void onServiceDisconnected(ComponentName name) { 18330 } 18331 } 18332 18333 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18334 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18335 18336 final boolean mounted; 18337 if (Environment.isExternalStorageEmulated()) { 18338 mounted = true; 18339 } else { 18340 final String status = Environment.getExternalStorageState(); 18341 18342 mounted = status.equals(Environment.MEDIA_MOUNTED) 18343 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18344 } 18345 18346 if (!mounted) { 18347 return; 18348 } 18349 18350 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18351 int[] users; 18352 if (userId == UserHandle.USER_ALL) { 18353 users = sUserManager.getUserIds(); 18354 } else { 18355 users = new int[] { userId }; 18356 } 18357 final ClearStorageConnection conn = new ClearStorageConnection(); 18358 if (mContext.bindServiceAsUser( 18359 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18360 try { 18361 for (int curUser : users) { 18362 long timeout = SystemClock.uptimeMillis() + 5000; 18363 synchronized (conn) { 18364 long now; 18365 while (conn.mContainerService == null && 18366 (now = SystemClock.uptimeMillis()) < timeout) { 18367 try { 18368 conn.wait(timeout - now); 18369 } catch (InterruptedException e) { 18370 } 18371 } 18372 } 18373 if (conn.mContainerService == null) { 18374 return; 18375 } 18376 18377 final UserEnvironment userEnv = new UserEnvironment(curUser); 18378 clearDirectory(conn.mContainerService, 18379 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18380 if (allData) { 18381 clearDirectory(conn.mContainerService, 18382 userEnv.buildExternalStorageAppDataDirs(packageName)); 18383 clearDirectory(conn.mContainerService, 18384 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18385 } 18386 } 18387 } finally { 18388 mContext.unbindService(conn); 18389 } 18390 } 18391 } 18392 18393 @Override 18394 public void clearApplicationProfileData(String packageName) { 18395 enforceSystemOrRoot("Only the system can clear all profile data"); 18396 18397 final PackageParser.Package pkg; 18398 synchronized (mPackages) { 18399 pkg = mPackages.get(packageName); 18400 } 18401 18402 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18403 synchronized (mInstallLock) { 18404 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18405 } 18406 } 18407 } 18408 18409 @Override 18410 public void clearApplicationUserData(final String packageName, 18411 final IPackageDataObserver observer, final int userId) { 18412 mContext.enforceCallingOrSelfPermission( 18413 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18414 18415 final int callingUid = Binder.getCallingUid(); 18416 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18417 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18418 18419 final PackageSetting ps = mSettings.getPackageLPr(packageName); 18420 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 18421 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18422 throw new SecurityException("Cannot clear data for a protected package: " 18423 + packageName); 18424 } 18425 // Queue up an async operation since the package deletion may take a little while. 18426 mHandler.post(new Runnable() { 18427 public void run() { 18428 mHandler.removeCallbacks(this); 18429 final boolean succeeded; 18430 if (!filterApp) { 18431 try (PackageFreezer freezer = freezePackage(packageName, 18432 "clearApplicationUserData")) { 18433 synchronized (mInstallLock) { 18434 succeeded = clearApplicationUserDataLIF(packageName, userId); 18435 } 18436 clearExternalStorageDataSync(packageName, userId, true); 18437 synchronized (mPackages) { 18438 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18439 packageName, userId); 18440 } 18441 } 18442 if (succeeded) { 18443 // invoke DeviceStorageMonitor's update method to clear any notifications 18444 DeviceStorageMonitorInternal dsm = LocalServices 18445 .getService(DeviceStorageMonitorInternal.class); 18446 if (dsm != null) { 18447 dsm.checkMemory(); 18448 } 18449 } 18450 } else { 18451 succeeded = false; 18452 } 18453 if (observer != null) { 18454 try { 18455 observer.onRemoveCompleted(packageName, succeeded); 18456 } catch (RemoteException e) { 18457 Log.i(TAG, "Observer no longer exists."); 18458 } 18459 } //end if observer 18460 } //end run 18461 }); 18462 } 18463 18464 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18465 if (packageName == null) { 18466 Slog.w(TAG, "Attempt to delete null packageName."); 18467 return false; 18468 } 18469 18470 // Try finding details about the requested package 18471 PackageParser.Package pkg; 18472 synchronized (mPackages) { 18473 pkg = mPackages.get(packageName); 18474 if (pkg == null) { 18475 final PackageSetting ps = mSettings.mPackages.get(packageName); 18476 if (ps != null) { 18477 pkg = ps.pkg; 18478 } 18479 } 18480 18481 if (pkg == null) { 18482 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18483 return false; 18484 } 18485 18486 PackageSetting ps = (PackageSetting) pkg.mExtras; 18487 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18488 } 18489 18490 clearAppDataLIF(pkg, userId, 18491 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18492 18493 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18494 removeKeystoreDataIfNeeded(userId, appId); 18495 18496 UserManagerInternal umInternal = getUserManagerInternal(); 18497 final int flags; 18498 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18499 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18500 } else if (umInternal.isUserRunning(userId)) { 18501 flags = StorageManager.FLAG_STORAGE_DE; 18502 } else { 18503 flags = 0; 18504 } 18505 prepareAppDataContentsLIF(pkg, userId, flags); 18506 18507 return true; 18508 } 18509 18510 /** 18511 * Reverts user permission state changes (permissions and flags) in 18512 * all packages for a given user. 18513 * 18514 * @param userId The device user for which to do a reset. 18515 */ 18516 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18517 final int packageCount = mPackages.size(); 18518 for (int i = 0; i < packageCount; i++) { 18519 PackageParser.Package pkg = mPackages.valueAt(i); 18520 PackageSetting ps = (PackageSetting) pkg.mExtras; 18521 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18522 } 18523 } 18524 18525 private void resetNetworkPolicies(int userId) { 18526 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18527 } 18528 18529 /** 18530 * Reverts user permission state changes (permissions and flags). 18531 * 18532 * @param ps The package for which to reset. 18533 * @param userId The device user for which to do a reset. 18534 */ 18535 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18536 final PackageSetting ps, final int userId) { 18537 if (ps.pkg == null) { 18538 return; 18539 } 18540 18541 // These are flags that can change base on user actions. 18542 final int userSettableMask = FLAG_PERMISSION_USER_SET 18543 | FLAG_PERMISSION_USER_FIXED 18544 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18545 | FLAG_PERMISSION_REVIEW_REQUIRED; 18546 18547 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18548 | FLAG_PERMISSION_POLICY_FIXED; 18549 18550 boolean writeInstallPermissions = false; 18551 boolean writeRuntimePermissions = false; 18552 18553 final int permissionCount = ps.pkg.requestedPermissions.size(); 18554 for (int i = 0; i < permissionCount; i++) { 18555 final String permName = ps.pkg.requestedPermissions.get(i); 18556 final BasePermission bp = 18557 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 18558 if (bp == null) { 18559 continue; 18560 } 18561 18562 // If shared user we just reset the state to which only this app contributed. 18563 if (ps.sharedUser != null) { 18564 boolean used = false; 18565 final int packageCount = ps.sharedUser.packages.size(); 18566 for (int j = 0; j < packageCount; j++) { 18567 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18568 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18569 && pkg.pkg.requestedPermissions.contains(permName)) { 18570 used = true; 18571 break; 18572 } 18573 } 18574 if (used) { 18575 continue; 18576 } 18577 } 18578 18579 final PermissionsState permissionsState = ps.getPermissionsState(); 18580 18581 final int oldFlags = permissionsState.getPermissionFlags(permName, userId); 18582 18583 // Always clear the user settable flags. 18584 final boolean hasInstallState = 18585 permissionsState.getInstallPermissionState(permName) != null; 18586 // If permission review is enabled and this is a legacy app, mark the 18587 // permission as requiring a review as this is the initial state. 18588 int flags = 0; 18589 if (mSettings.mPermissions.mPermissionReviewRequired 18590 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18591 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18592 } 18593 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18594 if (hasInstallState) { 18595 writeInstallPermissions = true; 18596 } else { 18597 writeRuntimePermissions = true; 18598 } 18599 } 18600 18601 // Below is only runtime permission handling. 18602 if (!bp.isRuntime()) { 18603 continue; 18604 } 18605 18606 // Never clobber system or policy. 18607 if ((oldFlags & policyOrSystemFlags) != 0) { 18608 continue; 18609 } 18610 18611 // If this permission was granted by default, make sure it is. 18612 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18613 if (permissionsState.grantRuntimePermission(bp, userId) 18614 != PERMISSION_OPERATION_FAILURE) { 18615 writeRuntimePermissions = true; 18616 } 18617 // If permission review is enabled the permissions for a legacy apps 18618 // are represented as constantly granted runtime ones, so don't revoke. 18619 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18620 // Otherwise, reset the permission. 18621 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18622 switch (revokeResult) { 18623 case PERMISSION_OPERATION_SUCCESS: 18624 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18625 writeRuntimePermissions = true; 18626 final int appId = ps.appId; 18627 mHandler.post(new Runnable() { 18628 @Override 18629 public void run() { 18630 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18631 } 18632 }); 18633 } break; 18634 } 18635 } 18636 } 18637 18638 // Synchronously write as we are taking permissions away. 18639 if (writeRuntimePermissions) { 18640 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18641 } 18642 18643 // Synchronously write as we are taking permissions away. 18644 if (writeInstallPermissions) { 18645 mSettings.writeLPr(); 18646 } 18647 } 18648 18649 /** 18650 * Remove entries from the keystore daemon. Will only remove it if the 18651 * {@code appId} is valid. 18652 */ 18653 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18654 if (appId < 0) { 18655 return; 18656 } 18657 18658 final KeyStore keyStore = KeyStore.getInstance(); 18659 if (keyStore != null) { 18660 if (userId == UserHandle.USER_ALL) { 18661 for (final int individual : sUserManager.getUserIds()) { 18662 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18663 } 18664 } else { 18665 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18666 } 18667 } else { 18668 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18669 } 18670 } 18671 18672 @Override 18673 public void deleteApplicationCacheFiles(final String packageName, 18674 final IPackageDataObserver observer) { 18675 final int userId = UserHandle.getCallingUserId(); 18676 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18677 } 18678 18679 @Override 18680 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18681 final IPackageDataObserver observer) { 18682 final int callingUid = Binder.getCallingUid(); 18683 mContext.enforceCallingOrSelfPermission( 18684 android.Manifest.permission.DELETE_CACHE_FILES, null); 18685 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18686 /* requireFullPermission= */ true, /* checkShell= */ false, 18687 "delete application cache files"); 18688 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 18689 android.Manifest.permission.ACCESS_INSTANT_APPS); 18690 18691 final PackageParser.Package pkg; 18692 synchronized (mPackages) { 18693 pkg = mPackages.get(packageName); 18694 } 18695 18696 // Queue up an async operation since the package deletion may take a little while. 18697 mHandler.post(new Runnable() { 18698 public void run() { 18699 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 18700 boolean doClearData = true; 18701 if (ps != null) { 18702 final boolean targetIsInstantApp = 18703 ps.getInstantApp(UserHandle.getUserId(callingUid)); 18704 doClearData = !targetIsInstantApp 18705 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 18706 } 18707 if (doClearData) { 18708 synchronized (mInstallLock) { 18709 final int flags = StorageManager.FLAG_STORAGE_DE 18710 | StorageManager.FLAG_STORAGE_CE; 18711 // We're only clearing cache files, so we don't care if the 18712 // app is unfrozen and still able to run 18713 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18714 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18715 } 18716 clearExternalStorageDataSync(packageName, userId, false); 18717 } 18718 if (observer != null) { 18719 try { 18720 observer.onRemoveCompleted(packageName, true); 18721 } catch (RemoteException e) { 18722 Log.i(TAG, "Observer no longer exists."); 18723 } 18724 } 18725 } 18726 }); 18727 } 18728 18729 @Override 18730 public void getPackageSizeInfo(final String packageName, int userHandle, 18731 final IPackageStatsObserver observer) { 18732 throw new UnsupportedOperationException( 18733 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 18734 } 18735 18736 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18737 final PackageSetting ps; 18738 synchronized (mPackages) { 18739 ps = mSettings.mPackages.get(packageName); 18740 if (ps == null) { 18741 Slog.w(TAG, "Failed to find settings for " + packageName); 18742 return false; 18743 } 18744 } 18745 18746 final String[] packageNames = { packageName }; 18747 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18748 final String[] codePaths = { ps.codePathString }; 18749 18750 try { 18751 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18752 ps.appId, ceDataInodes, codePaths, stats); 18753 18754 // For now, ignore code size of packages on system partition 18755 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18756 stats.codeSize = 0; 18757 } 18758 18759 // External clients expect these to be tracked separately 18760 stats.dataSize -= stats.cacheSize; 18761 18762 } catch (InstallerException e) { 18763 Slog.w(TAG, String.valueOf(e)); 18764 return false; 18765 } 18766 18767 return true; 18768 } 18769 18770 private int getUidTargetSdkVersionLockedLPr(int uid) { 18771 Object obj = mSettings.getUserIdLPr(uid); 18772 if (obj instanceof SharedUserSetting) { 18773 final SharedUserSetting sus = (SharedUserSetting) obj; 18774 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18775 final Iterator<PackageSetting> it = sus.packages.iterator(); 18776 while (it.hasNext()) { 18777 final PackageSetting ps = it.next(); 18778 if (ps.pkg != null) { 18779 int v = ps.pkg.applicationInfo.targetSdkVersion; 18780 if (v < vers) vers = v; 18781 } 18782 } 18783 return vers; 18784 } else if (obj instanceof PackageSetting) { 18785 final PackageSetting ps = (PackageSetting) obj; 18786 if (ps.pkg != null) { 18787 return ps.pkg.applicationInfo.targetSdkVersion; 18788 } 18789 } 18790 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18791 } 18792 18793 @Override 18794 public void addPreferredActivity(IntentFilter filter, int match, 18795 ComponentName[] set, ComponentName activity, int userId) { 18796 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18797 "Adding preferred"); 18798 } 18799 18800 private void addPreferredActivityInternal(IntentFilter filter, int match, 18801 ComponentName[] set, ComponentName activity, boolean always, int userId, 18802 String opname) { 18803 // writer 18804 int callingUid = Binder.getCallingUid(); 18805 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18806 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18807 if (filter.countActions() == 0) { 18808 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18809 return; 18810 } 18811 synchronized (mPackages) { 18812 if (mContext.checkCallingOrSelfPermission( 18813 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18814 != PackageManager.PERMISSION_GRANTED) { 18815 if (getUidTargetSdkVersionLockedLPr(callingUid) 18816 < Build.VERSION_CODES.FROYO) { 18817 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18818 + callingUid); 18819 return; 18820 } 18821 mContext.enforceCallingOrSelfPermission( 18822 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18823 } 18824 18825 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18826 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18827 + userId + ":"); 18828 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18829 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18830 scheduleWritePackageRestrictionsLocked(userId); 18831 postPreferredActivityChangedBroadcast(userId); 18832 } 18833 } 18834 18835 private void postPreferredActivityChangedBroadcast(int userId) { 18836 mHandler.post(() -> { 18837 final IActivityManager am = ActivityManager.getService(); 18838 if (am == null) { 18839 return; 18840 } 18841 18842 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18843 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18844 try { 18845 am.broadcastIntent(null, intent, null, null, 18846 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18847 null, false, false, userId); 18848 } catch (RemoteException e) { 18849 } 18850 }); 18851 } 18852 18853 @Override 18854 public void replacePreferredActivity(IntentFilter filter, int match, 18855 ComponentName[] set, ComponentName activity, int userId) { 18856 if (filter.countActions() != 1) { 18857 throw new IllegalArgumentException( 18858 "replacePreferredActivity expects filter to have only 1 action."); 18859 } 18860 if (filter.countDataAuthorities() != 0 18861 || filter.countDataPaths() != 0 18862 || filter.countDataSchemes() > 1 18863 || filter.countDataTypes() != 0) { 18864 throw new IllegalArgumentException( 18865 "replacePreferredActivity expects filter to have no data authorities, " + 18866 "paths, or types; and at most one scheme."); 18867 } 18868 18869 final int callingUid = Binder.getCallingUid(); 18870 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18871 true /* requireFullPermission */, false /* checkShell */, 18872 "replace preferred activity"); 18873 synchronized (mPackages) { 18874 if (mContext.checkCallingOrSelfPermission( 18875 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18876 != PackageManager.PERMISSION_GRANTED) { 18877 if (getUidTargetSdkVersionLockedLPr(callingUid) 18878 < Build.VERSION_CODES.FROYO) { 18879 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18880 + Binder.getCallingUid()); 18881 return; 18882 } 18883 mContext.enforceCallingOrSelfPermission( 18884 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18885 } 18886 18887 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18888 if (pir != null) { 18889 // Get all of the existing entries that exactly match this filter. 18890 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18891 if (existing != null && existing.size() == 1) { 18892 PreferredActivity cur = existing.get(0); 18893 if (DEBUG_PREFERRED) { 18894 Slog.i(TAG, "Checking replace of preferred:"); 18895 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18896 if (!cur.mPref.mAlways) { 18897 Slog.i(TAG, " -- CUR; not mAlways!"); 18898 } else { 18899 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18900 Slog.i(TAG, " -- CUR: mSet=" 18901 + Arrays.toString(cur.mPref.mSetComponents)); 18902 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18903 Slog.i(TAG, " -- NEW: mMatch=" 18904 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18905 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18906 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18907 } 18908 } 18909 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18910 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18911 && cur.mPref.sameSet(set)) { 18912 // Setting the preferred activity to what it happens to be already 18913 if (DEBUG_PREFERRED) { 18914 Slog.i(TAG, "Replacing with same preferred activity " 18915 + cur.mPref.mShortComponent + " for user " 18916 + userId + ":"); 18917 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18918 } 18919 return; 18920 } 18921 } 18922 18923 if (existing != null) { 18924 if (DEBUG_PREFERRED) { 18925 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18926 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18927 } 18928 for (int i = 0; i < existing.size(); i++) { 18929 PreferredActivity pa = existing.get(i); 18930 if (DEBUG_PREFERRED) { 18931 Slog.i(TAG, "Removing existing preferred activity " 18932 + pa.mPref.mComponent + ":"); 18933 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18934 } 18935 pir.removeFilter(pa); 18936 } 18937 } 18938 } 18939 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18940 "Replacing preferred"); 18941 } 18942 } 18943 18944 @Override 18945 public void clearPackagePreferredActivities(String packageName) { 18946 final int callingUid = Binder.getCallingUid(); 18947 if (getInstantAppPackageName(callingUid) != null) { 18948 return; 18949 } 18950 // writer 18951 synchronized (mPackages) { 18952 PackageParser.Package pkg = mPackages.get(packageName); 18953 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 18954 if (mContext.checkCallingOrSelfPermission( 18955 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18956 != PackageManager.PERMISSION_GRANTED) { 18957 if (getUidTargetSdkVersionLockedLPr(callingUid) 18958 < Build.VERSION_CODES.FROYO) { 18959 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18960 + callingUid); 18961 return; 18962 } 18963 mContext.enforceCallingOrSelfPermission( 18964 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18965 } 18966 } 18967 final PackageSetting ps = mSettings.getPackageLPr(packageName); 18968 if (ps != null 18969 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 18970 return; 18971 } 18972 int user = UserHandle.getCallingUserId(); 18973 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18974 scheduleWritePackageRestrictionsLocked(user); 18975 } 18976 } 18977 } 18978 18979 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18980 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 18981 ArrayList<PreferredActivity> removed = null; 18982 boolean changed = false; 18983 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18984 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 18985 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18986 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 18987 continue; 18988 } 18989 Iterator<PreferredActivity> it = pir.filterIterator(); 18990 while (it.hasNext()) { 18991 PreferredActivity pa = it.next(); 18992 // Mark entry for removal only if it matches the package name 18993 // and the entry is of type "always". 18994 if (packageName == null || 18995 (pa.mPref.mComponent.getPackageName().equals(packageName) 18996 && pa.mPref.mAlways)) { 18997 if (removed == null) { 18998 removed = new ArrayList<PreferredActivity>(); 18999 } 19000 removed.add(pa); 19001 } 19002 } 19003 if (removed != null) { 19004 for (int j=0; j<removed.size(); j++) { 19005 PreferredActivity pa = removed.get(j); 19006 pir.removeFilter(pa); 19007 } 19008 changed = true; 19009 } 19010 } 19011 if (changed) { 19012 postPreferredActivityChangedBroadcast(userId); 19013 } 19014 return changed; 19015 } 19016 19017 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19018 private void clearIntentFilterVerificationsLPw(int userId) { 19019 final int packageCount = mPackages.size(); 19020 for (int i = 0; i < packageCount; i++) { 19021 PackageParser.Package pkg = mPackages.valueAt(i); 19022 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19023 } 19024 } 19025 19026 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19027 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19028 if (userId == UserHandle.USER_ALL) { 19029 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19030 sUserManager.getUserIds())) { 19031 for (int oneUserId : sUserManager.getUserIds()) { 19032 scheduleWritePackageRestrictionsLocked(oneUserId); 19033 } 19034 } 19035 } else { 19036 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19037 scheduleWritePackageRestrictionsLocked(userId); 19038 } 19039 } 19040 } 19041 19042 /** Clears state for all users, and touches intent filter verification policy */ 19043 void clearDefaultBrowserIfNeeded(String packageName) { 19044 for (int oneUserId : sUserManager.getUserIds()) { 19045 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19046 } 19047 } 19048 19049 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19050 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19051 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19052 if (packageName.equals(defaultBrowserPackageName)) { 19053 setDefaultBrowserPackageName(null, userId); 19054 } 19055 } 19056 } 19057 19058 @Override 19059 public void resetApplicationPreferences(int userId) { 19060 mContext.enforceCallingOrSelfPermission( 19061 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19062 final long identity = Binder.clearCallingIdentity(); 19063 // writer 19064 try { 19065 synchronized (mPackages) { 19066 clearPackagePreferredActivitiesLPw(null, userId); 19067 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19068 // TODO: We have to reset the default SMS and Phone. This requires 19069 // significant refactoring to keep all default apps in the package 19070 // manager (cleaner but more work) or have the services provide 19071 // callbacks to the package manager to request a default app reset. 19072 applyFactoryDefaultBrowserLPw(userId); 19073 clearIntentFilterVerificationsLPw(userId); 19074 primeDomainVerificationsLPw(userId); 19075 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19076 scheduleWritePackageRestrictionsLocked(userId); 19077 } 19078 resetNetworkPolicies(userId); 19079 } finally { 19080 Binder.restoreCallingIdentity(identity); 19081 } 19082 } 19083 19084 @Override 19085 public int getPreferredActivities(List<IntentFilter> outFilters, 19086 List<ComponentName> outActivities, String packageName) { 19087 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19088 return 0; 19089 } 19090 int num = 0; 19091 final int userId = UserHandle.getCallingUserId(); 19092 // reader 19093 synchronized (mPackages) { 19094 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19095 if (pir != null) { 19096 final Iterator<PreferredActivity> it = pir.filterIterator(); 19097 while (it.hasNext()) { 19098 final PreferredActivity pa = it.next(); 19099 if (packageName == null 19100 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19101 && pa.mPref.mAlways)) { 19102 if (outFilters != null) { 19103 outFilters.add(new IntentFilter(pa)); 19104 } 19105 if (outActivities != null) { 19106 outActivities.add(pa.mPref.mComponent); 19107 } 19108 } 19109 } 19110 } 19111 } 19112 19113 return num; 19114 } 19115 19116 @Override 19117 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19118 int userId) { 19119 int callingUid = Binder.getCallingUid(); 19120 if (callingUid != Process.SYSTEM_UID) { 19121 throw new SecurityException( 19122 "addPersistentPreferredActivity can only be run by the system"); 19123 } 19124 if (filter.countActions() == 0) { 19125 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19126 return; 19127 } 19128 synchronized (mPackages) { 19129 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19130 ":"); 19131 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19132 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19133 new PersistentPreferredActivity(filter, activity)); 19134 scheduleWritePackageRestrictionsLocked(userId); 19135 postPreferredActivityChangedBroadcast(userId); 19136 } 19137 } 19138 19139 @Override 19140 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19141 int callingUid = Binder.getCallingUid(); 19142 if (callingUid != Process.SYSTEM_UID) { 19143 throw new SecurityException( 19144 "clearPackagePersistentPreferredActivities can only be run by the system"); 19145 } 19146 ArrayList<PersistentPreferredActivity> removed = null; 19147 boolean changed = false; 19148 synchronized (mPackages) { 19149 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19150 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19151 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19152 .valueAt(i); 19153 if (userId != thisUserId) { 19154 continue; 19155 } 19156 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19157 while (it.hasNext()) { 19158 PersistentPreferredActivity ppa = it.next(); 19159 // Mark entry for removal only if it matches the package name. 19160 if (ppa.mComponent.getPackageName().equals(packageName)) { 19161 if (removed == null) { 19162 removed = new ArrayList<PersistentPreferredActivity>(); 19163 } 19164 removed.add(ppa); 19165 } 19166 } 19167 if (removed != null) { 19168 for (int j=0; j<removed.size(); j++) { 19169 PersistentPreferredActivity ppa = removed.get(j); 19170 ppir.removeFilter(ppa); 19171 } 19172 changed = true; 19173 } 19174 } 19175 19176 if (changed) { 19177 scheduleWritePackageRestrictionsLocked(userId); 19178 postPreferredActivityChangedBroadcast(userId); 19179 } 19180 } 19181 } 19182 19183 /** 19184 * Common machinery for picking apart a restored XML blob and passing 19185 * it to a caller-supplied functor to be applied to the running system. 19186 */ 19187 private void restoreFromXml(XmlPullParser parser, int userId, 19188 String expectedStartTag, BlobXmlRestorer functor) 19189 throws IOException, XmlPullParserException { 19190 int type; 19191 while ((type = parser.next()) != XmlPullParser.START_TAG 19192 && type != XmlPullParser.END_DOCUMENT) { 19193 } 19194 if (type != XmlPullParser.START_TAG) { 19195 // oops didn't find a start tag?! 19196 if (DEBUG_BACKUP) { 19197 Slog.e(TAG, "Didn't find start tag during restore"); 19198 } 19199 return; 19200 } 19201Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19202 // this is supposed to be TAG_PREFERRED_BACKUP 19203 if (!expectedStartTag.equals(parser.getName())) { 19204 if (DEBUG_BACKUP) { 19205 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19206 } 19207 return; 19208 } 19209 19210 // skip interfering stuff, then we're aligned with the backing implementation 19211 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19212Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19213 functor.apply(parser, userId); 19214 } 19215 19216 private interface BlobXmlRestorer { 19217 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19218 } 19219 19220 /** 19221 * Non-Binder method, support for the backup/restore mechanism: write the 19222 * full set of preferred activities in its canonical XML format. Returns the 19223 * XML output as a byte array, or null if there is none. 19224 */ 19225 @Override 19226 public byte[] getPreferredActivityBackup(int userId) { 19227 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19228 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19229 } 19230 19231 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19232 try { 19233 final XmlSerializer serializer = new FastXmlSerializer(); 19234 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19235 serializer.startDocument(null, true); 19236 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19237 19238 synchronized (mPackages) { 19239 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19240 } 19241 19242 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19243 serializer.endDocument(); 19244 serializer.flush(); 19245 } catch (Exception e) { 19246 if (DEBUG_BACKUP) { 19247 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19248 } 19249 return null; 19250 } 19251 19252 return dataStream.toByteArray(); 19253 } 19254 19255 @Override 19256 public void restorePreferredActivities(byte[] backup, int userId) { 19257 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19258 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19259 } 19260 19261 try { 19262 final XmlPullParser parser = Xml.newPullParser(); 19263 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19264 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19265 new BlobXmlRestorer() { 19266 @Override 19267 public void apply(XmlPullParser parser, int userId) 19268 throws XmlPullParserException, IOException { 19269 synchronized (mPackages) { 19270 mSettings.readPreferredActivitiesLPw(parser, userId); 19271 } 19272 } 19273 } ); 19274 } catch (Exception e) { 19275 if (DEBUG_BACKUP) { 19276 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19277 } 19278 } 19279 } 19280 19281 /** 19282 * Non-Binder method, support for the backup/restore mechanism: write the 19283 * default browser (etc) settings in its canonical XML format. Returns the default 19284 * browser XML representation as a byte array, or null if there is none. 19285 */ 19286 @Override 19287 public byte[] getDefaultAppsBackup(int userId) { 19288 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19289 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19290 } 19291 19292 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19293 try { 19294 final XmlSerializer serializer = new FastXmlSerializer(); 19295 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19296 serializer.startDocument(null, true); 19297 serializer.startTag(null, TAG_DEFAULT_APPS); 19298 19299 synchronized (mPackages) { 19300 mSettings.writeDefaultAppsLPr(serializer, userId); 19301 } 19302 19303 serializer.endTag(null, TAG_DEFAULT_APPS); 19304 serializer.endDocument(); 19305 serializer.flush(); 19306 } catch (Exception e) { 19307 if (DEBUG_BACKUP) { 19308 Slog.e(TAG, "Unable to write default apps for backup", e); 19309 } 19310 return null; 19311 } 19312 19313 return dataStream.toByteArray(); 19314 } 19315 19316 @Override 19317 public void restoreDefaultApps(byte[] backup, int userId) { 19318 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19319 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19320 } 19321 19322 try { 19323 final XmlPullParser parser = Xml.newPullParser(); 19324 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19325 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19326 new BlobXmlRestorer() { 19327 @Override 19328 public void apply(XmlPullParser parser, int userId) 19329 throws XmlPullParserException, IOException { 19330 synchronized (mPackages) { 19331 mSettings.readDefaultAppsLPw(parser, userId); 19332 } 19333 } 19334 } ); 19335 } catch (Exception e) { 19336 if (DEBUG_BACKUP) { 19337 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19338 } 19339 } 19340 } 19341 19342 @Override 19343 public byte[] getIntentFilterVerificationBackup(int userId) { 19344 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19345 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19346 } 19347 19348 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19349 try { 19350 final XmlSerializer serializer = new FastXmlSerializer(); 19351 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19352 serializer.startDocument(null, true); 19353 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19354 19355 synchronized (mPackages) { 19356 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19357 } 19358 19359 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19360 serializer.endDocument(); 19361 serializer.flush(); 19362 } catch (Exception e) { 19363 if (DEBUG_BACKUP) { 19364 Slog.e(TAG, "Unable to write default apps for backup", e); 19365 } 19366 return null; 19367 } 19368 19369 return dataStream.toByteArray(); 19370 } 19371 19372 @Override 19373 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19374 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19375 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19376 } 19377 19378 try { 19379 final XmlPullParser parser = Xml.newPullParser(); 19380 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19381 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19382 new BlobXmlRestorer() { 19383 @Override 19384 public void apply(XmlPullParser parser, int userId) 19385 throws XmlPullParserException, IOException { 19386 synchronized (mPackages) { 19387 mSettings.readAllDomainVerificationsLPr(parser, userId); 19388 mSettings.writeLPr(); 19389 } 19390 } 19391 } ); 19392 } catch (Exception e) { 19393 if (DEBUG_BACKUP) { 19394 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19395 } 19396 } 19397 } 19398 19399 @Override 19400 public byte[] getPermissionGrantBackup(int userId) { 19401 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19402 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19403 } 19404 19405 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19406 try { 19407 final XmlSerializer serializer = new FastXmlSerializer(); 19408 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19409 serializer.startDocument(null, true); 19410 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19411 19412 synchronized (mPackages) { 19413 serializeRuntimePermissionGrantsLPr(serializer, userId); 19414 } 19415 19416 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19417 serializer.endDocument(); 19418 serializer.flush(); 19419 } catch (Exception e) { 19420 if (DEBUG_BACKUP) { 19421 Slog.e(TAG, "Unable to write default apps for backup", e); 19422 } 19423 return null; 19424 } 19425 19426 return dataStream.toByteArray(); 19427 } 19428 19429 @Override 19430 public void restorePermissionGrants(byte[] backup, int userId) { 19431 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19432 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19433 } 19434 19435 try { 19436 final XmlPullParser parser = Xml.newPullParser(); 19437 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19438 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19439 new BlobXmlRestorer() { 19440 @Override 19441 public void apply(XmlPullParser parser, int userId) 19442 throws XmlPullParserException, IOException { 19443 synchronized (mPackages) { 19444 processRestoredPermissionGrantsLPr(parser, userId); 19445 } 19446 } 19447 } ); 19448 } catch (Exception e) { 19449 if (DEBUG_BACKUP) { 19450 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19451 } 19452 } 19453 } 19454 19455 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19456 throws IOException { 19457 serializer.startTag(null, TAG_ALL_GRANTS); 19458 19459 final int N = mSettings.mPackages.size(); 19460 for (int i = 0; i < N; i++) { 19461 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19462 boolean pkgGrantsKnown = false; 19463 19464 PermissionsState packagePerms = ps.getPermissionsState(); 19465 19466 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19467 final int grantFlags = state.getFlags(); 19468 // only look at grants that are not system/policy fixed 19469 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19470 final boolean isGranted = state.isGranted(); 19471 // And only back up the user-twiddled state bits 19472 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19473 final String packageName = mSettings.mPackages.keyAt(i); 19474 if (!pkgGrantsKnown) { 19475 serializer.startTag(null, TAG_GRANT); 19476 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19477 pkgGrantsKnown = true; 19478 } 19479 19480 final boolean userSet = 19481 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19482 final boolean userFixed = 19483 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19484 final boolean revoke = 19485 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19486 19487 serializer.startTag(null, TAG_PERMISSION); 19488 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19489 if (isGranted) { 19490 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19491 } 19492 if (userSet) { 19493 serializer.attribute(null, ATTR_USER_SET, "true"); 19494 } 19495 if (userFixed) { 19496 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19497 } 19498 if (revoke) { 19499 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19500 } 19501 serializer.endTag(null, TAG_PERMISSION); 19502 } 19503 } 19504 } 19505 19506 if (pkgGrantsKnown) { 19507 serializer.endTag(null, TAG_GRANT); 19508 } 19509 } 19510 19511 serializer.endTag(null, TAG_ALL_GRANTS); 19512 } 19513 19514 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19515 throws XmlPullParserException, IOException { 19516 String pkgName = null; 19517 int outerDepth = parser.getDepth(); 19518 int type; 19519 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19520 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19521 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19522 continue; 19523 } 19524 19525 final String tagName = parser.getName(); 19526 if (tagName.equals(TAG_GRANT)) { 19527 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19528 if (DEBUG_BACKUP) { 19529 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19530 } 19531 } else if (tagName.equals(TAG_PERMISSION)) { 19532 19533 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19534 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19535 19536 int newFlagSet = 0; 19537 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19538 newFlagSet |= FLAG_PERMISSION_USER_SET; 19539 } 19540 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19541 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19542 } 19543 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19544 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19545 } 19546 if (DEBUG_BACKUP) { 19547 Slog.v(TAG, " + Restoring grant:" 19548 + " pkg=" + pkgName 19549 + " perm=" + permName 19550 + " granted=" + isGranted 19551 + " bits=0x" + Integer.toHexString(newFlagSet)); 19552 } 19553 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19554 if (ps != null) { 19555 // Already installed so we apply the grant immediately 19556 if (DEBUG_BACKUP) { 19557 Slog.v(TAG, " + already installed; applying"); 19558 } 19559 PermissionsState perms = ps.getPermissionsState(); 19560 BasePermission bp = 19561 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 19562 if (bp != null) { 19563 if (isGranted) { 19564 perms.grantRuntimePermission(bp, userId); 19565 } 19566 if (newFlagSet != 0) { 19567 perms.updatePermissionFlags( 19568 bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19569 } 19570 } 19571 } else { 19572 // Need to wait for post-restore install to apply the grant 19573 if (DEBUG_BACKUP) { 19574 Slog.v(TAG, " - not yet installed; saving for later"); 19575 } 19576 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19577 isGranted, newFlagSet, userId); 19578 } 19579 } else { 19580 PackageManagerService.reportSettingsProblem(Log.WARN, 19581 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19582 XmlUtils.skipCurrentTag(parser); 19583 } 19584 } 19585 19586 scheduleWriteSettingsLocked(); 19587 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19588 } 19589 19590 @Override 19591 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19592 int sourceUserId, int targetUserId, int flags) { 19593 mContext.enforceCallingOrSelfPermission( 19594 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19595 int callingUid = Binder.getCallingUid(); 19596 enforceOwnerRights(ownerPackage, callingUid); 19597 PackageManagerServiceUtils.enforceShellRestriction( 19598 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19599 if (intentFilter.countActions() == 0) { 19600 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19601 return; 19602 } 19603 synchronized (mPackages) { 19604 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19605 ownerPackage, targetUserId, flags); 19606 CrossProfileIntentResolver resolver = 19607 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19608 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19609 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19610 if (existing != null) { 19611 int size = existing.size(); 19612 for (int i = 0; i < size; i++) { 19613 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19614 return; 19615 } 19616 } 19617 } 19618 resolver.addFilter(newFilter); 19619 scheduleWritePackageRestrictionsLocked(sourceUserId); 19620 } 19621 } 19622 19623 @Override 19624 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19625 mContext.enforceCallingOrSelfPermission( 19626 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19627 final int callingUid = Binder.getCallingUid(); 19628 enforceOwnerRights(ownerPackage, callingUid); 19629 PackageManagerServiceUtils.enforceShellRestriction( 19630 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19631 synchronized (mPackages) { 19632 CrossProfileIntentResolver resolver = 19633 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19634 ArraySet<CrossProfileIntentFilter> set = 19635 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19636 for (CrossProfileIntentFilter filter : set) { 19637 if (filter.getOwnerPackage().equals(ownerPackage)) { 19638 resolver.removeFilter(filter); 19639 } 19640 } 19641 scheduleWritePackageRestrictionsLocked(sourceUserId); 19642 } 19643 } 19644 19645 // Enforcing that callingUid is owning pkg on userId 19646 private void enforceOwnerRights(String pkg, int callingUid) { 19647 // The system owns everything. 19648 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19649 return; 19650 } 19651 final int callingUserId = UserHandle.getUserId(callingUid); 19652 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19653 if (pi == null) { 19654 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19655 + callingUserId); 19656 } 19657 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19658 throw new SecurityException("Calling uid " + callingUid 19659 + " does not own package " + pkg); 19660 } 19661 } 19662 19663 @Override 19664 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19665 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19666 return null; 19667 } 19668 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19669 } 19670 19671 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 19672 UserManagerService ums = UserManagerService.getInstance(); 19673 if (ums != null) { 19674 final UserInfo parent = ums.getProfileParent(userId); 19675 final int launcherUid = (parent != null) ? parent.id : userId; 19676 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 19677 if (launcherComponent != null) { 19678 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 19679 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 19680 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 19681 .setPackage(launcherComponent.getPackageName()); 19682 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 19683 } 19684 } 19685 } 19686 19687 /** 19688 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19689 * then reports the most likely home activity or null if there are more than one. 19690 */ 19691 private ComponentName getDefaultHomeActivity(int userId) { 19692 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19693 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19694 if (cn != null) { 19695 return cn; 19696 } 19697 19698 // Find the launcher with the highest priority and return that component if there are no 19699 // other home activity with the same priority. 19700 int lastPriority = Integer.MIN_VALUE; 19701 ComponentName lastComponent = null; 19702 final int size = allHomeCandidates.size(); 19703 for (int i = 0; i < size; i++) { 19704 final ResolveInfo ri = allHomeCandidates.get(i); 19705 if (ri.priority > lastPriority) { 19706 lastComponent = ri.activityInfo.getComponentName(); 19707 lastPriority = ri.priority; 19708 } else if (ri.priority == lastPriority) { 19709 // Two components found with same priority. 19710 lastComponent = null; 19711 } 19712 } 19713 return lastComponent; 19714 } 19715 19716 private Intent getHomeIntent() { 19717 Intent intent = new Intent(Intent.ACTION_MAIN); 19718 intent.addCategory(Intent.CATEGORY_HOME); 19719 intent.addCategory(Intent.CATEGORY_DEFAULT); 19720 return intent; 19721 } 19722 19723 private IntentFilter getHomeFilter() { 19724 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19725 filter.addCategory(Intent.CATEGORY_HOME); 19726 filter.addCategory(Intent.CATEGORY_DEFAULT); 19727 return filter; 19728 } 19729 19730 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19731 int userId) { 19732 Intent intent = getHomeIntent(); 19733 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19734 PackageManager.GET_META_DATA, userId); 19735 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19736 true, false, false, userId); 19737 19738 allHomeCandidates.clear(); 19739 if (list != null) { 19740 for (ResolveInfo ri : list) { 19741 allHomeCandidates.add(ri); 19742 } 19743 } 19744 return (preferred == null || preferred.activityInfo == null) 19745 ? null 19746 : new ComponentName(preferred.activityInfo.packageName, 19747 preferred.activityInfo.name); 19748 } 19749 19750 @Override 19751 public void setHomeActivity(ComponentName comp, int userId) { 19752 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19753 return; 19754 } 19755 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19756 getHomeActivitiesAsUser(homeActivities, userId); 19757 19758 boolean found = false; 19759 19760 final int size = homeActivities.size(); 19761 final ComponentName[] set = new ComponentName[size]; 19762 for (int i = 0; i < size; i++) { 19763 final ResolveInfo candidate = homeActivities.get(i); 19764 final ActivityInfo info = candidate.activityInfo; 19765 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19766 set[i] = activityName; 19767 if (!found && activityName.equals(comp)) { 19768 found = true; 19769 } 19770 } 19771 if (!found) { 19772 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19773 + userId); 19774 } 19775 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19776 set, comp, userId); 19777 } 19778 19779 private @Nullable String getSetupWizardPackageName() { 19780 final Intent intent = new Intent(Intent.ACTION_MAIN); 19781 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19782 19783 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19784 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19785 | MATCH_DISABLED_COMPONENTS, 19786 UserHandle.myUserId()); 19787 if (matches.size() == 1) { 19788 return matches.get(0).getComponentInfo().packageName; 19789 } else { 19790 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19791 + ": matches=" + matches); 19792 return null; 19793 } 19794 } 19795 19796 private @Nullable String getStorageManagerPackageName() { 19797 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19798 19799 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19800 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19801 | MATCH_DISABLED_COMPONENTS, 19802 UserHandle.myUserId()); 19803 if (matches.size() == 1) { 19804 return matches.get(0).getComponentInfo().packageName; 19805 } else { 19806 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19807 + matches.size() + ": matches=" + matches); 19808 return null; 19809 } 19810 } 19811 19812 @Override 19813 public void setApplicationEnabledSetting(String appPackageName, 19814 int newState, int flags, int userId, String callingPackage) { 19815 if (!sUserManager.exists(userId)) return; 19816 if (callingPackage == null) { 19817 callingPackage = Integer.toString(Binder.getCallingUid()); 19818 } 19819 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19820 } 19821 19822 @Override 19823 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 19824 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 19825 synchronized (mPackages) { 19826 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 19827 if (pkgSetting != null) { 19828 pkgSetting.setUpdateAvailable(updateAvailable); 19829 } 19830 } 19831 } 19832 19833 @Override 19834 public void setComponentEnabledSetting(ComponentName componentName, 19835 int newState, int flags, int userId) { 19836 if (!sUserManager.exists(userId)) return; 19837 setEnabledSetting(componentName.getPackageName(), 19838 componentName.getClassName(), newState, flags, userId, null); 19839 } 19840 19841 private void setEnabledSetting(final String packageName, String className, int newState, 19842 final int flags, int userId, String callingPackage) { 19843 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19844 || newState == COMPONENT_ENABLED_STATE_ENABLED 19845 || newState == COMPONENT_ENABLED_STATE_DISABLED 19846 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19847 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19848 throw new IllegalArgumentException("Invalid new component state: " 19849 + newState); 19850 } 19851 PackageSetting pkgSetting; 19852 final int callingUid = Binder.getCallingUid(); 19853 final int permission; 19854 if (callingUid == Process.SYSTEM_UID) { 19855 permission = PackageManager.PERMISSION_GRANTED; 19856 } else { 19857 permission = mContext.checkCallingOrSelfPermission( 19858 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19859 } 19860 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19861 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19862 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19863 boolean sendNow = false; 19864 boolean isApp = (className == null); 19865 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 19866 String componentName = isApp ? packageName : className; 19867 int packageUid = -1; 19868 ArrayList<String> components; 19869 19870 // reader 19871 synchronized (mPackages) { 19872 pkgSetting = mSettings.mPackages.get(packageName); 19873 if (pkgSetting == null) { 19874 if (!isCallerInstantApp) { 19875 if (className == null) { 19876 throw new IllegalArgumentException("Unknown package: " + packageName); 19877 } 19878 throw new IllegalArgumentException( 19879 "Unknown component: " + packageName + "/" + className); 19880 } else { 19881 // throw SecurityException to prevent leaking package information 19882 throw new SecurityException( 19883 "Attempt to change component state; " 19884 + "pid=" + Binder.getCallingPid() 19885 + ", uid=" + callingUid 19886 + (className == null 19887 ? ", package=" + packageName 19888 : ", component=" + packageName + "/" + className)); 19889 } 19890 } 19891 } 19892 19893 // Limit who can change which apps 19894 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 19895 // Don't allow apps that don't have permission to modify other apps 19896 if (!allowedByPermission 19897 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 19898 throw new SecurityException( 19899 "Attempt to change component state; " 19900 + "pid=" + Binder.getCallingPid() 19901 + ", uid=" + callingUid 19902 + (className == null 19903 ? ", package=" + packageName 19904 : ", component=" + packageName + "/" + className)); 19905 } 19906 // Don't allow changing protected packages. 19907 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19908 throw new SecurityException("Cannot disable a protected package: " + packageName); 19909 } 19910 } 19911 19912 synchronized (mPackages) { 19913 if (callingUid == Process.SHELL_UID 19914 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19915 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19916 // unless it is a test package. 19917 int oldState = pkgSetting.getEnabled(userId); 19918 if (className == null 19919 && 19920 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19921 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19922 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19923 && 19924 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19925 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19926 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19927 // ok 19928 } else { 19929 throw new SecurityException( 19930 "Shell cannot change component state for " + packageName + "/" 19931 + className + " to " + newState); 19932 } 19933 } 19934 } 19935 if (className == null) { 19936 // We're dealing with an application/package level state change 19937 synchronized (mPackages) { 19938 if (pkgSetting.getEnabled(userId) == newState) { 19939 // Nothing to do 19940 return; 19941 } 19942 } 19943 // If we're enabling a system stub, there's a little more work to do. 19944 // Prior to enabling the package, we need to decompress the APK(s) to the 19945 // data partition and then replace the version on the system partition. 19946 final PackageParser.Package deletedPkg = pkgSetting.pkg; 19947 final boolean isSystemStub = deletedPkg.isStub 19948 && deletedPkg.isSystem(); 19949 if (isSystemStub 19950 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19951 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 19952 final File codePath = decompressPackage(deletedPkg); 19953 if (codePath == null) { 19954 Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name); 19955 return; 19956 } 19957 // TODO remove direct parsing of the package object during internal cleanup 19958 // of scan package 19959 // We need to call parse directly here for no other reason than we need 19960 // the new package in order to disable the old one [we use the information 19961 // for some internal optimization to optionally create a new package setting 19962 // object on replace]. However, we can't get the package from the scan 19963 // because the scan modifies live structures and we need to remove the 19964 // old [system] package from the system before a scan can be attempted. 19965 // Once scan is indempotent we can remove this parse and use the package 19966 // object we scanned, prior to adding it to package settings. 19967 final PackageParser pp = new PackageParser(); 19968 pp.setSeparateProcesses(mSeparateProcesses); 19969 pp.setDisplayMetrics(mMetrics); 19970 pp.setCallback(mPackageParserCallback); 19971 final PackageParser.Package tmpPkg; 19972 try { 19973 final @ParseFlags int parseFlags = mDefParseFlags 19974 | PackageParser.PARSE_MUST_BE_APK 19975 | PackageParser.PARSE_IS_SYSTEM_DIR; 19976 tmpPkg = pp.parsePackage(codePath, parseFlags); 19977 } catch (PackageParserException e) { 19978 Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e); 19979 return; 19980 } 19981 synchronized (mInstallLock) { 19982 // Disable the stub and remove any package entries 19983 removePackageLI(deletedPkg, true); 19984 synchronized (mPackages) { 19985 disableSystemPackageLPw(deletedPkg, tmpPkg); 19986 } 19987 final PackageParser.Package pkg; 19988 try (PackageFreezer freezer = 19989 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 19990 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 19991 | PackageParser.PARSE_ENFORCE_CODE; 19992 pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 19993 0 /*currentTime*/, null /*user*/); 19994 prepareAppDataAfterInstallLIF(pkg); 19995 synchronized (mPackages) { 19996 try { 19997 updateSharedLibrariesLPr(pkg, null); 19998 } catch (PackageManagerException e) { 19999 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 20000 } 20001 mPermissionManager.updatePermissions( 20002 pkg.packageName, pkg, true, mPackages.values(), 20003 mPermissionCallback); 20004 mSettings.writeLPr(); 20005 } 20006 } catch (PackageManagerException e) { 20007 // Whoops! Something went wrong; try to roll back to the stub 20008 Slog.w(TAG, "Failed to install compressed system package:" 20009 + pkgSetting.name, e); 20010 // Remove the failed install 20011 removeCodePathLI(codePath); 20012 20013 // Install the system package 20014 try (PackageFreezer freezer = 20015 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20016 synchronized (mPackages) { 20017 // NOTE: The system package always needs to be enabled; even 20018 // if it's for a compressed stub. If we don't, installing the 20019 // system package fails during scan [scanning checks the disabled 20020 // packages]. We will reverse this later, after we've "installed" 20021 // the stub. 20022 // This leaves us in a fragile state; the stub should never be 20023 // enabled, so, cross your fingers and hope nothing goes wrong 20024 // until we can disable the package later. 20025 enableSystemPackageLPw(deletedPkg); 20026 } 20027 installPackageFromSystemLIF(deletedPkg.codePath, 20028 false /*isPrivileged*/, null /*allUserHandles*/, 20029 null /*origUserHandles*/, null /*origPermissionsState*/, 20030 true /*writeSettings*/); 20031 } catch (PackageManagerException pme) { 20032 Slog.w(TAG, "Failed to restore system package:" 20033 + deletedPkg.packageName, pme); 20034 } finally { 20035 synchronized (mPackages) { 20036 mSettings.disableSystemPackageLPw( 20037 deletedPkg.packageName, true /*replaced*/); 20038 mSettings.writeLPr(); 20039 } 20040 } 20041 return; 20042 } 20043 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE 20044 | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20045 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 20046 mDexManager.notifyPackageUpdated(pkg.packageName, 20047 pkg.baseCodePath, pkg.splitCodePaths); 20048 } 20049 } 20050 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20051 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20052 // Don't care about who enables an app. 20053 callingPackage = null; 20054 } 20055 synchronized (mPackages) { 20056 pkgSetting.setEnabled(newState, userId, callingPackage); 20057 } 20058 } else { 20059 synchronized (mPackages) { 20060 // We're dealing with a component level state change 20061 // First, verify that this is a valid class name. 20062 PackageParser.Package pkg = pkgSetting.pkg; 20063 if (pkg == null || !pkg.hasComponentClassName(className)) { 20064 if (pkg != null && 20065 pkg.applicationInfo.targetSdkVersion >= 20066 Build.VERSION_CODES.JELLY_BEAN) { 20067 throw new IllegalArgumentException("Component class " + className 20068 + " does not exist in " + packageName); 20069 } else { 20070 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20071 + className + " does not exist in " + packageName); 20072 } 20073 } 20074 switch (newState) { 20075 case COMPONENT_ENABLED_STATE_ENABLED: 20076 if (!pkgSetting.enableComponentLPw(className, userId)) { 20077 return; 20078 } 20079 break; 20080 case COMPONENT_ENABLED_STATE_DISABLED: 20081 if (!pkgSetting.disableComponentLPw(className, userId)) { 20082 return; 20083 } 20084 break; 20085 case COMPONENT_ENABLED_STATE_DEFAULT: 20086 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20087 return; 20088 } 20089 break; 20090 default: 20091 Slog.e(TAG, "Invalid new component state: " + newState); 20092 return; 20093 } 20094 } 20095 } 20096 synchronized (mPackages) { 20097 scheduleWritePackageRestrictionsLocked(userId); 20098 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 20099 final long callingId = Binder.clearCallingIdentity(); 20100 try { 20101 updateInstantAppInstallerLocked(packageName); 20102 } finally { 20103 Binder.restoreCallingIdentity(callingId); 20104 } 20105 components = mPendingBroadcasts.get(userId, packageName); 20106 final boolean newPackage = components == null; 20107 if (newPackage) { 20108 components = new ArrayList<String>(); 20109 } 20110 if (!components.contains(componentName)) { 20111 components.add(componentName); 20112 } 20113 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20114 sendNow = true; 20115 // Purge entry from pending broadcast list if another one exists already 20116 // since we are sending one right away. 20117 mPendingBroadcasts.remove(userId, packageName); 20118 } else { 20119 if (newPackage) { 20120 mPendingBroadcasts.put(userId, packageName, components); 20121 } 20122 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20123 // Schedule a message 20124 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20125 } 20126 } 20127 } 20128 20129 long callingId = Binder.clearCallingIdentity(); 20130 try { 20131 if (sendNow) { 20132 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20133 sendPackageChangedBroadcast(packageName, 20134 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20135 } 20136 } finally { 20137 Binder.restoreCallingIdentity(callingId); 20138 } 20139 } 20140 20141 @Override 20142 public void flushPackageRestrictionsAsUser(int userId) { 20143 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20144 return; 20145 } 20146 if (!sUserManager.exists(userId)) { 20147 return; 20148 } 20149 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20150 false /* checkShell */, "flushPackageRestrictions"); 20151 synchronized (mPackages) { 20152 mSettings.writePackageRestrictionsLPr(userId); 20153 mDirtyUsers.remove(userId); 20154 if (mDirtyUsers.isEmpty()) { 20155 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20156 } 20157 } 20158 } 20159 20160 private void sendPackageChangedBroadcast(String packageName, 20161 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20162 if (DEBUG_INSTALL) 20163 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20164 + componentNames); 20165 Bundle extras = new Bundle(4); 20166 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20167 String nameList[] = new String[componentNames.size()]; 20168 componentNames.toArray(nameList); 20169 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20170 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20171 extras.putInt(Intent.EXTRA_UID, packageUid); 20172 // If this is not reporting a change of the overall package, then only send it 20173 // to registered receivers. We don't want to launch a swath of apps for every 20174 // little component state change. 20175 final int flags = !componentNames.contains(packageName) 20176 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20177 final int userId = UserHandle.getUserId(packageUid); 20178 final boolean isInstantApp = isInstantApp(packageName, userId); 20179 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 20180 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 20181 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20182 userIds, instantUserIds); 20183 } 20184 20185 @Override 20186 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20187 if (!sUserManager.exists(userId)) return; 20188 final int callingUid = Binder.getCallingUid(); 20189 if (getInstantAppPackageName(callingUid) != null) { 20190 return; 20191 } 20192 final int permission = mContext.checkCallingOrSelfPermission( 20193 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20194 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20195 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20196 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20197 // writer 20198 synchronized (mPackages) { 20199 final PackageSetting ps = mSettings.mPackages.get(packageName); 20200 if (!filterAppAccessLPr(ps, callingUid, userId) 20201 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20202 allowedByPermission, callingUid, userId)) { 20203 scheduleWritePackageRestrictionsLocked(userId); 20204 } 20205 } 20206 } 20207 20208 @Override 20209 public String getInstallerPackageName(String packageName) { 20210 final int callingUid = Binder.getCallingUid(); 20211 if (getInstantAppPackageName(callingUid) != null) { 20212 return null; 20213 } 20214 // reader 20215 synchronized (mPackages) { 20216 final PackageSetting ps = mSettings.mPackages.get(packageName); 20217 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20218 return null; 20219 } 20220 return mSettings.getInstallerPackageNameLPr(packageName); 20221 } 20222 } 20223 20224 public boolean isOrphaned(String packageName) { 20225 // reader 20226 synchronized (mPackages) { 20227 return mSettings.isOrphaned(packageName); 20228 } 20229 } 20230 20231 @Override 20232 public int getApplicationEnabledSetting(String packageName, int userId) { 20233 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20234 int callingUid = Binder.getCallingUid(); 20235 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20236 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20237 // reader 20238 synchronized (mPackages) { 20239 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 20240 return COMPONENT_ENABLED_STATE_DISABLED; 20241 } 20242 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20243 } 20244 } 20245 20246 @Override 20247 public int getComponentEnabledSetting(ComponentName component, int userId) { 20248 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20249 int callingUid = Binder.getCallingUid(); 20250 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20251 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 20252 synchronized (mPackages) { 20253 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 20254 component, TYPE_UNKNOWN, userId)) { 20255 return COMPONENT_ENABLED_STATE_DISABLED; 20256 } 20257 return mSettings.getComponentEnabledSettingLPr(component, userId); 20258 } 20259 } 20260 20261 @Override 20262 public void enterSafeMode() { 20263 enforceSystemOrRoot("Only the system can request entering safe mode"); 20264 20265 if (!mSystemReady) { 20266 mSafeMode = true; 20267 } 20268 } 20269 20270 @Override 20271 public void systemReady() { 20272 enforceSystemOrRoot("Only the system can claim the system is ready"); 20273 20274 mSystemReady = true; 20275 final ContentResolver resolver = mContext.getContentResolver(); 20276 ContentObserver co = new ContentObserver(mHandler) { 20277 @Override 20278 public void onChange(boolean selfChange) { 20279 mEphemeralAppsDisabled = 20280 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20281 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20282 } 20283 }; 20284 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20285 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20286 false, co, UserHandle.USER_SYSTEM); 20287 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20288 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20289 co.onChange(true); 20290 20291 // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to 20292 // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once 20293 // it is done. 20294 ContentObserver privAppOobObserver = new ContentObserver(mHandler) { 20295 @Override 20296 public void onChange(boolean selfChange) { 20297 int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0); 20298 SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, 20299 oobEnabled == 1 ? "true" : "false"); 20300 } 20301 }; 20302 mContext.getContentResolver().registerContentObserver( 20303 Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver, 20304 UserHandle.USER_SYSTEM); 20305 // At boot, restore the value from the setting, which persists across reboot. 20306 privAppOobObserver.onChange(true); 20307 20308 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20309 // disabled after already being started. 20310 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20311 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20312 20313 // Read the compatibilty setting when the system is ready. 20314 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20315 mContext.getContentResolver(), 20316 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20317 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20318 if (DEBUG_SETTINGS) { 20319 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20320 } 20321 20322 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20323 20324 synchronized (mPackages) { 20325 // Verify that all of the preferred activity components actually 20326 // exist. It is possible for applications to be updated and at 20327 // that point remove a previously declared activity component that 20328 // had been set as a preferred activity. We try to clean this up 20329 // the next time we encounter that preferred activity, but it is 20330 // possible for the user flow to never be able to return to that 20331 // situation so here we do a sanity check to make sure we haven't 20332 // left any junk around. 20333 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20334 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20335 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20336 removed.clear(); 20337 for (PreferredActivity pa : pir.filterSet()) { 20338 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20339 removed.add(pa); 20340 } 20341 } 20342 if (removed.size() > 0) { 20343 for (int r=0; r<removed.size(); r++) { 20344 PreferredActivity pa = removed.get(r); 20345 Slog.w(TAG, "Removing dangling preferred activity: " 20346 + pa.mPref.mComponent); 20347 pir.removeFilter(pa); 20348 } 20349 mSettings.writePackageRestrictionsLPr( 20350 mSettings.mPreferredActivities.keyAt(i)); 20351 } 20352 } 20353 20354 for (int userId : UserManagerService.getInstance().getUserIds()) { 20355 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20356 grantPermissionsUserIds = ArrayUtils.appendInt( 20357 grantPermissionsUserIds, userId); 20358 } 20359 } 20360 } 20361 sUserManager.systemReady(); 20362 // If we upgraded grant all default permissions before kicking off. 20363 for (int userId : grantPermissionsUserIds) { 20364 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20365 } 20366 20367 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20368 // If we did not grant default permissions, we preload from this the 20369 // default permission exceptions lazily to ensure we don't hit the 20370 // disk on a new user creation. 20371 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20372 } 20373 20374 // Now that we've scanned all packages, and granted any default 20375 // permissions, ensure permissions are updated. Beware of dragons if you 20376 // try optimizing this. 20377 synchronized (mPackages) { 20378 mPermissionManager.updateAllPermissions( 20379 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 20380 mPermissionCallback); 20381 } 20382 20383 // Kick off any messages waiting for system ready 20384 if (mPostSystemReadyMessages != null) { 20385 for (Message msg : mPostSystemReadyMessages) { 20386 msg.sendToTarget(); 20387 } 20388 mPostSystemReadyMessages = null; 20389 } 20390 20391 // Watch for external volumes that come and go over time 20392 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20393 storage.registerListener(mStorageListener); 20394 20395 mInstallerService.systemReady(); 20396 mPackageDexOptimizer.systemReady(); 20397 20398 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20399 StorageManagerInternal.class); 20400 StorageManagerInternal.addExternalStoragePolicy( 20401 new StorageManagerInternal.ExternalStorageMountPolicy() { 20402 @Override 20403 public int getMountMode(int uid, String packageName) { 20404 if (Process.isIsolated(uid)) { 20405 return Zygote.MOUNT_EXTERNAL_NONE; 20406 } 20407 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20408 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20409 } 20410 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20411 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20412 } 20413 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20414 return Zygote.MOUNT_EXTERNAL_READ; 20415 } 20416 return Zygote.MOUNT_EXTERNAL_WRITE; 20417 } 20418 20419 @Override 20420 public boolean hasExternalStorage(int uid, String packageName) { 20421 return true; 20422 } 20423 }); 20424 20425 // Now that we're mostly running, clean up stale users and apps 20426 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20427 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20428 20429 mPermissionManager.systemReady(); 20430 } 20431 20432 public void waitForAppDataPrepared() { 20433 if (mPrepareAppDataFuture == null) { 20434 return; 20435 } 20436 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20437 mPrepareAppDataFuture = null; 20438 } 20439 20440 @Override 20441 public boolean isSafeMode() { 20442 // allow instant applications 20443 return mSafeMode; 20444 } 20445 20446 @Override 20447 public boolean hasSystemUidErrors() { 20448 // allow instant applications 20449 return mHasSystemUidErrors; 20450 } 20451 20452 static String arrayToString(int[] array) { 20453 StringBuffer buf = new StringBuffer(128); 20454 buf.append('['); 20455 if (array != null) { 20456 for (int i=0; i<array.length; i++) { 20457 if (i > 0) buf.append(", "); 20458 buf.append(array[i]); 20459 } 20460 } 20461 buf.append(']'); 20462 return buf.toString(); 20463 } 20464 20465 @Override 20466 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20467 FileDescriptor err, String[] args, ShellCallback callback, 20468 ResultReceiver resultReceiver) { 20469 (new PackageManagerShellCommand(this)).exec( 20470 this, in, out, err, args, callback, resultReceiver); 20471 } 20472 20473 @Override 20474 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20475 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20476 20477 DumpState dumpState = new DumpState(); 20478 boolean fullPreferred = false; 20479 boolean checkin = false; 20480 20481 String packageName = null; 20482 ArraySet<String> permissionNames = null; 20483 20484 int opti = 0; 20485 while (opti < args.length) { 20486 String opt = args[opti]; 20487 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20488 break; 20489 } 20490 opti++; 20491 20492 if ("-a".equals(opt)) { 20493 // Right now we only know how to print all. 20494 } else if ("-h".equals(opt)) { 20495 pw.println("Package manager dump options:"); 20496 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20497 pw.println(" --checkin: dump for a checkin"); 20498 pw.println(" -f: print details of intent filters"); 20499 pw.println(" -h: print this help"); 20500 pw.println(" cmd may be one of:"); 20501 pw.println(" l[ibraries]: list known shared libraries"); 20502 pw.println(" f[eatures]: list device features"); 20503 pw.println(" k[eysets]: print known keysets"); 20504 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20505 pw.println(" perm[issions]: dump permissions"); 20506 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20507 pw.println(" pref[erred]: print preferred package settings"); 20508 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20509 pw.println(" prov[iders]: dump content providers"); 20510 pw.println(" p[ackages]: dump installed packages"); 20511 pw.println(" s[hared-users]: dump shared user IDs"); 20512 pw.println(" m[essages]: print collected runtime messages"); 20513 pw.println(" v[erifiers]: print package verifier info"); 20514 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20515 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20516 pw.println(" version: print database version info"); 20517 pw.println(" write: write current settings now"); 20518 pw.println(" installs: details about install sessions"); 20519 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20520 pw.println(" dexopt: dump dexopt state"); 20521 pw.println(" compiler-stats: dump compiler statistics"); 20522 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20523 pw.println(" service-permissions: dump permissions required by services"); 20524 pw.println(" <package.name>: info about given package"); 20525 return; 20526 } else if ("--checkin".equals(opt)) { 20527 checkin = true; 20528 } else if ("-f".equals(opt)) { 20529 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20530 } else if ("--proto".equals(opt)) { 20531 dumpProto(fd); 20532 return; 20533 } else { 20534 pw.println("Unknown argument: " + opt + "; use -h for help"); 20535 } 20536 } 20537 20538 // Is the caller requesting to dump a particular piece of data? 20539 if (opti < args.length) { 20540 String cmd = args[opti]; 20541 opti++; 20542 // Is this a package name? 20543 if ("android".equals(cmd) || cmd.contains(".")) { 20544 packageName = cmd; 20545 // When dumping a single package, we always dump all of its 20546 // filter information since the amount of data will be reasonable. 20547 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20548 } else if ("check-permission".equals(cmd)) { 20549 if (opti >= args.length) { 20550 pw.println("Error: check-permission missing permission argument"); 20551 return; 20552 } 20553 String perm = args[opti]; 20554 opti++; 20555 if (opti >= args.length) { 20556 pw.println("Error: check-permission missing package argument"); 20557 return; 20558 } 20559 20560 String pkg = args[opti]; 20561 opti++; 20562 int user = UserHandle.getUserId(Binder.getCallingUid()); 20563 if (opti < args.length) { 20564 try { 20565 user = Integer.parseInt(args[opti]); 20566 } catch (NumberFormatException e) { 20567 pw.println("Error: check-permission user argument is not a number: " 20568 + args[opti]); 20569 return; 20570 } 20571 } 20572 20573 // Normalize package name to handle renamed packages and static libs 20574 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20575 20576 pw.println(checkPermission(perm, pkg, user)); 20577 return; 20578 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20579 dumpState.setDump(DumpState.DUMP_LIBS); 20580 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20581 dumpState.setDump(DumpState.DUMP_FEATURES); 20582 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20583 if (opti >= args.length) { 20584 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20585 | DumpState.DUMP_SERVICE_RESOLVERS 20586 | DumpState.DUMP_RECEIVER_RESOLVERS 20587 | DumpState.DUMP_CONTENT_RESOLVERS); 20588 } else { 20589 while (opti < args.length) { 20590 String name = args[opti]; 20591 if ("a".equals(name) || "activity".equals(name)) { 20592 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20593 } else if ("s".equals(name) || "service".equals(name)) { 20594 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20595 } else if ("r".equals(name) || "receiver".equals(name)) { 20596 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20597 } else if ("c".equals(name) || "content".equals(name)) { 20598 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20599 } else { 20600 pw.println("Error: unknown resolver table type: " + name); 20601 return; 20602 } 20603 opti++; 20604 } 20605 } 20606 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20607 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20608 } else if ("permission".equals(cmd)) { 20609 if (opti >= args.length) { 20610 pw.println("Error: permission requires permission name"); 20611 return; 20612 } 20613 permissionNames = new ArraySet<>(); 20614 while (opti < args.length) { 20615 permissionNames.add(args[opti]); 20616 opti++; 20617 } 20618 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20619 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20620 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20621 dumpState.setDump(DumpState.DUMP_PREFERRED); 20622 } else if ("preferred-xml".equals(cmd)) { 20623 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20624 if (opti < args.length && "--full".equals(args[opti])) { 20625 fullPreferred = true; 20626 opti++; 20627 } 20628 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20629 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20630 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20631 dumpState.setDump(DumpState.DUMP_PACKAGES); 20632 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20633 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20634 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20635 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20636 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20637 dumpState.setDump(DumpState.DUMP_MESSAGES); 20638 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20639 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20640 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20641 || "intent-filter-verifiers".equals(cmd)) { 20642 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20643 } else if ("version".equals(cmd)) { 20644 dumpState.setDump(DumpState.DUMP_VERSION); 20645 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20646 dumpState.setDump(DumpState.DUMP_KEYSETS); 20647 } else if ("installs".equals(cmd)) { 20648 dumpState.setDump(DumpState.DUMP_INSTALLS); 20649 } else if ("frozen".equals(cmd)) { 20650 dumpState.setDump(DumpState.DUMP_FROZEN); 20651 } else if ("volumes".equals(cmd)) { 20652 dumpState.setDump(DumpState.DUMP_VOLUMES); 20653 } else if ("dexopt".equals(cmd)) { 20654 dumpState.setDump(DumpState.DUMP_DEXOPT); 20655 } else if ("compiler-stats".equals(cmd)) { 20656 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20657 } else if ("changes".equals(cmd)) { 20658 dumpState.setDump(DumpState.DUMP_CHANGES); 20659 } else if ("service-permissions".equals(cmd)) { 20660 dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS); 20661 } else if ("write".equals(cmd)) { 20662 synchronized (mPackages) { 20663 mSettings.writeLPr(); 20664 pw.println("Settings written."); 20665 return; 20666 } 20667 } 20668 } 20669 20670 if (checkin) { 20671 pw.println("vers,1"); 20672 } 20673 20674 // reader 20675 synchronized (mPackages) { 20676 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20677 if (!checkin) { 20678 if (dumpState.onTitlePrinted()) 20679 pw.println(); 20680 pw.println("Database versions:"); 20681 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20682 } 20683 } 20684 20685 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20686 if (!checkin) { 20687 if (dumpState.onTitlePrinted()) 20688 pw.println(); 20689 pw.println("Verifiers:"); 20690 pw.print(" Required: "); 20691 pw.print(mRequiredVerifierPackage); 20692 pw.print(" (uid="); 20693 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20694 UserHandle.USER_SYSTEM)); 20695 pw.println(")"); 20696 } else if (mRequiredVerifierPackage != null) { 20697 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20698 pw.print(","); 20699 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20700 UserHandle.USER_SYSTEM)); 20701 } 20702 } 20703 20704 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20705 packageName == null) { 20706 if (mIntentFilterVerifierComponent != null) { 20707 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20708 if (!checkin) { 20709 if (dumpState.onTitlePrinted()) 20710 pw.println(); 20711 pw.println("Intent Filter Verifier:"); 20712 pw.print(" Using: "); 20713 pw.print(verifierPackageName); 20714 pw.print(" (uid="); 20715 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20716 UserHandle.USER_SYSTEM)); 20717 pw.println(")"); 20718 } else if (verifierPackageName != null) { 20719 pw.print("ifv,"); pw.print(verifierPackageName); 20720 pw.print(","); 20721 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20722 UserHandle.USER_SYSTEM)); 20723 } 20724 } else { 20725 pw.println(); 20726 pw.println("No Intent Filter Verifier available!"); 20727 } 20728 } 20729 20730 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20731 boolean printedHeader = false; 20732 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20733 while (it.hasNext()) { 20734 String libName = it.next(); 20735 LongSparseArray<SharedLibraryEntry> versionedLib 20736 = mSharedLibraries.get(libName); 20737 if (versionedLib == null) { 20738 continue; 20739 } 20740 final int versionCount = versionedLib.size(); 20741 for (int i = 0; i < versionCount; i++) { 20742 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20743 if (!checkin) { 20744 if (!printedHeader) { 20745 if (dumpState.onTitlePrinted()) 20746 pw.println(); 20747 pw.println("Libraries:"); 20748 printedHeader = true; 20749 } 20750 pw.print(" "); 20751 } else { 20752 pw.print("lib,"); 20753 } 20754 pw.print(libEntry.info.getName()); 20755 if (libEntry.info.isStatic()) { 20756 pw.print(" version=" + libEntry.info.getLongVersion()); 20757 } 20758 if (!checkin) { 20759 pw.print(" -> "); 20760 } 20761 if (libEntry.path != null) { 20762 pw.print(" (jar) "); 20763 pw.print(libEntry.path); 20764 } else { 20765 pw.print(" (apk) "); 20766 pw.print(libEntry.apk); 20767 } 20768 pw.println(); 20769 } 20770 } 20771 } 20772 20773 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20774 if (dumpState.onTitlePrinted()) 20775 pw.println(); 20776 if (!checkin) { 20777 pw.println("Features:"); 20778 } 20779 20780 synchronized (mAvailableFeatures) { 20781 for (FeatureInfo feat : mAvailableFeatures.values()) { 20782 if (checkin) { 20783 pw.print("feat,"); 20784 pw.print(feat.name); 20785 pw.print(","); 20786 pw.println(feat.version); 20787 } else { 20788 pw.print(" "); 20789 pw.print(feat.name); 20790 if (feat.version > 0) { 20791 pw.print(" version="); 20792 pw.print(feat.version); 20793 } 20794 pw.println(); 20795 } 20796 } 20797 } 20798 } 20799 20800 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20801 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20802 : "Activity Resolver Table:", " ", packageName, 20803 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20804 dumpState.setTitlePrinted(true); 20805 } 20806 } 20807 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20808 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20809 : "Receiver Resolver Table:", " ", packageName, 20810 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20811 dumpState.setTitlePrinted(true); 20812 } 20813 } 20814 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20815 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20816 : "Service Resolver Table:", " ", packageName, 20817 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20818 dumpState.setTitlePrinted(true); 20819 } 20820 } 20821 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20822 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20823 : "Provider Resolver Table:", " ", packageName, 20824 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20825 dumpState.setTitlePrinted(true); 20826 } 20827 } 20828 20829 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20830 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20831 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20832 int user = mSettings.mPreferredActivities.keyAt(i); 20833 if (pir.dump(pw, 20834 dumpState.getTitlePrinted() 20835 ? "\nPreferred Activities User " + user + ":" 20836 : "Preferred Activities User " + user + ":", " ", 20837 packageName, true, false)) { 20838 dumpState.setTitlePrinted(true); 20839 } 20840 } 20841 } 20842 20843 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20844 pw.flush(); 20845 FileOutputStream fout = new FileOutputStream(fd); 20846 BufferedOutputStream str = new BufferedOutputStream(fout); 20847 XmlSerializer serializer = new FastXmlSerializer(); 20848 try { 20849 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20850 serializer.startDocument(null, true); 20851 serializer.setFeature( 20852 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20853 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20854 serializer.endDocument(); 20855 serializer.flush(); 20856 } catch (IllegalArgumentException e) { 20857 pw.println("Failed writing: " + e); 20858 } catch (IllegalStateException e) { 20859 pw.println("Failed writing: " + e); 20860 } catch (IOException e) { 20861 pw.println("Failed writing: " + e); 20862 } 20863 } 20864 20865 if (!checkin 20866 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20867 && packageName == null) { 20868 pw.println(); 20869 int count = mSettings.mPackages.size(); 20870 if (count == 0) { 20871 pw.println("No applications!"); 20872 pw.println(); 20873 } else { 20874 final String prefix = " "; 20875 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20876 if (allPackageSettings.size() == 0) { 20877 pw.println("No domain preferred apps!"); 20878 pw.println(); 20879 } else { 20880 pw.println("App verification status:"); 20881 pw.println(); 20882 count = 0; 20883 for (PackageSetting ps : allPackageSettings) { 20884 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20885 if (ivi == null || ivi.getPackageName() == null) continue; 20886 pw.println(prefix + "Package: " + ivi.getPackageName()); 20887 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20888 pw.println(prefix + "Status: " + ivi.getStatusString()); 20889 pw.println(); 20890 count++; 20891 } 20892 if (count == 0) { 20893 pw.println(prefix + "No app verification established."); 20894 pw.println(); 20895 } 20896 for (int userId : sUserManager.getUserIds()) { 20897 pw.println("App linkages for user " + userId + ":"); 20898 pw.println(); 20899 count = 0; 20900 for (PackageSetting ps : allPackageSettings) { 20901 final long status = ps.getDomainVerificationStatusForUser(userId); 20902 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20903 && !DEBUG_DOMAIN_VERIFICATION) { 20904 continue; 20905 } 20906 pw.println(prefix + "Package: " + ps.name); 20907 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20908 String statusStr = IntentFilterVerificationInfo. 20909 getStatusStringFromValue(status); 20910 pw.println(prefix + "Status: " + statusStr); 20911 pw.println(); 20912 count++; 20913 } 20914 if (count == 0) { 20915 pw.println(prefix + "No configured app linkages."); 20916 pw.println(); 20917 } 20918 } 20919 } 20920 } 20921 } 20922 20923 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20924 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20925 } 20926 20927 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20928 boolean printedSomething = false; 20929 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20930 if (packageName != null && !packageName.equals(p.info.packageName)) { 20931 continue; 20932 } 20933 if (!printedSomething) { 20934 if (dumpState.onTitlePrinted()) 20935 pw.println(); 20936 pw.println("Registered ContentProviders:"); 20937 printedSomething = true; 20938 } 20939 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20940 pw.print(" "); pw.println(p.toString()); 20941 } 20942 printedSomething = false; 20943 for (Map.Entry<String, PackageParser.Provider> entry : 20944 mProvidersByAuthority.entrySet()) { 20945 PackageParser.Provider p = entry.getValue(); 20946 if (packageName != null && !packageName.equals(p.info.packageName)) { 20947 continue; 20948 } 20949 if (!printedSomething) { 20950 if (dumpState.onTitlePrinted()) 20951 pw.println(); 20952 pw.println("ContentProvider Authorities:"); 20953 printedSomething = true; 20954 } 20955 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20956 pw.print(" "); pw.println(p.toString()); 20957 if (p.info != null && p.info.applicationInfo != null) { 20958 final String appInfo = p.info.applicationInfo.toString(); 20959 pw.print(" applicationInfo="); pw.println(appInfo); 20960 } 20961 } 20962 } 20963 20964 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20965 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20966 } 20967 20968 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20969 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20970 } 20971 20972 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20973 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20974 } 20975 20976 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 20977 if (dumpState.onTitlePrinted()) pw.println(); 20978 pw.println("Package Changes:"); 20979 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 20980 final int K = mChangedPackages.size(); 20981 for (int i = 0; i < K; i++) { 20982 final SparseArray<String> changes = mChangedPackages.valueAt(i); 20983 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 20984 final int N = changes.size(); 20985 if (N == 0) { 20986 pw.print(" "); pw.println("No packages changed"); 20987 } else { 20988 for (int j = 0; j < N; j++) { 20989 final String pkgName = changes.valueAt(j); 20990 final int sequenceNumber = changes.keyAt(j); 20991 pw.print(" "); 20992 pw.print("seq="); 20993 pw.print(sequenceNumber); 20994 pw.print(", package="); 20995 pw.println(pkgName); 20996 } 20997 } 20998 } 20999 } 21000 21001 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 21002 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 21003 } 21004 21005 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21006 // XXX should handle packageName != null by dumping only install data that 21007 // the given package is involved with. 21008 if (dumpState.onTitlePrinted()) pw.println(); 21009 21010 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21011 ipw.println(); 21012 ipw.println("Frozen packages:"); 21013 ipw.increaseIndent(); 21014 if (mFrozenPackages.size() == 0) { 21015 ipw.println("(none)"); 21016 } else { 21017 for (int i = 0; i < mFrozenPackages.size(); i++) { 21018 ipw.println(mFrozenPackages.valueAt(i)); 21019 } 21020 } 21021 ipw.decreaseIndent(); 21022 } 21023 21024 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 21025 if (dumpState.onTitlePrinted()) pw.println(); 21026 21027 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21028 ipw.println(); 21029 ipw.println("Loaded volumes:"); 21030 ipw.increaseIndent(); 21031 if (mLoadedVolumes.size() == 0) { 21032 ipw.println("(none)"); 21033 } else { 21034 for (int i = 0; i < mLoadedVolumes.size(); i++) { 21035 ipw.println(mLoadedVolumes.valueAt(i)); 21036 } 21037 } 21038 ipw.decreaseIndent(); 21039 } 21040 21041 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS) 21042 && packageName == null) { 21043 if (dumpState.onTitlePrinted()) pw.println(); 21044 pw.println("Service permissions:"); 21045 21046 final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator(); 21047 while (filterIterator.hasNext()) { 21048 final ServiceIntentInfo info = filterIterator.next(); 21049 final ServiceInfo serviceInfo = info.service.info; 21050 final String permission = serviceInfo.permission; 21051 if (permission != null) { 21052 pw.print(" "); 21053 pw.print(serviceInfo.getComponentName().flattenToShortString()); 21054 pw.print(": "); 21055 pw.println(permission); 21056 } 21057 } 21058 } 21059 21060 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21061 if (dumpState.onTitlePrinted()) pw.println(); 21062 dumpDexoptStateLPr(pw, packageName); 21063 } 21064 21065 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21066 if (dumpState.onTitlePrinted()) pw.println(); 21067 dumpCompilerStatsLPr(pw, packageName); 21068 } 21069 21070 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21071 if (dumpState.onTitlePrinted()) pw.println(); 21072 mSettings.dumpReadMessagesLPr(pw, dumpState); 21073 21074 pw.println(); 21075 pw.println("Package warning messages:"); 21076 dumpCriticalInfo(pw, null); 21077 } 21078 21079 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21080 dumpCriticalInfo(pw, "msg,"); 21081 } 21082 } 21083 21084 // PackageInstaller should be called outside of mPackages lock 21085 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21086 // XXX should handle packageName != null by dumping only install data that 21087 // the given package is involved with. 21088 if (dumpState.onTitlePrinted()) pw.println(); 21089 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21090 } 21091 } 21092 21093 private void dumpProto(FileDescriptor fd) { 21094 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21095 21096 synchronized (mPackages) { 21097 final long requiredVerifierPackageToken = 21098 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21099 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21100 proto.write( 21101 PackageServiceDumpProto.PackageShortProto.UID, 21102 getPackageUid( 21103 mRequiredVerifierPackage, 21104 MATCH_DEBUG_TRIAGED_MISSING, 21105 UserHandle.USER_SYSTEM)); 21106 proto.end(requiredVerifierPackageToken); 21107 21108 if (mIntentFilterVerifierComponent != null) { 21109 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21110 final long verifierPackageToken = 21111 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21112 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21113 proto.write( 21114 PackageServiceDumpProto.PackageShortProto.UID, 21115 getPackageUid( 21116 verifierPackageName, 21117 MATCH_DEBUG_TRIAGED_MISSING, 21118 UserHandle.USER_SYSTEM)); 21119 proto.end(verifierPackageToken); 21120 } 21121 21122 dumpSharedLibrariesProto(proto); 21123 dumpFeaturesProto(proto); 21124 mSettings.dumpPackagesProto(proto); 21125 mSettings.dumpSharedUsersProto(proto); 21126 dumpCriticalInfo(proto); 21127 } 21128 proto.flush(); 21129 } 21130 21131 private void dumpFeaturesProto(ProtoOutputStream proto) { 21132 synchronized (mAvailableFeatures) { 21133 final int count = mAvailableFeatures.size(); 21134 for (int i = 0; i < count; i++) { 21135 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES); 21136 } 21137 } 21138 } 21139 21140 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21141 final int count = mSharedLibraries.size(); 21142 for (int i = 0; i < count; i++) { 21143 final String libName = mSharedLibraries.keyAt(i); 21144 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21145 if (versionedLib == null) { 21146 continue; 21147 } 21148 final int versionCount = versionedLib.size(); 21149 for (int j = 0; j < versionCount; j++) { 21150 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21151 final long sharedLibraryToken = 21152 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21153 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21154 final boolean isJar = (libEntry.path != null); 21155 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21156 if (isJar) { 21157 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21158 } else { 21159 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21160 } 21161 proto.end(sharedLibraryToken); 21162 } 21163 } 21164 } 21165 21166 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21167 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21168 ipw.println(); 21169 ipw.println("Dexopt state:"); 21170 ipw.increaseIndent(); 21171 Collection<PackageParser.Package> packages = null; 21172 if (packageName != null) { 21173 PackageParser.Package targetPackage = mPackages.get(packageName); 21174 if (targetPackage != null) { 21175 packages = Collections.singletonList(targetPackage); 21176 } else { 21177 ipw.println("Unable to find package: " + packageName); 21178 return; 21179 } 21180 } else { 21181 packages = mPackages.values(); 21182 } 21183 21184 for (PackageParser.Package pkg : packages) { 21185 ipw.println("[" + pkg.packageName + "]"); 21186 ipw.increaseIndent(); 21187 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 21188 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 21189 ipw.decreaseIndent(); 21190 } 21191 } 21192 21193 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21194 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21195 ipw.println(); 21196 ipw.println("Compiler stats:"); 21197 ipw.increaseIndent(); 21198 Collection<PackageParser.Package> packages = null; 21199 if (packageName != null) { 21200 PackageParser.Package targetPackage = mPackages.get(packageName); 21201 if (targetPackage != null) { 21202 packages = Collections.singletonList(targetPackage); 21203 } else { 21204 ipw.println("Unable to find package: " + packageName); 21205 return; 21206 } 21207 } else { 21208 packages = mPackages.values(); 21209 } 21210 21211 for (PackageParser.Package pkg : packages) { 21212 ipw.println("[" + pkg.packageName + "]"); 21213 ipw.increaseIndent(); 21214 21215 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21216 if (stats == null) { 21217 ipw.println("(No recorded stats)"); 21218 } else { 21219 stats.dump(ipw); 21220 } 21221 ipw.decreaseIndent(); 21222 } 21223 } 21224 21225 private String dumpDomainString(String packageName) { 21226 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21227 .getList(); 21228 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21229 21230 ArraySet<String> result = new ArraySet<>(); 21231 if (iviList.size() > 0) { 21232 for (IntentFilterVerificationInfo ivi : iviList) { 21233 for (String host : ivi.getDomains()) { 21234 result.add(host); 21235 } 21236 } 21237 } 21238 if (filters != null && filters.size() > 0) { 21239 for (IntentFilter filter : filters) { 21240 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21241 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21242 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21243 result.addAll(filter.getHostsList()); 21244 } 21245 } 21246 } 21247 21248 StringBuilder sb = new StringBuilder(result.size() * 16); 21249 for (String domain : result) { 21250 if (sb.length() > 0) sb.append(" "); 21251 sb.append(domain); 21252 } 21253 return sb.toString(); 21254 } 21255 21256 // ------- apps on sdcard specific code ------- 21257 static final boolean DEBUG_SD_INSTALL = false; 21258 21259 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21260 21261 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21262 21263 private boolean mMediaMounted = false; 21264 21265 static String getEncryptKey() { 21266 try { 21267 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21268 SD_ENCRYPTION_KEYSTORE_NAME); 21269 if (sdEncKey == null) { 21270 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21271 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21272 if (sdEncKey == null) { 21273 Slog.e(TAG, "Failed to create encryption keys"); 21274 return null; 21275 } 21276 } 21277 return sdEncKey; 21278 } catch (NoSuchAlgorithmException nsae) { 21279 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21280 return null; 21281 } catch (IOException ioe) { 21282 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21283 return null; 21284 } 21285 } 21286 21287 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21288 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21289 final int size = infos.size(); 21290 final String[] packageNames = new String[size]; 21291 final int[] packageUids = new int[size]; 21292 for (int i = 0; i < size; i++) { 21293 final ApplicationInfo info = infos.get(i); 21294 packageNames[i] = info.packageName; 21295 packageUids[i] = info.uid; 21296 } 21297 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21298 finishedReceiver); 21299 } 21300 21301 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21302 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21303 sendResourcesChangedBroadcast(mediaStatus, replacing, 21304 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21305 } 21306 21307 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21308 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21309 int size = pkgList.length; 21310 if (size > 0) { 21311 // Send broadcasts here 21312 Bundle extras = new Bundle(); 21313 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21314 if (uidArr != null) { 21315 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21316 } 21317 if (replacing) { 21318 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21319 } 21320 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21321 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21322 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null); 21323 } 21324 } 21325 21326 private void loadPrivatePackages(final VolumeInfo vol) { 21327 mHandler.post(new Runnable() { 21328 @Override 21329 public void run() { 21330 loadPrivatePackagesInner(vol); 21331 } 21332 }); 21333 } 21334 21335 private void loadPrivatePackagesInner(VolumeInfo vol) { 21336 final String volumeUuid = vol.fsUuid; 21337 if (TextUtils.isEmpty(volumeUuid)) { 21338 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21339 return; 21340 } 21341 21342 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21343 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21344 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21345 21346 final VersionInfo ver; 21347 final List<PackageSetting> packages; 21348 synchronized (mPackages) { 21349 ver = mSettings.findOrCreateVersion(volumeUuid); 21350 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21351 } 21352 21353 for (PackageSetting ps : packages) { 21354 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21355 synchronized (mInstallLock) { 21356 final PackageParser.Package pkg; 21357 try { 21358 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21359 loaded.add(pkg.applicationInfo); 21360 21361 } catch (PackageManagerException e) { 21362 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21363 } 21364 21365 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21366 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21367 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21368 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21369 } 21370 } 21371 } 21372 21373 // Reconcile app data for all started/unlocked users 21374 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21375 final UserManager um = mContext.getSystemService(UserManager.class); 21376 UserManagerInternal umInternal = getUserManagerInternal(); 21377 for (UserInfo user : um.getUsers()) { 21378 final int flags; 21379 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21380 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21381 } else if (umInternal.isUserRunning(user.id)) { 21382 flags = StorageManager.FLAG_STORAGE_DE; 21383 } else { 21384 continue; 21385 } 21386 21387 try { 21388 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21389 synchronized (mInstallLock) { 21390 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21391 } 21392 } catch (IllegalStateException e) { 21393 // Device was probably ejected, and we'll process that event momentarily 21394 Slog.w(TAG, "Failed to prepare storage: " + e); 21395 } 21396 } 21397 21398 synchronized (mPackages) { 21399 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 21400 if (sdkUpdated) { 21401 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21402 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21403 } 21404 mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(), 21405 mPermissionCallback); 21406 21407 // Yay, everything is now upgraded 21408 ver.forceCurrent(); 21409 21410 mSettings.writeLPr(); 21411 } 21412 21413 for (PackageFreezer freezer : freezers) { 21414 freezer.close(); 21415 } 21416 21417 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21418 sendResourcesChangedBroadcast(true, false, loaded, null); 21419 mLoadedVolumes.add(vol.getId()); 21420 } 21421 21422 private void unloadPrivatePackages(final VolumeInfo vol) { 21423 mHandler.post(new Runnable() { 21424 @Override 21425 public void run() { 21426 unloadPrivatePackagesInner(vol); 21427 } 21428 }); 21429 } 21430 21431 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21432 final String volumeUuid = vol.fsUuid; 21433 if (TextUtils.isEmpty(volumeUuid)) { 21434 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21435 return; 21436 } 21437 21438 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21439 synchronized (mInstallLock) { 21440 synchronized (mPackages) { 21441 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21442 for (PackageSetting ps : packages) { 21443 if (ps.pkg == null) continue; 21444 21445 final ApplicationInfo info = ps.pkg.applicationInfo; 21446 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21447 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 21448 21449 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21450 "unloadPrivatePackagesInner")) { 21451 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21452 false, null)) { 21453 unloaded.add(info); 21454 } else { 21455 Slog.w(TAG, "Failed to unload " + ps.codePath); 21456 } 21457 } 21458 21459 // Try very hard to release any references to this package 21460 // so we don't risk the system server being killed due to 21461 // open FDs 21462 AttributeCache.instance().removePackage(ps.name); 21463 } 21464 21465 mSettings.writeLPr(); 21466 } 21467 } 21468 21469 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21470 sendResourcesChangedBroadcast(false, false, unloaded, null); 21471 mLoadedVolumes.remove(vol.getId()); 21472 21473 // Try very hard to release any references to this path so we don't risk 21474 // the system server being killed due to open FDs 21475 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21476 21477 for (int i = 0; i < 3; i++) { 21478 System.gc(); 21479 System.runFinalization(); 21480 } 21481 } 21482 21483 private void assertPackageKnown(String volumeUuid, String packageName) 21484 throws PackageManagerException { 21485 synchronized (mPackages) { 21486 // Normalize package name to handle renamed packages 21487 packageName = normalizePackageNameLPr(packageName); 21488 21489 final PackageSetting ps = mSettings.mPackages.get(packageName); 21490 if (ps == null) { 21491 throw new PackageManagerException("Package " + packageName + " is unknown"); 21492 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21493 throw new PackageManagerException( 21494 "Package " + packageName + " found on unknown volume " + volumeUuid 21495 + "; expected volume " + ps.volumeUuid); 21496 } 21497 } 21498 } 21499 21500 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21501 throws PackageManagerException { 21502 synchronized (mPackages) { 21503 // Normalize package name to handle renamed packages 21504 packageName = normalizePackageNameLPr(packageName); 21505 21506 final PackageSetting ps = mSettings.mPackages.get(packageName); 21507 if (ps == null) { 21508 throw new PackageManagerException("Package " + packageName + " is unknown"); 21509 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21510 throw new PackageManagerException( 21511 "Package " + packageName + " found on unknown volume " + volumeUuid 21512 + "; expected volume " + ps.volumeUuid); 21513 } else if (!ps.getInstalled(userId)) { 21514 throw new PackageManagerException( 21515 "Package " + packageName + " not installed for user " + userId); 21516 } 21517 } 21518 } 21519 21520 private List<String> collectAbsoluteCodePaths() { 21521 synchronized (mPackages) { 21522 List<String> codePaths = new ArrayList<>(); 21523 final int packageCount = mSettings.mPackages.size(); 21524 for (int i = 0; i < packageCount; i++) { 21525 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21526 codePaths.add(ps.codePath.getAbsolutePath()); 21527 } 21528 return codePaths; 21529 } 21530 } 21531 21532 /** 21533 * Examine all apps present on given mounted volume, and destroy apps that 21534 * aren't expected, either due to uninstallation or reinstallation on 21535 * another volume. 21536 */ 21537 private void reconcileApps(String volumeUuid) { 21538 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21539 List<File> filesToDelete = null; 21540 21541 final File[] files = FileUtils.listFilesOrEmpty( 21542 Environment.getDataAppDirectory(volumeUuid)); 21543 for (File file : files) { 21544 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21545 && !PackageInstallerService.isStageName(file.getName()); 21546 if (!isPackage) { 21547 // Ignore entries which are not packages 21548 continue; 21549 } 21550 21551 String absolutePath = file.getAbsolutePath(); 21552 21553 boolean pathValid = false; 21554 final int absoluteCodePathCount = absoluteCodePaths.size(); 21555 for (int i = 0; i < absoluteCodePathCount; i++) { 21556 String absoluteCodePath = absoluteCodePaths.get(i); 21557 if (absolutePath.startsWith(absoluteCodePath)) { 21558 pathValid = true; 21559 break; 21560 } 21561 } 21562 21563 if (!pathValid) { 21564 if (filesToDelete == null) { 21565 filesToDelete = new ArrayList<>(); 21566 } 21567 filesToDelete.add(file); 21568 } 21569 } 21570 21571 if (filesToDelete != null) { 21572 final int fileToDeleteCount = filesToDelete.size(); 21573 for (int i = 0; i < fileToDeleteCount; i++) { 21574 File fileToDelete = filesToDelete.get(i); 21575 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21576 synchronized (mInstallLock) { 21577 removeCodePathLI(fileToDelete); 21578 } 21579 } 21580 } 21581 } 21582 21583 /** 21584 * Reconcile all app data for the given user. 21585 * <p> 21586 * Verifies that directories exist and that ownership and labeling is 21587 * correct for all installed apps on all mounted volumes. 21588 */ 21589 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21590 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21591 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21592 final String volumeUuid = vol.getFsUuid(); 21593 synchronized (mInstallLock) { 21594 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21595 } 21596 } 21597 } 21598 21599 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21600 boolean migrateAppData) { 21601 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21602 } 21603 21604 /** 21605 * Reconcile all app data on given mounted volume. 21606 * <p> 21607 * Destroys app data that isn't expected, either due to uninstallation or 21608 * reinstallation on another volume. 21609 * <p> 21610 * Verifies that directories exist and that ownership and labeling is 21611 * correct for all installed apps. 21612 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21613 */ 21614 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21615 boolean migrateAppData, boolean onlyCoreApps) { 21616 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21617 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21618 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21619 21620 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21621 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21622 21623 // First look for stale data that doesn't belong, and check if things 21624 // have changed since we did our last restorecon 21625 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21626 if (StorageManager.isFileEncryptedNativeOrEmulated() 21627 && !StorageManager.isUserKeyUnlocked(userId)) { 21628 throw new RuntimeException( 21629 "Yikes, someone asked us to reconcile CE storage while " + userId 21630 + " was still locked; this would have caused massive data loss!"); 21631 } 21632 21633 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21634 for (File file : files) { 21635 final String packageName = file.getName(); 21636 try { 21637 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21638 } catch (PackageManagerException e) { 21639 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21640 try { 21641 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21642 StorageManager.FLAG_STORAGE_CE, 0); 21643 } catch (InstallerException e2) { 21644 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21645 } 21646 } 21647 } 21648 } 21649 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21650 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21651 for (File file : files) { 21652 final String packageName = file.getName(); 21653 try { 21654 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21655 } catch (PackageManagerException e) { 21656 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21657 try { 21658 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21659 StorageManager.FLAG_STORAGE_DE, 0); 21660 } catch (InstallerException e2) { 21661 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21662 } 21663 } 21664 } 21665 } 21666 21667 // Ensure that data directories are ready to roll for all packages 21668 // installed for this volume and user 21669 final List<PackageSetting> packages; 21670 synchronized (mPackages) { 21671 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21672 } 21673 int preparedCount = 0; 21674 for (PackageSetting ps : packages) { 21675 final String packageName = ps.name; 21676 if (ps.pkg == null) { 21677 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21678 // TODO: might be due to legacy ASEC apps; we should circle back 21679 // and reconcile again once they're scanned 21680 continue; 21681 } 21682 // Skip non-core apps if requested 21683 if (onlyCoreApps && !ps.pkg.coreApp) { 21684 result.add(packageName); 21685 continue; 21686 } 21687 21688 if (ps.getInstalled(userId)) { 21689 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21690 preparedCount++; 21691 } 21692 } 21693 21694 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21695 return result; 21696 } 21697 21698 /** 21699 * Prepare app data for the given app just after it was installed or 21700 * upgraded. This method carefully only touches users that it's installed 21701 * for, and it forces a restorecon to handle any seinfo changes. 21702 * <p> 21703 * Verifies that directories exist and that ownership and labeling is 21704 * correct for all installed apps. If there is an ownership mismatch, it 21705 * will try recovering system apps by wiping data; third-party app data is 21706 * left intact. 21707 * <p> 21708 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21709 */ 21710 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21711 final PackageSetting ps; 21712 synchronized (mPackages) { 21713 ps = mSettings.mPackages.get(pkg.packageName); 21714 mSettings.writeKernelMappingLPr(ps); 21715 } 21716 21717 final UserManager um = mContext.getSystemService(UserManager.class); 21718 UserManagerInternal umInternal = getUserManagerInternal(); 21719 for (UserInfo user : um.getUsers()) { 21720 final int flags; 21721 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21722 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21723 } else if (umInternal.isUserRunning(user.id)) { 21724 flags = StorageManager.FLAG_STORAGE_DE; 21725 } else { 21726 continue; 21727 } 21728 21729 if (ps.getInstalled(user.id)) { 21730 // TODO: when user data is locked, mark that we're still dirty 21731 prepareAppDataLIF(pkg, user.id, flags); 21732 } 21733 } 21734 } 21735 21736 /** 21737 * Prepare app data for the given app. 21738 * <p> 21739 * Verifies that directories exist and that ownership and labeling is 21740 * correct for all installed apps. If there is an ownership mismatch, this 21741 * will try recovering system apps by wiping data; third-party app data is 21742 * left intact. 21743 */ 21744 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21745 if (pkg == null) { 21746 Slog.wtf(TAG, "Package was null!", new Throwable()); 21747 return; 21748 } 21749 prepareAppDataLeafLIF(pkg, userId, flags); 21750 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21751 for (int i = 0; i < childCount; i++) { 21752 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21753 } 21754 } 21755 21756 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21757 boolean maybeMigrateAppData) { 21758 prepareAppDataLIF(pkg, userId, flags); 21759 21760 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21761 // We may have just shuffled around app data directories, so 21762 // prepare them one more time 21763 prepareAppDataLIF(pkg, userId, flags); 21764 } 21765 } 21766 21767 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21768 if (DEBUG_APP_DATA) { 21769 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21770 + Integer.toHexString(flags)); 21771 } 21772 21773 final String volumeUuid = pkg.volumeUuid; 21774 final String packageName = pkg.packageName; 21775 final ApplicationInfo app = pkg.applicationInfo; 21776 final int appId = UserHandle.getAppId(app.uid); 21777 21778 Preconditions.checkNotNull(app.seInfo); 21779 21780 long ceDataInode = -1; 21781 try { 21782 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21783 appId, app.seInfo, app.targetSdkVersion); 21784 } catch (InstallerException e) { 21785 if (app.isSystemApp()) { 21786 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21787 + ", but trying to recover: " + e); 21788 destroyAppDataLeafLIF(pkg, userId, flags); 21789 try { 21790 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21791 appId, app.seInfo, app.targetSdkVersion); 21792 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21793 } catch (InstallerException e2) { 21794 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21795 } 21796 } else { 21797 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21798 } 21799 } 21800 21801 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21802 // TODO: mark this structure as dirty so we persist it! 21803 synchronized (mPackages) { 21804 final PackageSetting ps = mSettings.mPackages.get(packageName); 21805 if (ps != null) { 21806 ps.setCeDataInode(ceDataInode, userId); 21807 } 21808 } 21809 } 21810 21811 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21812 } 21813 21814 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21815 if (pkg == null) { 21816 Slog.wtf(TAG, "Package was null!", new Throwable()); 21817 return; 21818 } 21819 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21820 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21821 for (int i = 0; i < childCount; i++) { 21822 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21823 } 21824 } 21825 21826 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21827 final String volumeUuid = pkg.volumeUuid; 21828 final String packageName = pkg.packageName; 21829 final ApplicationInfo app = pkg.applicationInfo; 21830 21831 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21832 // Create a native library symlink only if we have native libraries 21833 // and if the native libraries are 32 bit libraries. We do not provide 21834 // this symlink for 64 bit libraries. 21835 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21836 final String nativeLibPath = app.nativeLibraryDir; 21837 try { 21838 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21839 nativeLibPath, userId); 21840 } catch (InstallerException e) { 21841 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21842 } 21843 } 21844 } 21845 } 21846 21847 /** 21848 * For system apps on non-FBE devices, this method migrates any existing 21849 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21850 * requested by the app. 21851 */ 21852 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21853 if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated() 21854 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21855 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21856 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21857 try { 21858 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21859 storageTarget); 21860 } catch (InstallerException e) { 21861 logCriticalInfo(Log.WARN, 21862 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21863 } 21864 return true; 21865 } else { 21866 return false; 21867 } 21868 } 21869 21870 public PackageFreezer freezePackage(String packageName, String killReason) { 21871 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21872 } 21873 21874 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 21875 return new PackageFreezer(packageName, userId, killReason); 21876 } 21877 21878 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 21879 String killReason) { 21880 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 21881 } 21882 21883 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 21884 String killReason) { 21885 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 21886 return new PackageFreezer(); 21887 } else { 21888 return freezePackage(packageName, userId, killReason); 21889 } 21890 } 21891 21892 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 21893 String killReason) { 21894 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 21895 } 21896 21897 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 21898 String killReason) { 21899 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 21900 return new PackageFreezer(); 21901 } else { 21902 return freezePackage(packageName, userId, killReason); 21903 } 21904 } 21905 21906 /** 21907 * Class that freezes and kills the given package upon creation, and 21908 * unfreezes it upon closing. This is typically used when doing surgery on 21909 * app code/data to prevent the app from running while you're working. 21910 */ 21911 private class PackageFreezer implements AutoCloseable { 21912 private final String mPackageName; 21913 private final PackageFreezer[] mChildren; 21914 21915 private final boolean mWeFroze; 21916 21917 private final AtomicBoolean mClosed = new AtomicBoolean(); 21918 private final CloseGuard mCloseGuard = CloseGuard.get(); 21919 21920 /** 21921 * Create and return a stub freezer that doesn't actually do anything, 21922 * typically used when someone requested 21923 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 21924 * {@link PackageManager#DELETE_DONT_KILL_APP}. 21925 */ 21926 public PackageFreezer() { 21927 mPackageName = null; 21928 mChildren = null; 21929 mWeFroze = false; 21930 mCloseGuard.open("close"); 21931 } 21932 21933 public PackageFreezer(String packageName, int userId, String killReason) { 21934 synchronized (mPackages) { 21935 mPackageName = packageName; 21936 mWeFroze = mFrozenPackages.add(mPackageName); 21937 21938 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 21939 if (ps != null) { 21940 killApplication(ps.name, ps.appId, userId, killReason); 21941 } 21942 21943 final PackageParser.Package p = mPackages.get(packageName); 21944 if (p != null && p.childPackages != null) { 21945 final int N = p.childPackages.size(); 21946 mChildren = new PackageFreezer[N]; 21947 for (int i = 0; i < N; i++) { 21948 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 21949 userId, killReason); 21950 } 21951 } else { 21952 mChildren = null; 21953 } 21954 } 21955 mCloseGuard.open("close"); 21956 } 21957 21958 @Override 21959 protected void finalize() throws Throwable { 21960 try { 21961 if (mCloseGuard != null) { 21962 mCloseGuard.warnIfOpen(); 21963 } 21964 21965 close(); 21966 } finally { 21967 super.finalize(); 21968 } 21969 } 21970 21971 @Override 21972 public void close() { 21973 mCloseGuard.close(); 21974 if (mClosed.compareAndSet(false, true)) { 21975 synchronized (mPackages) { 21976 if (mWeFroze) { 21977 mFrozenPackages.remove(mPackageName); 21978 } 21979 21980 if (mChildren != null) { 21981 for (PackageFreezer freezer : mChildren) { 21982 freezer.close(); 21983 } 21984 } 21985 } 21986 } 21987 } 21988 } 21989 21990 /** 21991 * Verify that given package is currently frozen. 21992 */ 21993 private void checkPackageFrozen(String packageName) { 21994 synchronized (mPackages) { 21995 if (!mFrozenPackages.contains(packageName)) { 21996 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 21997 } 21998 } 21999 } 22000 22001 @Override 22002 public int movePackage(final String packageName, final String volumeUuid) { 22003 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22004 22005 final int callingUid = Binder.getCallingUid(); 22006 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 22007 final int moveId = mNextMoveId.getAndIncrement(); 22008 mHandler.post(new Runnable() { 22009 @Override 22010 public void run() { 22011 try { 22012 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 22013 } catch (PackageManagerException e) { 22014 Slog.w(TAG, "Failed to move " + packageName, e); 22015 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 22016 } 22017 } 22018 }); 22019 return moveId; 22020 } 22021 22022 private void movePackageInternal(final String packageName, final String volumeUuid, 22023 final int moveId, final int callingUid, UserHandle user) 22024 throws PackageManagerException { 22025 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22026 final PackageManager pm = mContext.getPackageManager(); 22027 22028 final boolean currentAsec; 22029 final String currentVolumeUuid; 22030 final File codeFile; 22031 final String installerPackageName; 22032 final String packageAbiOverride; 22033 final int appId; 22034 final String seinfo; 22035 final String label; 22036 final int targetSdkVersion; 22037 final PackageFreezer freezer; 22038 final int[] installedUserIds; 22039 22040 // reader 22041 synchronized (mPackages) { 22042 final PackageParser.Package pkg = mPackages.get(packageName); 22043 final PackageSetting ps = mSettings.mPackages.get(packageName); 22044 if (pkg == null 22045 || ps == null 22046 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 22047 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22048 } 22049 if (pkg.applicationInfo.isSystemApp()) { 22050 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22051 "Cannot move system application"); 22052 } 22053 22054 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22055 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22056 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22057 if (isInternalStorage && !allow3rdPartyOnInternal) { 22058 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22059 "3rd party apps are not allowed on internal storage"); 22060 } 22061 22062 if (pkg.applicationInfo.isExternalAsec()) { 22063 currentAsec = true; 22064 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22065 } else if (pkg.applicationInfo.isForwardLocked()) { 22066 currentAsec = true; 22067 currentVolumeUuid = "forward_locked"; 22068 } else { 22069 currentAsec = false; 22070 currentVolumeUuid = ps.volumeUuid; 22071 22072 final File probe = new File(pkg.codePath); 22073 final File probeOat = new File(probe, "oat"); 22074 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22075 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22076 "Move only supported for modern cluster style installs"); 22077 } 22078 } 22079 22080 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22081 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22082 "Package already moved to " + volumeUuid); 22083 } 22084 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22085 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22086 "Device admin cannot be moved"); 22087 } 22088 22089 if (mFrozenPackages.contains(packageName)) { 22090 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22091 "Failed to move already frozen package"); 22092 } 22093 22094 codeFile = new File(pkg.codePath); 22095 installerPackageName = ps.installerPackageName; 22096 packageAbiOverride = ps.cpuAbiOverrideString; 22097 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22098 seinfo = pkg.applicationInfo.seInfo; 22099 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22100 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22101 freezer = freezePackage(packageName, "movePackageInternal"); 22102 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22103 } 22104 22105 final Bundle extras = new Bundle(); 22106 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22107 extras.putString(Intent.EXTRA_TITLE, label); 22108 mMoveCallbacks.notifyCreated(moveId, extras); 22109 22110 int installFlags; 22111 final boolean moveCompleteApp; 22112 final File measurePath; 22113 22114 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22115 installFlags = INSTALL_INTERNAL; 22116 moveCompleteApp = !currentAsec; 22117 measurePath = Environment.getDataAppDirectory(volumeUuid); 22118 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22119 installFlags = INSTALL_EXTERNAL; 22120 moveCompleteApp = false; 22121 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22122 } else { 22123 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22124 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22125 || !volume.isMountedWritable()) { 22126 freezer.close(); 22127 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22128 "Move location not mounted private volume"); 22129 } 22130 22131 Preconditions.checkState(!currentAsec); 22132 22133 installFlags = INSTALL_INTERNAL; 22134 moveCompleteApp = true; 22135 measurePath = Environment.getDataAppDirectory(volumeUuid); 22136 } 22137 22138 // If we're moving app data around, we need all the users unlocked 22139 if (moveCompleteApp) { 22140 for (int userId : installedUserIds) { 22141 if (StorageManager.isFileEncryptedNativeOrEmulated() 22142 && !StorageManager.isUserKeyUnlocked(userId)) { 22143 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 22144 "User " + userId + " must be unlocked"); 22145 } 22146 } 22147 } 22148 22149 final PackageStats stats = new PackageStats(null, -1); 22150 synchronized (mInstaller) { 22151 for (int userId : installedUserIds) { 22152 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22153 freezer.close(); 22154 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22155 "Failed to measure package size"); 22156 } 22157 } 22158 } 22159 22160 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22161 + stats.dataSize); 22162 22163 final long startFreeBytes = measurePath.getUsableSpace(); 22164 final long sizeBytes; 22165 if (moveCompleteApp) { 22166 sizeBytes = stats.codeSize + stats.dataSize; 22167 } else { 22168 sizeBytes = stats.codeSize; 22169 } 22170 22171 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22172 freezer.close(); 22173 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22174 "Not enough free space to move"); 22175 } 22176 22177 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22178 22179 final CountDownLatch installedLatch = new CountDownLatch(1); 22180 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22181 @Override 22182 public void onUserActionRequired(Intent intent) throws RemoteException { 22183 throw new IllegalStateException(); 22184 } 22185 22186 @Override 22187 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22188 Bundle extras) throws RemoteException { 22189 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22190 + PackageManager.installStatusToString(returnCode, msg)); 22191 22192 installedLatch.countDown(); 22193 freezer.close(); 22194 22195 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22196 switch (status) { 22197 case PackageInstaller.STATUS_SUCCESS: 22198 mMoveCallbacks.notifyStatusChanged(moveId, 22199 PackageManager.MOVE_SUCCEEDED); 22200 break; 22201 case PackageInstaller.STATUS_FAILURE_STORAGE: 22202 mMoveCallbacks.notifyStatusChanged(moveId, 22203 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22204 break; 22205 default: 22206 mMoveCallbacks.notifyStatusChanged(moveId, 22207 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22208 break; 22209 } 22210 } 22211 }; 22212 22213 final MoveInfo move; 22214 if (moveCompleteApp) { 22215 // Kick off a thread to report progress estimates 22216 new Thread() { 22217 @Override 22218 public void run() { 22219 while (true) { 22220 try { 22221 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22222 break; 22223 } 22224 } catch (InterruptedException ignored) { 22225 } 22226 22227 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22228 final int progress = 10 + (int) MathUtils.constrain( 22229 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22230 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22231 } 22232 } 22233 }.start(); 22234 22235 final String dataAppName = codeFile.getName(); 22236 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22237 dataAppName, appId, seinfo, targetSdkVersion); 22238 } else { 22239 move = null; 22240 } 22241 22242 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22243 22244 final Message msg = mHandler.obtainMessage(INIT_COPY); 22245 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22246 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22247 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22248 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22249 PackageManager.INSTALL_REASON_UNKNOWN); 22250 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22251 msg.obj = params; 22252 22253 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22254 System.identityHashCode(msg.obj)); 22255 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22256 System.identityHashCode(msg.obj)); 22257 22258 mHandler.sendMessage(msg); 22259 } 22260 22261 @Override 22262 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22263 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22264 22265 final int realMoveId = mNextMoveId.getAndIncrement(); 22266 final Bundle extras = new Bundle(); 22267 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22268 mMoveCallbacks.notifyCreated(realMoveId, extras); 22269 22270 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22271 @Override 22272 public void onCreated(int moveId, Bundle extras) { 22273 // Ignored 22274 } 22275 22276 @Override 22277 public void onStatusChanged(int moveId, int status, long estMillis) { 22278 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22279 } 22280 }; 22281 22282 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22283 storage.setPrimaryStorageUuid(volumeUuid, callback); 22284 return realMoveId; 22285 } 22286 22287 @Override 22288 public int getMoveStatus(int moveId) { 22289 mContext.enforceCallingOrSelfPermission( 22290 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22291 return mMoveCallbacks.mLastStatus.get(moveId); 22292 } 22293 22294 @Override 22295 public void registerMoveCallback(IPackageMoveObserver callback) { 22296 mContext.enforceCallingOrSelfPermission( 22297 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22298 mMoveCallbacks.register(callback); 22299 } 22300 22301 @Override 22302 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22303 mContext.enforceCallingOrSelfPermission( 22304 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22305 mMoveCallbacks.unregister(callback); 22306 } 22307 22308 @Override 22309 public boolean setInstallLocation(int loc) { 22310 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22311 null); 22312 if (getInstallLocation() == loc) { 22313 return true; 22314 } 22315 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22316 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22317 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22318 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22319 return true; 22320 } 22321 return false; 22322 } 22323 22324 @Override 22325 public int getInstallLocation() { 22326 // allow instant app access 22327 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22328 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22329 PackageHelper.APP_INSTALL_AUTO); 22330 } 22331 22332 /** Called by UserManagerService */ 22333 void cleanUpUser(UserManagerService userManager, int userHandle) { 22334 synchronized (mPackages) { 22335 mDirtyUsers.remove(userHandle); 22336 mUserNeedsBadging.delete(userHandle); 22337 mSettings.removeUserLPw(userHandle); 22338 mPendingBroadcasts.remove(userHandle); 22339 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22340 removeUnusedPackagesLPw(userManager, userHandle); 22341 } 22342 } 22343 22344 /** 22345 * We're removing userHandle and would like to remove any downloaded packages 22346 * that are no longer in use by any other user. 22347 * @param userHandle the user being removed 22348 */ 22349 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22350 final boolean DEBUG_CLEAN_APKS = false; 22351 int [] users = userManager.getUserIds(); 22352 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22353 while (psit.hasNext()) { 22354 PackageSetting ps = psit.next(); 22355 if (ps.pkg == null) { 22356 continue; 22357 } 22358 final String packageName = ps.pkg.packageName; 22359 // Skip over if system app 22360 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22361 continue; 22362 } 22363 if (DEBUG_CLEAN_APKS) { 22364 Slog.i(TAG, "Checking package " + packageName); 22365 } 22366 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22367 if (keep) { 22368 if (DEBUG_CLEAN_APKS) { 22369 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22370 } 22371 } else { 22372 for (int i = 0; i < users.length; i++) { 22373 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22374 keep = true; 22375 if (DEBUG_CLEAN_APKS) { 22376 Slog.i(TAG, " Keeping package " + packageName + " for user " 22377 + users[i]); 22378 } 22379 break; 22380 } 22381 } 22382 } 22383 if (!keep) { 22384 if (DEBUG_CLEAN_APKS) { 22385 Slog.i(TAG, " Removing package " + packageName); 22386 } 22387 mHandler.post(new Runnable() { 22388 public void run() { 22389 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22390 userHandle, 0); 22391 } //end run 22392 }); 22393 } 22394 } 22395 } 22396 22397 /** Called by UserManagerService */ 22398 void createNewUser(int userId, String[] disallowedPackages) { 22399 synchronized (mInstallLock) { 22400 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22401 } 22402 synchronized (mPackages) { 22403 scheduleWritePackageRestrictionsLocked(userId); 22404 scheduleWritePackageListLocked(userId); 22405 applyFactoryDefaultBrowserLPw(userId); 22406 primeDomainVerificationsLPw(userId); 22407 } 22408 } 22409 22410 void onNewUserCreated(final int userId) { 22411 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22412 synchronized(mPackages) { 22413 // If permission review for legacy apps is required, we represent 22414 // dagerous permissions for such apps as always granted runtime 22415 // permissions to keep per user flag state whether review is needed. 22416 // Hence, if a new user is added we have to propagate dangerous 22417 // permission grants for these legacy apps. 22418 if (mSettings.mPermissions.mPermissionReviewRequired) { 22419// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG 22420 mPermissionManager.updateAllPermissions( 22421 StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(), 22422 mPermissionCallback); 22423 } 22424 } 22425 } 22426 22427 @Override 22428 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22429 mContext.enforceCallingOrSelfPermission( 22430 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22431 "Only package verification agents can read the verifier device identity"); 22432 22433 synchronized (mPackages) { 22434 return mSettings.getVerifierDeviceIdentityLPw(); 22435 } 22436 } 22437 22438 @Override 22439 public void setPermissionEnforced(String permission, boolean enforced) { 22440 // TODO: Now that we no longer change GID for storage, this should to away. 22441 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22442 "setPermissionEnforced"); 22443 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22444 synchronized (mPackages) { 22445 if (mSettings.mReadExternalStorageEnforced == null 22446 || mSettings.mReadExternalStorageEnforced != enforced) { 22447 mSettings.mReadExternalStorageEnforced = 22448 enforced ? Boolean.TRUE : Boolean.FALSE; 22449 mSettings.writeLPr(); 22450 } 22451 } 22452 // kill any non-foreground processes so we restart them and 22453 // grant/revoke the GID. 22454 final IActivityManager am = ActivityManager.getService(); 22455 if (am != null) { 22456 final long token = Binder.clearCallingIdentity(); 22457 try { 22458 am.killProcessesBelowForeground("setPermissionEnforcement"); 22459 } catch (RemoteException e) { 22460 } finally { 22461 Binder.restoreCallingIdentity(token); 22462 } 22463 } 22464 } else { 22465 throw new IllegalArgumentException("No selective enforcement for " + permission); 22466 } 22467 } 22468 22469 @Override 22470 @Deprecated 22471 public boolean isPermissionEnforced(String permission) { 22472 // allow instant applications 22473 return true; 22474 } 22475 22476 @Override 22477 public boolean isStorageLow() { 22478 // allow instant applications 22479 final long token = Binder.clearCallingIdentity(); 22480 try { 22481 final DeviceStorageMonitorInternal 22482 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22483 if (dsm != null) { 22484 return dsm.isMemoryLow(); 22485 } else { 22486 return false; 22487 } 22488 } finally { 22489 Binder.restoreCallingIdentity(token); 22490 } 22491 } 22492 22493 @Override 22494 public IPackageInstaller getPackageInstaller() { 22495 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 22496 return null; 22497 } 22498 return mInstallerService; 22499 } 22500 22501 @Override 22502 public IArtManager getArtManager() { 22503 return mArtManagerService; 22504 } 22505 22506 private boolean userNeedsBadging(int userId) { 22507 int index = mUserNeedsBadging.indexOfKey(userId); 22508 if (index < 0) { 22509 final UserInfo userInfo; 22510 final long token = Binder.clearCallingIdentity(); 22511 try { 22512 userInfo = sUserManager.getUserInfo(userId); 22513 } finally { 22514 Binder.restoreCallingIdentity(token); 22515 } 22516 final boolean b; 22517 if (userInfo != null && userInfo.isManagedProfile()) { 22518 b = true; 22519 } else { 22520 b = false; 22521 } 22522 mUserNeedsBadging.put(userId, b); 22523 return b; 22524 } 22525 return mUserNeedsBadging.valueAt(index); 22526 } 22527 22528 @Override 22529 public KeySet getKeySetByAlias(String packageName, String alias) { 22530 if (packageName == null || alias == null) { 22531 return null; 22532 } 22533 synchronized(mPackages) { 22534 final PackageParser.Package pkg = mPackages.get(packageName); 22535 if (pkg == null) { 22536 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22537 throw new IllegalArgumentException("Unknown package: " + packageName); 22538 } 22539 final PackageSetting ps = (PackageSetting) pkg.mExtras; 22540 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 22541 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 22542 throw new IllegalArgumentException("Unknown package: " + packageName); 22543 } 22544 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22545 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22546 } 22547 } 22548 22549 @Override 22550 public KeySet getSigningKeySet(String packageName) { 22551 if (packageName == null) { 22552 return null; 22553 } 22554 synchronized(mPackages) { 22555 final int callingUid = Binder.getCallingUid(); 22556 final int callingUserId = UserHandle.getUserId(callingUid); 22557 final PackageParser.Package pkg = mPackages.get(packageName); 22558 if (pkg == null) { 22559 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22560 throw new IllegalArgumentException("Unknown package: " + packageName); 22561 } 22562 final PackageSetting ps = (PackageSetting) pkg.mExtras; 22563 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 22564 // filter and pretend the package doesn't exist 22565 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 22566 + ", uid:" + callingUid); 22567 throw new IllegalArgumentException("Unknown package: " + packageName); 22568 } 22569 if (pkg.applicationInfo.uid != callingUid 22570 && Process.SYSTEM_UID != callingUid) { 22571 throw new SecurityException("May not access signing KeySet of other apps."); 22572 } 22573 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22574 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22575 } 22576 } 22577 22578 @Override 22579 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22580 final int callingUid = Binder.getCallingUid(); 22581 if (getInstantAppPackageName(callingUid) != null) { 22582 return false; 22583 } 22584 if (packageName == null || ks == null) { 22585 return false; 22586 } 22587 synchronized(mPackages) { 22588 final PackageParser.Package pkg = mPackages.get(packageName); 22589 if (pkg == null 22590 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 22591 UserHandle.getUserId(callingUid))) { 22592 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22593 throw new IllegalArgumentException("Unknown package: " + packageName); 22594 } 22595 IBinder ksh = ks.getToken(); 22596 if (ksh instanceof KeySetHandle) { 22597 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22598 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22599 } 22600 return false; 22601 } 22602 } 22603 22604 @Override 22605 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22606 final int callingUid = Binder.getCallingUid(); 22607 if (getInstantAppPackageName(callingUid) != null) { 22608 return false; 22609 } 22610 if (packageName == null || ks == null) { 22611 return false; 22612 } 22613 synchronized(mPackages) { 22614 final PackageParser.Package pkg = mPackages.get(packageName); 22615 if (pkg == null 22616 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 22617 UserHandle.getUserId(callingUid))) { 22618 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22619 throw new IllegalArgumentException("Unknown package: " + packageName); 22620 } 22621 IBinder ksh = ks.getToken(); 22622 if (ksh instanceof KeySetHandle) { 22623 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22624 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22625 } 22626 return false; 22627 } 22628 } 22629 22630 private void deletePackageIfUnusedLPr(final String packageName) { 22631 PackageSetting ps = mSettings.mPackages.get(packageName); 22632 if (ps == null) { 22633 return; 22634 } 22635 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22636 // TODO Implement atomic delete if package is unused 22637 // It is currently possible that the package will be deleted even if it is installed 22638 // after this method returns. 22639 mHandler.post(new Runnable() { 22640 public void run() { 22641 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22642 0, PackageManager.DELETE_ALL_USERS); 22643 } 22644 }); 22645 } 22646 } 22647 22648 /** 22649 * Check and throw if the given before/after packages would be considered a 22650 * downgrade. 22651 */ 22652 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22653 throws PackageManagerException { 22654 if (after.getLongVersionCode() < before.getLongVersionCode()) { 22655 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22656 "Update version code " + after.versionCode + " is older than current " 22657 + before.getLongVersionCode()); 22658 } else if (after.getLongVersionCode() == before.getLongVersionCode()) { 22659 if (after.baseRevisionCode < before.baseRevisionCode) { 22660 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22661 "Update base revision code " + after.baseRevisionCode 22662 + " is older than current " + before.baseRevisionCode); 22663 } 22664 22665 if (!ArrayUtils.isEmpty(after.splitNames)) { 22666 for (int i = 0; i < after.splitNames.length; i++) { 22667 final String splitName = after.splitNames[i]; 22668 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22669 if (j != -1) { 22670 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22671 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22672 "Update split " + splitName + " revision code " 22673 + after.splitRevisionCodes[i] + " is older than current " 22674 + before.splitRevisionCodes[j]); 22675 } 22676 } 22677 } 22678 } 22679 } 22680 } 22681 22682 private static class MoveCallbacks extends Handler { 22683 private static final int MSG_CREATED = 1; 22684 private static final int MSG_STATUS_CHANGED = 2; 22685 22686 private final RemoteCallbackList<IPackageMoveObserver> 22687 mCallbacks = new RemoteCallbackList<>(); 22688 22689 private final SparseIntArray mLastStatus = new SparseIntArray(); 22690 22691 public MoveCallbacks(Looper looper) { 22692 super(looper); 22693 } 22694 22695 public void register(IPackageMoveObserver callback) { 22696 mCallbacks.register(callback); 22697 } 22698 22699 public void unregister(IPackageMoveObserver callback) { 22700 mCallbacks.unregister(callback); 22701 } 22702 22703 @Override 22704 public void handleMessage(Message msg) { 22705 final SomeArgs args = (SomeArgs) msg.obj; 22706 final int n = mCallbacks.beginBroadcast(); 22707 for (int i = 0; i < n; i++) { 22708 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22709 try { 22710 invokeCallback(callback, msg.what, args); 22711 } catch (RemoteException ignored) { 22712 } 22713 } 22714 mCallbacks.finishBroadcast(); 22715 args.recycle(); 22716 } 22717 22718 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22719 throws RemoteException { 22720 switch (what) { 22721 case MSG_CREATED: { 22722 callback.onCreated(args.argi1, (Bundle) args.arg2); 22723 break; 22724 } 22725 case MSG_STATUS_CHANGED: { 22726 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22727 break; 22728 } 22729 } 22730 } 22731 22732 private void notifyCreated(int moveId, Bundle extras) { 22733 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22734 22735 final SomeArgs args = SomeArgs.obtain(); 22736 args.argi1 = moveId; 22737 args.arg2 = extras; 22738 obtainMessage(MSG_CREATED, args).sendToTarget(); 22739 } 22740 22741 private void notifyStatusChanged(int moveId, int status) { 22742 notifyStatusChanged(moveId, status, -1); 22743 } 22744 22745 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22746 Slog.v(TAG, "Move " + moveId + " status " + status); 22747 22748 final SomeArgs args = SomeArgs.obtain(); 22749 args.argi1 = moveId; 22750 args.argi2 = status; 22751 args.arg3 = estMillis; 22752 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22753 22754 synchronized (mLastStatus) { 22755 mLastStatus.put(moveId, status); 22756 } 22757 } 22758 } 22759 22760 private final static class OnPermissionChangeListeners extends Handler { 22761 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22762 22763 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22764 new RemoteCallbackList<>(); 22765 22766 public OnPermissionChangeListeners(Looper looper) { 22767 super(looper); 22768 } 22769 22770 @Override 22771 public void handleMessage(Message msg) { 22772 switch (msg.what) { 22773 case MSG_ON_PERMISSIONS_CHANGED: { 22774 final int uid = msg.arg1; 22775 handleOnPermissionsChanged(uid); 22776 } break; 22777 } 22778 } 22779 22780 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22781 mPermissionListeners.register(listener); 22782 22783 } 22784 22785 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22786 mPermissionListeners.unregister(listener); 22787 } 22788 22789 public void onPermissionsChanged(int uid) { 22790 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22791 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22792 } 22793 } 22794 22795 private void handleOnPermissionsChanged(int uid) { 22796 final int count = mPermissionListeners.beginBroadcast(); 22797 try { 22798 for (int i = 0; i < count; i++) { 22799 IOnPermissionsChangeListener callback = mPermissionListeners 22800 .getBroadcastItem(i); 22801 try { 22802 callback.onPermissionsChanged(uid); 22803 } catch (RemoteException e) { 22804 Log.e(TAG, "Permission listener is dead", e); 22805 } 22806 } 22807 } finally { 22808 mPermissionListeners.finishBroadcast(); 22809 } 22810 } 22811 } 22812 22813 private class PackageManagerNative extends IPackageManagerNative.Stub { 22814 @Override 22815 public String[] getNamesForUids(int[] uids) throws RemoteException { 22816 final String[] results = PackageManagerService.this.getNamesForUids(uids); 22817 // massage results so they can be parsed by the native binder 22818 for (int i = results.length - 1; i >= 0; --i) { 22819 if (results[i] == null) { 22820 results[i] = ""; 22821 } 22822 } 22823 return results; 22824 } 22825 22826 // NB: this differentiates between preloads and sideloads 22827 @Override 22828 public String getInstallerForPackage(String packageName) throws RemoteException { 22829 final String installerName = getInstallerPackageName(packageName); 22830 if (!TextUtils.isEmpty(installerName)) { 22831 return installerName; 22832 } 22833 // differentiate between preload and sideload 22834 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 22835 ApplicationInfo appInfo = getApplicationInfo(packageName, 22836 /*flags*/ 0, 22837 /*userId*/ callingUser); 22838 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22839 return "preload"; 22840 } 22841 return ""; 22842 } 22843 22844 @Override 22845 public long getVersionCodeForPackage(String packageName) throws RemoteException { 22846 try { 22847 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 22848 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 22849 if (pInfo != null) { 22850 return pInfo.getLongVersionCode(); 22851 } 22852 } catch (Exception e) { 22853 } 22854 return 0; 22855 } 22856 } 22857 22858 private class PackageManagerInternalImpl extends PackageManagerInternal { 22859 @Override 22860 public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask, 22861 int flagValues, int userId) { 22862 PackageManagerService.this.updatePermissionFlags( 22863 permName, packageName, flagMask, flagValues, userId); 22864 } 22865 22866 @Override 22867 public int getPermissionFlagsTEMP(String permName, String packageName, int userId) { 22868 return PackageManagerService.this.getPermissionFlags(permName, packageName, userId); 22869 } 22870 22871 @Override 22872 public boolean isInstantApp(String packageName, int userId) { 22873 return PackageManagerService.this.isInstantApp(packageName, userId); 22874 } 22875 22876 @Override 22877 public String getInstantAppPackageName(int uid) { 22878 return PackageManagerService.this.getInstantAppPackageName(uid); 22879 } 22880 22881 @Override 22882 public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) { 22883 synchronized (mPackages) { 22884 return PackageManagerService.this.filterAppAccessLPr( 22885 (PackageSetting) pkg.mExtras, callingUid, userId); 22886 } 22887 } 22888 22889 @Override 22890 public PackageParser.Package getPackage(String packageName) { 22891 synchronized (mPackages) { 22892 packageName = resolveInternalPackageNameLPr( 22893 packageName, PackageManager.VERSION_CODE_HIGHEST); 22894 return mPackages.get(packageName); 22895 } 22896 } 22897 22898 @Override 22899 public PackageList getPackageList(PackageListObserver observer) { 22900 synchronized (mPackages) { 22901 final int N = mPackages.size(); 22902 final ArrayList<String> list = new ArrayList<>(N); 22903 for (int i = 0; i < N; i++) { 22904 list.add(mPackages.keyAt(i)); 22905 } 22906 final PackageList packageList = new PackageList(list, observer); 22907 if (observer != null) { 22908 mPackageListObservers.add(packageList); 22909 } 22910 return packageList; 22911 } 22912 } 22913 22914 @Override 22915 public void removePackageListObserver(PackageListObserver observer) { 22916 synchronized (mPackages) { 22917 mPackageListObservers.remove(observer); 22918 } 22919 } 22920 22921 @Override 22922 public PackageParser.Package getDisabledPackage(String packageName) { 22923 synchronized (mPackages) { 22924 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 22925 return (ps != null) ? ps.pkg : null; 22926 } 22927 } 22928 22929 @Override 22930 public String getKnownPackageName(int knownPackage, int userId) { 22931 switch(knownPackage) { 22932 case PackageManagerInternal.PACKAGE_BROWSER: 22933 return getDefaultBrowserPackageName(userId); 22934 case PackageManagerInternal.PACKAGE_INSTALLER: 22935 return mRequiredInstallerPackage; 22936 case PackageManagerInternal.PACKAGE_SETUP_WIZARD: 22937 return mSetupWizardPackage; 22938 case PackageManagerInternal.PACKAGE_SYSTEM: 22939 return "android"; 22940 case PackageManagerInternal.PACKAGE_VERIFIER: 22941 return mRequiredVerifierPackage; 22942 } 22943 return null; 22944 } 22945 22946 @Override 22947 public boolean isResolveActivityComponent(ComponentInfo component) { 22948 return mResolveActivity.packageName.equals(component.packageName) 22949 && mResolveActivity.name.equals(component.name); 22950 } 22951 22952 @Override 22953 public void setLocationPackagesProvider(PackagesProvider provider) { 22954 mDefaultPermissionPolicy.setLocationPackagesProvider(provider); 22955 } 22956 22957 @Override 22958 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22959 mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider); 22960 } 22961 22962 @Override 22963 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22964 mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider); 22965 } 22966 22967 @Override 22968 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22969 mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider); 22970 } 22971 22972 @Override 22973 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22974 mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider); 22975 } 22976 22977 @Override 22978 public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) { 22979 mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider); 22980 } 22981 22982 @Override 22983 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22984 mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider); 22985 } 22986 22987 @Override 22988 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22989 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId); 22990 } 22991 22992 @Override 22993 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22994 synchronized (mPackages) { 22995 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22996 } 22997 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId); 22998 } 22999 23000 @Override 23001 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23002 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager( 23003 packageName, userId); 23004 } 23005 23006 @Override 23007 public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) { 23008 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp( 23009 packageName, userId); 23010 } 23011 23012 @Override 23013 public void setKeepUninstalledPackages(final List<String> packageList) { 23014 Preconditions.checkNotNull(packageList); 23015 List<String> removedFromList = null; 23016 synchronized (mPackages) { 23017 if (mKeepUninstalledPackages != null) { 23018 final int packagesCount = mKeepUninstalledPackages.size(); 23019 for (int i = 0; i < packagesCount; i++) { 23020 String oldPackage = mKeepUninstalledPackages.get(i); 23021 if (packageList != null && packageList.contains(oldPackage)) { 23022 continue; 23023 } 23024 if (removedFromList == null) { 23025 removedFromList = new ArrayList<>(); 23026 } 23027 removedFromList.add(oldPackage); 23028 } 23029 } 23030 mKeepUninstalledPackages = new ArrayList<>(packageList); 23031 if (removedFromList != null) { 23032 final int removedCount = removedFromList.size(); 23033 for (int i = 0; i < removedCount; i++) { 23034 deletePackageIfUnusedLPr(removedFromList.get(i)); 23035 } 23036 } 23037 } 23038 } 23039 23040 @Override 23041 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23042 synchronized (mPackages) { 23043 return mPermissionManager.isPermissionsReviewRequired( 23044 mPackages.get(packageName), userId); 23045 } 23046 } 23047 23048 @Override 23049 public PackageInfo getPackageInfo( 23050 String packageName, int flags, int filterCallingUid, int userId) { 23051 return PackageManagerService.this 23052 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 23053 flags, filterCallingUid, userId); 23054 } 23055 23056 @Override 23057 public int getPackageUid(String packageName, int flags, int userId) { 23058 return PackageManagerService.this 23059 .getPackageUid(packageName, flags, userId); 23060 } 23061 23062 @Override 23063 public ApplicationInfo getApplicationInfo( 23064 String packageName, int flags, int filterCallingUid, int userId) { 23065 return PackageManagerService.this 23066 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 23067 } 23068 23069 @Override 23070 public ActivityInfo getActivityInfo( 23071 ComponentName component, int flags, int filterCallingUid, int userId) { 23072 return PackageManagerService.this 23073 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 23074 } 23075 23076 @Override 23077 public List<ResolveInfo> queryIntentActivities( 23078 Intent intent, int flags, int filterCallingUid, int userId) { 23079 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23080 return PackageManagerService.this 23081 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 23082 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 23083 } 23084 23085 @Override 23086 public List<ResolveInfo> queryIntentServices( 23087 Intent intent, int flags, int callingUid, int userId) { 23088 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23089 return PackageManagerService.this 23090 .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid, 23091 false); 23092 } 23093 23094 @Override 23095 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23096 int userId) { 23097 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23098 } 23099 23100 @Override 23101 public void setDeviceAndProfileOwnerPackages( 23102 int deviceOwnerUserId, String deviceOwnerPackage, 23103 SparseArray<String> profileOwnerPackages) { 23104 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23105 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23106 } 23107 23108 @Override 23109 public boolean isPackageDataProtected(int userId, String packageName) { 23110 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23111 } 23112 23113 @Override 23114 public boolean isPackageEphemeral(int userId, String packageName) { 23115 synchronized (mPackages) { 23116 final PackageSetting ps = mSettings.mPackages.get(packageName); 23117 return ps != null ? ps.getInstantApp(userId) : false; 23118 } 23119 } 23120 23121 @Override 23122 public boolean wasPackageEverLaunched(String packageName, int userId) { 23123 synchronized (mPackages) { 23124 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23125 } 23126 } 23127 23128 @Override 23129 public void grantRuntimePermission(String packageName, String permName, int userId, 23130 boolean overridePolicy) { 23131 PackageManagerService.this.mPermissionManager.grantRuntimePermission( 23132 permName, packageName, overridePolicy, getCallingUid(), userId, 23133 mPermissionCallback); 23134 } 23135 23136 @Override 23137 public void revokeRuntimePermission(String packageName, String permName, int userId, 23138 boolean overridePolicy) { 23139 mPermissionManager.revokeRuntimePermission( 23140 permName, packageName, overridePolicy, getCallingUid(), userId, 23141 mPermissionCallback); 23142 } 23143 23144 @Override 23145 public String getNameForUid(int uid) { 23146 return PackageManagerService.this.getNameForUid(uid); 23147 } 23148 23149 @Override 23150 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23151 Intent origIntent, String resolvedType, String callingPackage, 23152 Bundle verificationBundle, int userId) { 23153 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23154 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 23155 userId); 23156 } 23157 23158 @Override 23159 public void grantEphemeralAccess(int userId, Intent intent, 23160 int targetAppId, int ephemeralAppId) { 23161 synchronized (mPackages) { 23162 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23163 targetAppId, ephemeralAppId); 23164 } 23165 } 23166 23167 @Override 23168 public boolean isInstantAppInstallerComponent(ComponentName component) { 23169 synchronized (mPackages) { 23170 return mInstantAppInstallerActivity != null 23171 && mInstantAppInstallerActivity.getComponentName().equals(component); 23172 } 23173 } 23174 23175 @Override 23176 public void pruneInstantApps() { 23177 mInstantAppRegistry.pruneInstantApps(); 23178 } 23179 23180 @Override 23181 public String getSetupWizardPackageName() { 23182 return mSetupWizardPackage; 23183 } 23184 23185 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23186 if (policy != null) { 23187 mExternalSourcesPolicy = policy; 23188 } 23189 } 23190 23191 @Override 23192 public boolean isPackagePersistent(String packageName) { 23193 synchronized (mPackages) { 23194 PackageParser.Package pkg = mPackages.get(packageName); 23195 return pkg != null 23196 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23197 | ApplicationInfo.FLAG_PERSISTENT)) == 23198 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23199 : false; 23200 } 23201 } 23202 23203 @Override 23204 public boolean isLegacySystemApp(Package pkg) { 23205 synchronized (mPackages) { 23206 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23207 return mPromoteSystemApps 23208 && ps.isSystem() 23209 && mExistingSystemPackages.contains(ps.name); 23210 } 23211 } 23212 23213 @Override 23214 public List<PackageInfo> getOverlayPackages(int userId) { 23215 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23216 synchronized (mPackages) { 23217 for (PackageParser.Package p : mPackages.values()) { 23218 if (p.mOverlayTarget != null) { 23219 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23220 if (pkg != null) { 23221 overlayPackages.add(pkg); 23222 } 23223 } 23224 } 23225 } 23226 return overlayPackages; 23227 } 23228 23229 @Override 23230 public List<String> getTargetPackageNames(int userId) { 23231 List<String> targetPackages = new ArrayList<>(); 23232 synchronized (mPackages) { 23233 for (PackageParser.Package p : mPackages.values()) { 23234 if (p.mOverlayTarget == null) { 23235 targetPackages.add(p.packageName); 23236 } 23237 } 23238 } 23239 return targetPackages; 23240 } 23241 23242 @Override 23243 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23244 @Nullable List<String> overlayPackageNames) { 23245 synchronized (mPackages) { 23246 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23247 Slog.e(TAG, "failed to find package " + targetPackageName); 23248 return false; 23249 } 23250 ArrayList<String> overlayPaths = null; 23251 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 23252 final int N = overlayPackageNames.size(); 23253 overlayPaths = new ArrayList<>(N); 23254 for (int i = 0; i < N; i++) { 23255 final String packageName = overlayPackageNames.get(i); 23256 final PackageParser.Package pkg = mPackages.get(packageName); 23257 if (pkg == null) { 23258 Slog.e(TAG, "failed to find package " + packageName); 23259 return false; 23260 } 23261 overlayPaths.add(pkg.baseCodePath); 23262 } 23263 } 23264 23265 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 23266 ps.setOverlayPaths(overlayPaths, userId); 23267 return true; 23268 } 23269 } 23270 23271 @Override 23272 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23273 int flags, int userId, boolean resolveForStart) { 23274 return resolveIntentInternal( 23275 intent, resolvedType, flags, userId, resolveForStart); 23276 } 23277 23278 @Override 23279 public ResolveInfo resolveService(Intent intent, String resolvedType, 23280 int flags, int userId, int callingUid) { 23281 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 23282 } 23283 23284 @Override 23285 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 23286 return PackageManagerService.this.resolveContentProviderInternal( 23287 name, flags, userId); 23288 } 23289 23290 @Override 23291 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23292 synchronized (mPackages) { 23293 mIsolatedOwners.put(isolatedUid, ownerUid); 23294 } 23295 } 23296 23297 @Override 23298 public void removeIsolatedUid(int isolatedUid) { 23299 synchronized (mPackages) { 23300 mIsolatedOwners.delete(isolatedUid); 23301 } 23302 } 23303 23304 @Override 23305 public int getUidTargetSdkVersion(int uid) { 23306 synchronized (mPackages) { 23307 return getUidTargetSdkVersionLockedLPr(uid); 23308 } 23309 } 23310 23311 @Override 23312 public boolean canAccessInstantApps(int callingUid, int userId) { 23313 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 23314 } 23315 23316 @Override 23317 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 23318 synchronized (mPackages) { 23319 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 23320 } 23321 } 23322 23323 @Override 23324 public void notifyPackageUse(String packageName, int reason) { 23325 synchronized (mPackages) { 23326 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 23327 } 23328 } 23329 } 23330 23331 @Override 23332 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23333 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23334 synchronized (mPackages) { 23335 final long identity = Binder.clearCallingIdentity(); 23336 try { 23337 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps( 23338 packageNames, userId); 23339 } finally { 23340 Binder.restoreCallingIdentity(identity); 23341 } 23342 } 23343 } 23344 23345 @Override 23346 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23347 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23348 synchronized (mPackages) { 23349 final long identity = Binder.clearCallingIdentity(); 23350 try { 23351 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices( 23352 packageNames, userId); 23353 } finally { 23354 Binder.restoreCallingIdentity(identity); 23355 } 23356 } 23357 } 23358 23359 private static void enforceSystemOrPhoneCaller(String tag) { 23360 int callingUid = Binder.getCallingUid(); 23361 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23362 throw new SecurityException( 23363 "Cannot call " + tag + " from UID " + callingUid); 23364 } 23365 } 23366 23367 boolean isHistoricalPackageUsageAvailable() { 23368 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23369 } 23370 23371 /** 23372 * Return a <b>copy</b> of the collection of packages known to the package manager. 23373 * @return A copy of the values of mPackages. 23374 */ 23375 Collection<PackageParser.Package> getPackages() { 23376 synchronized (mPackages) { 23377 return new ArrayList<>(mPackages.values()); 23378 } 23379 } 23380 23381 /** 23382 * Logs process start information (including base APK hash) to the security log. 23383 * @hide 23384 */ 23385 @Override 23386 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23387 String apkFile, int pid) { 23388 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23389 return; 23390 } 23391 if (!SecurityLog.isLoggingEnabled()) { 23392 return; 23393 } 23394 Bundle data = new Bundle(); 23395 data.putLong("startTimestamp", System.currentTimeMillis()); 23396 data.putString("processName", processName); 23397 data.putInt("uid", uid); 23398 data.putString("seinfo", seinfo); 23399 data.putString("apkFile", apkFile); 23400 data.putInt("pid", pid); 23401 Message msg = mProcessLoggingHandler.obtainMessage( 23402 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23403 msg.setData(data); 23404 mProcessLoggingHandler.sendMessage(msg); 23405 } 23406 23407 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23408 return mCompilerStats.getPackageStats(pkgName); 23409 } 23410 23411 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23412 return getOrCreateCompilerPackageStats(pkg.packageName); 23413 } 23414 23415 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23416 return mCompilerStats.getOrCreatePackageStats(pkgName); 23417 } 23418 23419 public void deleteCompilerPackageStats(String pkgName) { 23420 mCompilerStats.deletePackageStats(pkgName); 23421 } 23422 23423 @Override 23424 public int getInstallReason(String packageName, int userId) { 23425 final int callingUid = Binder.getCallingUid(); 23426 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23427 true /* requireFullPermission */, false /* checkShell */, 23428 "get install reason"); 23429 synchronized (mPackages) { 23430 final PackageSetting ps = mSettings.mPackages.get(packageName); 23431 if (filterAppAccessLPr(ps, callingUid, userId)) { 23432 return PackageManager.INSTALL_REASON_UNKNOWN; 23433 } 23434 if (ps != null) { 23435 return ps.getInstallReason(userId); 23436 } 23437 } 23438 return PackageManager.INSTALL_REASON_UNKNOWN; 23439 } 23440 23441 @Override 23442 public boolean canRequestPackageInstalls(String packageName, int userId) { 23443 return canRequestPackageInstallsInternal(packageName, 0, userId, 23444 true /* throwIfPermNotDeclared*/); 23445 } 23446 23447 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 23448 boolean throwIfPermNotDeclared) { 23449 int callingUid = Binder.getCallingUid(); 23450 int uid = getPackageUid(packageName, 0, userId); 23451 if (callingUid != uid && callingUid != Process.ROOT_UID 23452 && callingUid != Process.SYSTEM_UID) { 23453 throw new SecurityException( 23454 "Caller uid " + callingUid + " does not own package " + packageName); 23455 } 23456 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 23457 if (info == null) { 23458 return false; 23459 } 23460 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23461 return false; 23462 } 23463 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23464 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23465 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23466 if (throwIfPermNotDeclared) { 23467 throw new SecurityException("Need to declare " + appOpPermission 23468 + " to call this api"); 23469 } else { 23470 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 23471 return false; 23472 } 23473 } 23474 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23475 return false; 23476 } 23477 if (mExternalSourcesPolicy != null) { 23478 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23479 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23480 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23481 } 23482 } 23483 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23484 } 23485 23486 @Override 23487 public ComponentName getInstantAppResolverSettingsComponent() { 23488 return mInstantAppResolverSettingsComponent; 23489 } 23490 23491 @Override 23492 public ComponentName getInstantAppInstallerComponent() { 23493 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23494 return null; 23495 } 23496 return mInstantAppInstallerActivity == null 23497 ? null : mInstantAppInstallerActivity.getComponentName(); 23498 } 23499 23500 @Override 23501 public String getInstantAppAndroidId(String packageName, int userId) { 23502 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 23503 "getInstantAppAndroidId"); 23504 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 23505 true /* requireFullPermission */, false /* checkShell */, 23506 "getInstantAppAndroidId"); 23507 // Make sure the target is an Instant App. 23508 if (!isInstantApp(packageName, userId)) { 23509 return null; 23510 } 23511 synchronized (mPackages) { 23512 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 23513 } 23514 } 23515 23516 boolean canHaveOatDir(String packageName) { 23517 synchronized (mPackages) { 23518 PackageParser.Package p = mPackages.get(packageName); 23519 if (p == null) { 23520 return false; 23521 } 23522 return p.canHaveOatDir(); 23523 } 23524 } 23525 23526 private String getOatDir(PackageParser.Package pkg) { 23527 if (!pkg.canHaveOatDir()) { 23528 return null; 23529 } 23530 File codePath = new File(pkg.codePath); 23531 if (codePath.isDirectory()) { 23532 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 23533 } 23534 return null; 23535 } 23536 23537 void deleteOatArtifactsOfPackage(String packageName) { 23538 final String[] instructionSets; 23539 final List<String> codePaths; 23540 final String oatDir; 23541 final PackageParser.Package pkg; 23542 synchronized (mPackages) { 23543 pkg = mPackages.get(packageName); 23544 } 23545 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 23546 codePaths = pkg.getAllCodePaths(); 23547 oatDir = getOatDir(pkg); 23548 23549 for (String codePath : codePaths) { 23550 for (String isa : instructionSets) { 23551 try { 23552 mInstaller.deleteOdex(codePath, isa, oatDir); 23553 } catch (InstallerException e) { 23554 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 23555 } 23556 } 23557 } 23558 } 23559 23560 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 23561 Set<String> unusedPackages = new HashSet<>(); 23562 long currentTimeInMillis = System.currentTimeMillis(); 23563 synchronized (mPackages) { 23564 for (PackageParser.Package pkg : mPackages.values()) { 23565 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 23566 if (ps == null) { 23567 continue; 23568 } 23569 PackageDexUsage.PackageUseInfo packageUseInfo = 23570 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 23571 if (PackageManagerServiceUtils 23572 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 23573 downgradeTimeThresholdMillis, packageUseInfo, 23574 pkg.getLatestPackageUseTimeInMills(), 23575 pkg.getLatestForegroundPackageUseTimeInMills())) { 23576 unusedPackages.add(pkg.packageName); 23577 } 23578 } 23579 } 23580 return unusedPackages; 23581 } 23582} 23583 23584interface PackageSender { 23585 /** 23586 * @param userIds User IDs where the action occurred on a full application 23587 * @param instantUserIds User IDs where the action occurred on an instant application 23588 */ 23589 void sendPackageBroadcast(final String action, final String pkg, 23590 final Bundle extras, final int flags, final String targetPkg, 23591 final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds); 23592 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 23593 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds); 23594 void notifyPackageAdded(String packageName); 23595 void notifyPackageRemoved(String packageName); 23596} 23597